content stringlengths 5 1.05M |
|---|
import numpy as np
from sklearn import ensemble, tree, neural_network, svm
models = {
# https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html
"rf": {
"model": ensemble.RandomForestRegressor,
"param": {
"n_jobs": lambda: np.random.ch... |
"""
Functions for simplifying the creation of a local dask cluster.
License
-------
The code in this notebook is licensed under the Apache License,
Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). Digital Earth
Africa data is licensed under the Creative Commons by Attribution 4.0
license (https://creativecom... |
from dolfin import *
import numpy as np
from petsc4py import PETSc
class DirichletBoundary(SubDomain):
def inside(self, x, on_boundary):
return on_boundary
def build_nullspace(V, x):
"""Function to build null space for 3D elasticity"""
# Create list of vectors for null space
nullspace_basis =... |
output_formats = ('txt', 'bin', 'hex')
|
import os
import torch
import pickle
import pysmiles
import matplotlib
import numpy as np
import multiprocessing as mp
import matplotlib.pyplot as plt
from model import GNN
from openbabel import pybel
from featurizer import MolEFeaturizer
from dgl.dataloading import GraphDataLoader
from sklearn.manifold import TSNE
fro... |
# Implementation of Shell Sort algorithm in Python
def shellSort(arr):
interval = 1
# Initializes interval
while (interval < (len(arr) // 3)):
interval = (interval * 3) + 1
while (interval > 0):
for i in range(interval, len(arr)):
# Select val to be inserted
... |
from pensieve import Pensieve
from chronometry.progress import ProgressBar
from silverware import Link
def get_special_data(wikipedia, name, echo=1):
"""
:type wikipedia: .Wikipedia.Wikipedia
:type name: str
:rtype: list[Pensieve]
"""
if name == 'country_pages':
page = wikipedia.get_page(url='https://en.wikip... |
# -*- coding: utf-8 -*-
import sys, os
import datetime, time, json, time, random
import argparse
import operator
import boto.ec2
import boto.iam
import boto3
import win32com.client as win
import getpass
from utils import get_local_refs
from logsetup import logger, log_event
TASK_FOLDER = "\\Drift"
PYTHON_PATH = r"... |
# ---------------------------------------------------------
# IOU Tracker
# Copyright (c) 2017 TU Berlin, Communication Systems Group
# Licensed under The MIT License [see LICENSE for details]
# Written by Erik Bochinski
# ---------------------------------------------------------
from time import time
from util impor... |
from typing import List
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
result = [0] * (rowIndex + 1)
result[0] = 1
for i in range(1, rowIndex + 1):
for j in range(i, 0, -1):
result[j] += result[j - 1]
return resul... |
import i3
workspaces = i3.get_workspaces()
for workspace in workspaces:
if workspace['focused']:
if workspace["name"] != "1":
i3.command('move', 'container to workspace number ' + str(int(workspace["name"])-1))
else:
i3.command('move', 'container to workspace number 10')
|
import Orange
data = Orange.data.Table("lenses")
print("Attributes:", ", ".join(x.name for x in data.domain.attributes))
print("Class:", data.domain.class_var.name)
print("Data instances", len(data))
target = "soft"
print("Data instances with %s prescriptions:" % target)
atts = data.domain.attributes
for d in data:
... |
import tempfile
from pathlib import PosixPath
import pytest
from django.test import TestCase
from mock import Mock
from model_mommy import mommy
from miseq_portal.miseq_viewer.models import *
pytestmark = pytest.mark.django_db
def test_validate_sample_id():
assert validate_sample_id('BMH-2017-000001') is True
... |
from bunny_storm import RabbitMQConnectionData
def test_connection_data_creation() -> None:
# Arrange
expected_user = "user"
expected_pass = "pass"
expected_host = "8.8.8.8"
default_port = 5672
default_vhost = "/"
expected_uri = f"amqp://{expected_user}:{expected_pass}@{expected_host}:{de... |
#!/usr/bin/env python3
"""Convert person detections from the patched Darknet output to a pickle format.
The patched Darknet output is like:
Enter Image Path: /some/path1.jpg: Predicted in 0.035027 seconds.
cell phone: 12.924%
Box (LTWH): 1319,367,75,120
car: 86.035%
truck: 13.739%
Box (LTWH): 1799,345,79,47
Enter Ima... |
import numpy as np
import histoptimizer
name = 'enumerate'
def partition_generator(num_items: int, num_buckets: int) -> list:
"""
Given a number of items `num_items` and a number of buckets `num_buckets`, enumerate lists of all the possible
combinations of divider locations that partition `num_items` int... |
#encoding=utf8
import os
from wox import Wox,WoxAPI
from datetime import date
#Your class must inherit from Wox base class https://github.com/qianlifeng/Wox/blob/master/PythonHome/wox.py
#The wox class here did some works to simplify the communication between Wox and python plugin.
class Main(Wox):
... |
import xlrd
import os
import sys
# rootdir = 'D:/工作/code/electric/'
rootdir = sys.argv[1]
xlrd.Book.encoding = "gbk"
sumnum=0
filenum = 0
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isfile(path):
print('正在处理:'+path)
data... |
#!/usr/bin/env python
import sys
import subprocess
import dbus
import string
import os
import fcntl
import glib
import gobject
import dbus.service
import dbus.mainloop.glib
DBUS_NAME = 'org.openbmc.HostIpmi'
OBJ_NAME = '/org/openbmc/HostIpmi/1'
def header(seq, netfn, lun, cmd):
return (
'seq: 0x%02x\n... |
import os
import pickle
import numpy as np
import torch
import torch.nn.functional as F
from torch.optim import Adam
from torch.utils.data import DataLoader
from molgrad.net import MPNNPredictor
from molgrad.net_utils import GraphData, collate_pair
from molgrad.utils import DATA_PATH, MODELS_PATH, LOG_PATH
from molgr... |
import pytest
from sqlalchemy import or_
from galaxy_crawler.models import v1 as models
from .base import ModelTestBase, create_session, create_ns, \
create_provider, create_provider_ns, create_platform, \
create_tag, create_repository
class TestRoleModel(ModelTestBase):
def setup_method(self):
... |
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accom... |
from numpy.lib.function_base import disp
from transformers import *
import os
import torch
import json
import numpy as np
from parallel_model import MemeDialoGPT
from dataset import MODDataset, get_data
from utils import accuracy_compute, AverageMeter, meme_classify_accuracy
import torch.distributed as dist
# from ap... |
from snakeoil.demandload import demand_compile_regexp
from snakeoil.strings import pluralism as _pl
from .. import results, sources
from . import Check
demand_compile_regexp('indent_regexp', '^\t* \t+')
class _Whitespace(results.VersionResult, results.Warning):
@property
def lines_str(self):
return... |
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from extensions import celery
from app import create_... |
# Copyright 2020 OpenRCA Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Crea... |
import os
import subprocess
import pandas as pd
from utils.combine import merge_by_subject
from utils.save_data import write_csv
def add_log_k(file_trial_input, file_subjects_to_merge, path):
path_matlab_fit_k = os.path.join('data_prep', 'add_variables', 'fit_k')
path_input = os.path.join(path, file_trial_... |
import pandas as pd
import numpy as np
def email (name,receiver,file,cc,password):
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
subject = "Automated Test Mail -... |
import os
import sys
import numbers
from ..cosmology import get_ccl_cosmology, RESERVED_CCL_PARAMS
from ..loglike import compute_loglike
from ..parser_constants import FIRECROWN_RESERVED_NAMES
import numpy as np
import cosmosis
# these keys are ignored by cosmosis
RESERVED_NAMES_COSMOSIS = FIRECROWN_RESERVED_NAMES + ... |
#XXX: for a clean exit we need to import KDT first because it initializes MPI
# in any case
import kdt
import numpy
import scipy
import unittest
from mpi4py import MPI
from skylark import io
import elem
class IO_test(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(IO_test, self).__in... |
# This file is Copyright (c) 2015-2018 Florent Kermarrec <florent@enjoy-digital.fr>
# License: BSD
from migen import *
from migen.genlib.io import CRG
from litex.boards.platforms import arty
from litex.build.generic_platform import Pins, IOStandard, Misc, Subsignal, Inverted
from litex.soc.cores.uart import UARTWishb... |
''' Problem Description
Given a positive integer A, return its corresponding column title as appear in an Excel sheet.
Problem Constraints
1 <= A <= 1000000000
Input Format
First and only argument is integer A.
Output Format
Return a string, the answer to the problem.
Approach: base conversion'''
class Solution:
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""COWC datasets."""
import abc
import csv
import os
from typing import Callable, Dict, List, Optional, cast
import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image
from torch import Tensor
fr... |
import logging
from unittest import TestCase
from robot_math.types import Percent
from robot_math.types.data_packet_type import DataPacket
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG)
eq = {... |
from setuptools import setup
version = '2.5.0'
setup(
name='cbagent',
version=version,
description='Stats collectors package for Couchbase Server monitoring',
author='Couchbase',
license='Apache Software License',
packages=[
'cbagent',
'cbagent.collectors',
'cbagent.col... |
"""UseCase for showing metrics."""
import logging
from argparse import Namespace, ArgumentParser
from typing import Final, cast
import jupiter.command.command as command
from jupiter.domain.adate import ADate
from jupiter.domain.metrics.metric_key import MetricKey
from jupiter.use_cases.metrics.find import MetricFindU... |
# flake8: noqa: W403
from .base import *
DEBUG = True
|
#!/usr/bin/env python
import os
import sys
here = sys.path[0]
sys.path.insert(0, os.path.join(here, '..', '..', '..')) # root/
sys.path.insert(0, os.path.join(here, '..')) # openLbr/
sys.path.insert(0, os.path.join(here, '..', '..','eventBus','PyDispatcher-2.0.3'... |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Cookie Module
module for cookie management in webdriver
Create by Artur Spirin
https://github.com/ArturSpirin/YouTube-WebDriver-Tutorials/blob/master/Cookies.py
'''''''''''''''''''''''''''''''''''''''''''''''''''... |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
import numpy as np
from maze.msg import Maze
import astar
from scipy.spatial.transform import Rotation as R
import sys
from fixed_path_controller import Controller
class DynamicController(Controller):
"""
This controller will be able to ha... |
import logging
import os
import unittest
from src.dasicon_api import DaisyconApi
class TestDaisyconApi(unittest.TestCase):
def setUp(self):
# set up logging
logging.root.handlers = []
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s', level=logging.INFO)
loggin... |
#!/usr/bin/env python3
# pip3 install pymupdf
import fitz
import sys
import re
import os
def pdf2pic(pdf_path, output_path):
# 使用正则表达式来查找图片
checkXO = r"/Type(?= */XObject)"
checkIM = r"/Subtype(?= */Image)"
# 打开pdf
doc = fitz.open(pdf_path)
# 图片计数
imgcount = 0
lenXREF = doc._ge... |
"""
Sequence distance metrics (:mod:`skbio.sequence.distance`)
==========================================================
.. currentmodule:: skbio.sequence.distance
This module contains functions for computing distances between scikit-bio
``Sequence`` objects. These functions can be used directly or supplied to other... |
# Generated by Django 2.2.13 on 2020-08-26 17:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pipeline', '0061_regionaldistrict_oc_m_yr'),
]
operations = [
migrations.RemoveField(
model_name='censussubdivision',
... |
import argparse
import logging as log
import os
import time
import shutil
import sys
import datetime
import numpy as np
from math import ceil, floor
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.optim as optim
from torch.multiprocessing import Process
from torch.autograd import Var... |
import string
from argparse import ArgumentParser
from pathlib import Path
import pytest
from espnet2.bin.tts_inference import Text2Speech, get_parser, main
from espnet2.tasks.tts import TTSTask
def test_get_parser():
assert isinstance(get_parser(), ArgumentParser)
def test_main():
with pytest.raises(Syst... |
# coding=utf-8
try:
from src.testcase.GN_APP.case.GN_APP_REGISTER.GN_APP_REGISTER_001 import *
from src.testcase.GN_APP.case.GN_APP_REGISTER.GN_APP_REGISTER_002 import *
from src.testcase.GN_APP.case.GN_APP_REGISTER.GN_APP_REGISTER_003 import *
from src.testcase.GN_APP.case.GN_APP_REGISTER.GN_APP_REGIST... |
# -*- coding: utf-8 -*-
from .context import ENDPOINT
from .helpers import Request
# api = OKExAPI(apikey, secret)
# api.post('future_userinfo', params=None)
# api.get('userinfo', params=None)
class OKExAPI(object):
"""
基础类
"""
def __init__(self, apikey, secret):
"""
Constructor for ... |
from .book_io import *
from .character_loader import *
from .constants import *
from .parser import *
|
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
count=0
if s=="" :
return True
if t=="":
return False
for i in range (0,len(t)):
if count<len(s) and s[count]==t[i]:
count+=1
if count<len(s):
... |
def solution(n, k, l):
l = sorted(l)
day = 0
capacity = 0
consume = 0
for a in l:
if a > day:
consume += 1
capacity += 1
if capacity >= k:
capacity = 0
day += 1
return consume
numOfTests = int(input())
for i in range(n... |
"""Test suite for dataset loading code."""
from os import path
import pytest
import numpy as np
import datasets
LSP_PATH = "../datasets/lsp/lsp_dataset.zip"
LSPET_PATH = "../datasets/lspet/lspet_dataset.zip"
@pytest.mark.skipif(not path.exists(LSP_PATH), reason="Need LSP .zip")
def test_lsp():
lsp = datasets... |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2021, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# mod... |
# encoding: utf-8
'''
The system_info table and SystemInfo mapped class store runtime-editable
configuration options.
For more details, check :doc:`maintaining/configuration`.
'''
from sqlalchemy import types, Column, Table
from six import text_type
from ckan.model import meta
from ckan.model import core
from ckan.... |
import pygame as pg
import math
# Screen Surface & Constants
pg.init()
WIDTH = 1024
HEIGHT = 850
WHITE = (255,255,255)
BLACK = (0,0,0)
PINK = (200,0,100)
RED = (240,0,0)
ORANGE = (255, 153, 0)
BLUE = (0,0,255)
GREEN = (0,255,0)
LGREEN = (30,130,100)
screen = pg.display.set_mode((WIDTH,HEIGHT))
# Su... |
from psycopg2 import pool
class Database:
_connection_pool = None
@staticmethod
def initialise(**kwargs):
Database._connection_pool = pool.SimpleConnectionPool(1, 10, **kwargs)
@staticmethod
def get_connection():
return Database._connection_pool.getconn()
@staticmethod
d... |
description_short = "Interact with google contacts"
keywords = [
"google",
"contacts",
"python",
]
|
from __future__ import annotations
import json
from dbus_next import Variant
from dbus_next.aio import MessageBus
from dbus_next.introspection import Node
from .service import StatusService
notifications_xml = '''
<node>
<interface name="org.freedesktop.Notifications">
<method name="GetCapabilities">
... |
import dataclasses
import itertools
import math
from typing import Dict, Callable, List, Optional
from flwr.server.strategy import Strategy
from tensorflow_addons.utils.types import Optimizer
from sources.experiments.experiment_metadata import ExperimentMetadata
from sources.experiments.experiment_metadata_provider_u... |
from base64 import b64decode
from malwareconfig import crypto
from malwareconfig.common import Decoder
from malwareconfig.common import string_printable
class Arcom(Decoder):
decoder_name = "Arcom"
decoder__version = 1
decoder_author = "@kevthehermit"
decoder_description = "Arcom RAT Decoder"
de... |
import numpy as np
class PenalizationGrid:
def __init__(self, minCoef=1e-10, maxCoef=1, length=200):
self.values = np.linspace(maxCoef, minCoef, length).tolist()
def isEmpty(self) -> bool:
return len(self.values) == 0
def getNextKCoeffs(self, k):
penalizationCoeffsForBatch = self... |
from __future__ import print_function
from models import LipRead
import torch
import toml
from training import Trainer
from validation import Validator
print("Loading options...")
with open('options.toml', 'r') as optionsFile:
options = toml.loads(optionsFile.read())
if(options["general"]["usecudnnbenchmark"] and... |
import os
import io
import re
import datetime
import itertools
import markdown as markdown_module
import pygments.formatters
import yaml
import jinja2
import werkzeug
from flask import Flask, render_template, send_from_directory, abort, url_for
app = Flask(__name__)
app.jinja_env.undefined = jinja2.StrictUndefined
a... |
import logging
import salt.exceptions
import salt_more
from datetime import datetime
log = logging.getLogger(__name__)
def help():
"""
Shows this help information.
"""
return __salt__["sys.doc"]("power")
def status():
"""
Get status and debug information regarding power management.
"... |
from dataclasses import dataclass
from omegaconf.omegaconf import MISSING
import torch
from torch.functional import Tensor
import torch.nn as nn
import torch.nn.functional as F
from rnnms.networks.vocoder import ConfRNNMSVocoder, RNNMSVocoder
@dataclass
class ConfVocoder:
"""
Args:
size_i_codebook: S... |
from os import environ
class Config:
"""Set Flask configuration vars from .env file."""
# General Config
SECRET_KEY = environ.get('SECRET_KEY')
FLASK_APP = environ.get('FLASK_APP')
FLASK_ENV = environ.get('FLASK_ENV')
DEBUG = True
# Specific Config
MODEL_FILE = 'model.plk' |
import numpy as np
from artemis.experiments.decorators import experiment_function
from matplotlib import pyplot as plt
from six.moves import xrange
__author__ = 'peter'
"""
This file demonstates Artemis's "Experiments"
When you run an experiment, all figures and console output, as well as some metadata such as tota... |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy
de = numpy.genfromtxt("total internal energy_EDRAHT.txt")
dm = numpy.genfromtxt("forces fx,fy,fz_NROT.txt")
plt.plot(de[:,0],de[:,1],'b',dm[:,0],dm[:,3],'r')
plt.grid(True)
plt.xlim([0,1])
plt.xlabel("t")
plt.ylabel("y")
plt.legend(["Energy","Moment"]... |
# coding: utf-8
"""
pollination-server
Pollination Server OpenAPI Definition # noqa: E501
The version of the OpenAPI document: 0.16.0
Contact: info@pollination.cloud
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and... |
class Constants(object):
LOGGER_CONF = "conf/logger.yml"
USERNAME = "mapr"
PASSWORD = "mapr"
GROUPNAME = "mapr"
USERID = 5000
GROUPID = 5000
MYSQL_USER = "admin"
MYSQL_PASS = "mapr"
LDAPADMIN_USER = "admin"
LDAPADMIN_PASS = "mapr"
LDAPBIND_USER = "readonly"
LDAPBIND_PASS... |
## for data
import pandas as pd
import numpy as np
import requests
import json
import os
from datetime import datetime, date
from dotenv import load_dotenv
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
## for plotting
import matplotlib.pyplot as plt
import mat... |
# pylint: disable=missing-docstring,redefined-outer-name
import pathlib
import pytest
from tox_constraints import git_filter
@pytest.fixture
def sample():
dirpath = pathlib.Path(__file__).with_suffix("")
filepath = dirpath / "constraints.txt"
return filepath.read_text()
def test_roundtrip(sample):
... |
# Imports
from os.path import join
import matplotlib.pyplot as plt
import nibabel as nib
from nilearn import plotting
from gclda.model import Model
from gclda.decode import decode_continuous
from gclda.utils import get_resource_path
# Files to decode
f_in = '/home/data/nbc/physics-learning/data/group-level/fci/fci-p... |
from abc import ABC, abstractmethod
from typing import List, Union
import numpy as np
import torch
SOBEL_X = (
torch.tensor([[1, 0, -1], [2, 0, -2], [1, 0, -1]], dtype=torch.float).unsqueeze(0).unsqueeze(0)
)
SOBEL_Y = (
torch.tensor([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=torch.float).unsqueeze(0).unsqu... |
print('---' * 10)
print('Analisador de Triângulos')
print('---' * 10)
r1 = int(input('Primeiro valor: '))
r2 = int(input('Segundo valor: '))
r3 = int(input('Terceiro valor: '))
if r1 < r2 + 3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos acima FORMAM um triângulo')
else:
print('O... |
"""
Cookie Clicker Simulator
"""
import simpleplot
# Used to increase the timeout, if necessary
import codeskulptor
codeskulptor.set_timeout(20)
import poc_clicker_provided as provided
import math
# Constants
SIM_TIME = 10000000000.0
class ClickerState:
"""
Simple class to keep track of the game state.
... |
""" Library of submission strings
"""
from submission import substr
from submission import read_dat
__all__ = [
'substr',
'read_dat'
]
|
#!/usr/bin/env python
import logging
import sys
import unittest
import scipy as sp
import numpy as np
import mango.mpi as mpi
import mango.image
import mango.data
import mango.io
logger, rootLogger = mpi.getLoggers(__name__)
class CropTest(unittest.TestCase):
def setUp(self):
np.random.seed((mango.mpi.ran... |
from django.db import models
class Category(models.Model):
"""Model definition for Category."""
# TODO: Define fields here
name = models.CharField(max_length=50)
description = models.TextField()
products = models.ManyToManyField(
'Product', through='ProductCategory')
class Meta:
... |
import json, os
from core.models.client import Client
from discord_slash import SlashCommand
main_path = os.path.dirname(__file__)
config_path = os.path.join(main_path, "config.json")
with open(config_path, "r") as jsonfile:
config: dict = json.load(jsonfile)
if __name__ == "__main__":
Client(**config).run()... |
# -*- coding: utf-8 -*-
'''Defines file types and implements commands on files
'''
# module imports
from . import cli, get_user_context_obj, logger
from .common import *
|
## /!\ NE PAS TOUCHER NI SUPPRIMER CE FICHIER /!\ ##
import discord
from replit import db
client = discord.Client()
commands = {}
@client.event
async def on_message(message, *member: discord.User):
if message.content.split(" ")[0] in commands.keys():
code = commands[message.content.split(" ")[0]]
... |
import argparse
import pickle as pkl
import numpy as np
import tensorflow as tf
import params
import model
FLAGS = None
def remove_eos(sentence, eos = '<EOS>', pad = '<PAD>'):
if eos in sentence:
return sentence[:sentence.index(eos)] + '\n'
elif pad in sentence:
return sentence[:sentence.inde... |
import logging
import blueforge.apis.telegram as tg
import requests
from blueforge.apis.facebook import Message, ImageAttachment, QuickReply, QuickReplyTextItem
from chatbrick.util import get_items_from_xml, UNKNOWN_ERROR_MSG
import time
from blueforge.apis.facebook import TemplateAttachment, Element, GenericTemplate... |
from .persistence_provider import IPersistenceProvider
from .lock_provider import ILockProvider
from .queue_provider import IQueueProvider, EVENT_QUEUE, WORKFLOW_QUEUE
from .background_service import IBackgroundService
from .execution_pointer_factory import IExecutionPointerFactory
from .execution_result_processor impo... |
import textwrap
import sys
from datetime import datetime
HEADER = """\
from zic.classes import *
from datetime import *
"""
RAW_FILES = [
'africa', 'antarctica', 'asia', 'australasia',
'europe', 'northamerica', 'southamerica'
]
def lines(input):
"""Remove comments and empty lines"""
for raw_line... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import unittest
import os
import configparser
from pathlib import Path
from pyshex import ShExEvaluator
from pyshex.utils.schema_loader import SchemaLoader
from rdflib import Namespace
from rdflib import Graph
from rdflib.namespace import RDF
class TestDdiemRDF(unittest.TestCase):
RDF_FILE = ""
BASE = Namespa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import pandas as pd
import numpy as np
from tqdm import tqdm
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import MinMaxScaler
# Set train file names
train_queries_file = "./dataset/train_queries.csv"
train_plans_file = "./dataset/... |
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Dense
class VGGNetSmall():
def __init__(self, input... |
def cigar_party(cigars, is_weekend):
return (40<=cigars<=60 or (is_weekend and 40<=cigars))
def date_fashion(you, date):
if you <= 2 or date <= 2:
return 0
if you >= 8 or date >= 8:
return 2
else:
return 1
def squirrel_play(temp, is_summer):
if 60<=temp<=90:
return ... |
# coding=utf-8
from __future__ import unicode_literals
from collections import OrderedDict
from .. import Provider as AddressProvider
class Provider(AddressProvider):
street_suffixes = OrderedDict(
(('utca', 0.75), ('út', 0.1), ('tér', 0.1), ('köz', 0.001), ('körút', 0.001), ('sétány', 0.001),))
st... |
number = int(input("Enter number: "))
if (number >= 100 and number <= 200) or number == 0:
pass
else:
print("invalid") |
#!/usr/bin/env python3
"""
File: isc_clause_acl.py
Clause: acl
Title: Clause statement for the Access Control List
Description: Provides clause-specific aspect of ACL-related grammar
in PyParsing engine for ISC-configuration style.
Reason for separate file from isc_acl is to avoid the Pyth... |
from __future__ import division, print_function, absolute_import
import numpy as np
from ..math import gauss
from .ideal import aideal, daideal_drho, d2aideal_drho
from .association_aux import association_config
from .polarGV import aij, bij, cij
from .monomer_aux import I_lam, J_lam
from .a1sB_monomer import x0lambda_... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class ActionRunner(object):
def __init__(self, page, tab, page_test=None):
self._page = page
self._tab = tab
self._page_test = page_test
def... |
'''
Highway layers and multitask modules
Author: yichongx@cs.cmu.edu
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from allennlp.modules.elmo import Elmo, batch_to_ids
import pickle
test_outputs=False
class PositionwiseNN(nn.Module):
def __init__(s... |
"""
Create a default folder and a file structure for a
python package based on the name of the project.
"""
import os
import sys
import json
import click
def make_skeleton(project_name, template=False):
"""
Create a default structure for a python project.
"""
if template:
# load the structure... |
from header_common import *
from ID_animations import *
from header_mission_templates import *
from header_tableau_materials import *
from header_items import *
from module_constants import *
####################################################################################################################
# Each ta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.