code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import json
import warnings
from collections import namedtuple
from pathlib import Path
from ele.exceptions import ElementError
from ele.exceptions import MultiMatchError
JSON_PATH = Path.joinpath(Path(__file__).parent, "lib/elements.json")
__all__ = (
"element_from_name",
"element_from_mass",
"element_... | ele/element.py | import json
import warnings
from collections import namedtuple
from pathlib import Path
from ele.exceptions import ElementError
from ele.exceptions import MultiMatchError
JSON_PATH = Path.joinpath(Path(__file__).parent, "lib/elements.json")
__all__ = (
"element_from_name",
"element_from_mass",
"element_... | 0.886039 | 0.406479 |
import numpy
class Embeddings:
def __init__(self):
"""
Initializes the embeddings database.
"""
self.Vectors = []
self.Labels = []
def Add(self, vector, label):
"""
Adds embedding to embeddings database.
Args:
vector: Vector
... | python/faceonnx/embeddings.py | import numpy
class Embeddings:
def __init__(self):
"""
Initializes the embeddings database.
"""
self.Vectors = []
self.Labels = []
def Add(self, vector, label):
"""
Adds embedding to embeddings database.
Args:
vector: Vector
... | 0.89522 | 0.567218 |
import itertools
from typing import Tuple, Sequence, Union
from webdnn.graph.axis import Axis, AxisKeyDict
class Order:
"""Order(axes)
Descriptor class for representing semantics of data order.
For example, :obj:`~webdnn.graph.order.OrderNHWC` means that the data is aligned as Channel-major (Batch-size... | src/graph_transpiler/webdnn/graph/order.py | import itertools
from typing import Tuple, Sequence, Union
from webdnn.graph.axis import Axis, AxisKeyDict
class Order:
"""Order(axes)
Descriptor class for representing semantics of data order.
For example, :obj:`~webdnn.graph.order.OrderNHWC` means that the data is aligned as Channel-major (Batch-size... | 0.913247 | 0.673574 |
from read_data import read_all_images
from extract_haar_feature import extract_haar_feature, get_int_image
from my_adaboost_main import my_adaboost
import numpy as np
import pickle
import gl
import time
from sklearn import metrics
if __name__ == '__main__':
total_time1 = time.time()
load_trained_model = True
... | src/pipeline.py | from read_data import read_all_images
from extract_haar_feature import extract_haar_feature, get_int_image
from my_adaboost_main import my_adaboost
import numpy as np
import pickle
import gl
import time
from sklearn import metrics
if __name__ == '__main__':
total_time1 = time.time()
load_trained_model = True
... | 0.354657 | 0.226463 |
allowed_classes = [
# Exceptions
ArithmeticError, AssertionError, AttributeError, BaseException,
BlockingIOError, BrokenPipeError, BufferError, BytesWarning,
ChildProcessError, ConnectionAbortedError, ConnectionError,
ConnectionRefusedError, ConnectionResetError, DeprecationWarning, EOFError,
En... | public/plugins/Blockchain/sandboxer/scope.py | allowed_classes = [
# Exceptions
ArithmeticError, AssertionError, AttributeError, BaseException,
BlockingIOError, BrokenPipeError, BufferError, BytesWarning,
ChildProcessError, ConnectionAbortedError, ConnectionError,
ConnectionRefusedError, ConnectionResetError, DeprecationWarning, EOFError,
En... | 0.495606 | 0.119203 |
import requests
import os
import argparse
from datetime import datetime, timedelta
# Constants
BASE_URL = "http://www.madrid.org/cs/FileServlet"
def main():
parser = argparse.ArgumentParser(description='CLI to download contracts in CSV format')
parser.add_argument('--start-date', type=valid_date, default=dat... | src/etl/extract_csv.py | import requests
import os
import argparse
from datetime import datetime, timedelta
# Constants
BASE_URL = "http://www.madrid.org/cs/FileServlet"
def main():
parser = argparse.ArgumentParser(description='CLI to download contracts in CSV format')
parser.add_argument('--start-date', type=valid_date, default=dat... | 0.361277 | 0.06276 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.community.general.tests.unit.compat import unittest
from ansible_collections.manala.roles.plugins.filter.php_fpm_pools import pools, pools_section, pools_parameter
from ansible.errors import AnsibleFilterE... | tests/unit/plugins/filter/test_php_fpm_pools.py | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.community.general.tests.unit.compat import unittest
from ansible_collections.manala.roles.plugins.filter.php_fpm_pools import pools, pools_section, pools_parameter
from ansible.errors import AnsibleFilterE... | 0.786418 | 0.488588 |
from .test_utils import TestCase
import importlib
from galgebra.ga import Ga
from galgebra.mv import J, Jinv
from galgebra.generator import format_geometric_algebra, flatten, expand
class TestGenerator(TestCase):
def setUp(self):
Ga.dual_mode("Iinv+")
GA = Ga('e*1|2|3|4', g=[0, 1, 1, 1])
... | test/test_generator.py | from .test_utils import TestCase
import importlib
from galgebra.ga import Ga
from galgebra.mv import J, Jinv
from galgebra.generator import format_geometric_algebra, flatten, expand
class TestGenerator(TestCase):
def setUp(self):
Ga.dual_mode("Iinv+")
GA = Ga('e*1|2|3|4', g=[0, 1, 1, 1])
... | 0.652131 | 0.303732 |
import torch
import torch.nn as nn
from typing import Callable
class RBFLayer(nn.Module):
"""
Defines a Radial Basis Function Layer
An RBF is defined by 5 elements:
1. A radial kernel phi
2. A positive shape parameter epsilon
3. The number of kernels N, and their relative
... | rbf_layer/rbf_layer.py |
import torch
import torch.nn as nn
from typing import Callable
class RBFLayer(nn.Module):
"""
Defines a Radial Basis Function Layer
An RBF is defined by 5 elements:
1. A radial kernel phi
2. A positive shape parameter epsilon
3. The number of kernels N, and their relative
... | 0.967717 | 0.801276 |
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='recaptcha-client',
version='1.0.6',
url = "http://recaptcha.net",
author = "<NAME>",
author_email = "... | recaptcha-client-1.0.6/setup.py | try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='recaptcha-client',
version='1.0.6',
url = "http://recaptcha.net",
author = "<NAME>",
author_email = "... | 0.430626 | 0.140425 |
# Test script for testing the features...
# This script first generates the configuration files and then runs experiments
import run as r
import os, sys
from ConfigParser import SafeConfigParser
def getConfigParameters():
# print os.getcwd()
parser = SafeConfigParser()
parser.read('face-rec/config_LTP_view1... | face-rec/code/demo.py | # Test script for testing the features...
# This script first generates the configuration files and then runs experiments
import run as r
import os, sys
from ConfigParser import SafeConfigParser
def getConfigParameters():
# print os.getcwd()
parser = SafeConfigParser()
parser.read('face-rec/config_LTP_view1... | 0.136608 | 0.190649 |
import numpy as np
def generate_random_policy(env):
n_states = env.observation_space.n
n_actions = env.action_space.n
policy = np.ones([n_states, n_actions]) / n_actions
policy[0, :] = 0
policy[n_states - 1, :] = 0
return policy
def policy_evaluation(policy, env, V=None, gamma=1, theta=1e-8,... | 4. Dynamic Programming/dp.py | import numpy as np
def generate_random_policy(env):
n_states = env.observation_space.n
n_actions = env.action_space.n
policy = np.ones([n_states, n_actions]) / n_actions
policy[0, :] = 0
policy[n_states - 1, :] = 0
return policy
def policy_evaluation(policy, env, V=None, gamma=1, theta=1e-8,... | 0.623721 | 0.522507 |
import matplotlib
matplotlib.use('Agg') # set the backend before importing pyplot
import pandas as pd
import numpy as np
import pyper as pr
import rpy2.robjects as robj
from rpy2.robjects import pandas2ri
from rpy2.robjects import FloatVector as rfc
from rpy2.robjects import StrVector as rsc
from rpy2.robjects impor... | spatial_analysis_utils_v2_sh.py | import matplotlib
matplotlib.use('Agg') # set the backend before importing pyplot
import pandas as pd
import numpy as np
import pyper as pr
import rpy2.robjects as robj
from rpy2.robjects import pandas2ri
from rpy2.robjects import FloatVector as rfc
from rpy2.robjects import StrVector as rsc
from rpy2.robjects impor... | 0.50952 | 0.643553 |
from pyws.errors import ET_CLIENT
__all__ = ('Protocol', )
class Protocol(object):
"""
Abstract protocol class. Implements basic constructor, context and error
handling.
"""
def __init__(
self, context_data_getter=None, common_context_data_getter=None):
"""
Both argum... | src/pyws/protocols/base.py | from pyws.errors import ET_CLIENT
__all__ = ('Protocol', )
class Protocol(object):
"""
Abstract protocol class. Implements basic constructor, context and error
handling.
"""
def __init__(
self, context_data_getter=None, common_context_data_getter=None):
"""
Both argum... | 0.751192 | 0.254712 |
# Copyrigh 2018 <EMAIL>
# Apache 2.0.
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F... | loss.py |
# Copyrigh 2018 <EMAIL>
# Apache 2.0.
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F... | 0.529507 | 0.379005 |
import cv2
import numpy as np
from ORBFeature import ORBFeature, orb_match
from cnnmatching import cnn_match
from lib.utils import show_match
class Coarse2Fine(object):
def __init__(self, img1, img2, M):
self.img1 = img1
self.img2 = img2
self.h_mat = np.eye(3)
self.M = M
... | coarse2fine.py | import cv2
import numpy as np
from ORBFeature import ORBFeature, orb_match
from cnnmatching import cnn_match
from lib.utils import show_match
class Coarse2Fine(object):
def __init__(self, img1, img2, M):
self.img1 = img1
self.img2 = img2
self.h_mat = np.eye(3)
self.M = M
... | 0.468791 | 0.499817 |
import torch
import torch.nn as nn
import numpy as np
from hparams import HParams
try:
from .layers import LevelBlockUp, LevelBlockDown, ResidualConvCell
from ..utils.utils import one_hot, get_same_padding, compute_latent_dimension
from .conv2d import Conv2d
from ..utils.utils import scale_pixels
excep... | efficient_vdvae_torch/model/autoencoder.py | import torch
import torch.nn as nn
import numpy as np
from hparams import HParams
try:
from .layers import LevelBlockUp, LevelBlockDown, ResidualConvCell
from ..utils.utils import one_hot, get_same_padding, compute_latent_dimension
from .conv2d import Conv2d
from ..utils.utils import scale_pixels
excep... | 0.908092 | 0.298862 |
import argparse
import base64
import binascii
import os
import re
import yaml
from os import environ as env
from configparser import ConfigParser
from semantic_version import Version
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--skip-aws",
dest="aws",
ac... | .functional_ci_setup.py | import argparse
import base64
import binascii
import os
import re
import yaml
from os import environ as env
from configparser import ConfigParser
from semantic_version import Version
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--skip-aws",
dest="aws",
ac... | 0.311741 | 0.0704 |
import os, shutil
import urllib.request
uoDir = r"C:\UORenaissance" # change this to your UO:R directory
iconsSwitch = False # change to True to use 3D icons
localMapIcons = "BikrMapIcons"
if iconsSwitch:
localMapIcons = "MapIconsOld"
url = "http://www.uorenaissance.com/map/house.txt"
dataDir = os.path.join(uoDi... | UORHousePositions.py | import os, shutil
import urllib.request
uoDir = r"C:\UORenaissance" # change this to your UO:R directory
iconsSwitch = False # change to True to use 3D icons
localMapIcons = "BikrMapIcons"
if iconsSwitch:
localMapIcons = "MapIconsOld"
url = "http://www.uorenaissance.com/map/house.txt"
dataDir = os.path.join(uoDi... | 0.079353 | 0.133274 |
import ctypes
import subprocess
# pylint: disable=g-bad-import-order
import autochannel
import experiment
import utils
crypto = ctypes.CDLL('libcrypto.so')
EXPERIMENTS = [
'NoSwapWifiPrimaryChannel', # checked by hostapd itself
'NoAutoNarrowWifiChannel', # checked by hostapd itself
'Wifi80211k',
... | wifi/configs.py | import ctypes
import subprocess
# pylint: disable=g-bad-import-order
import autochannel
import experiment
import utils
crypto = ctypes.CDLL('libcrypto.so')
EXPERIMENTS = [
'NoSwapWifiPrimaryChannel', # checked by hostapd itself
'NoAutoNarrowWifiChannel', # checked by hostapd itself
'Wifi80211k',
... | 0.465873 | 0.085518 |
import urllib
import shutil
from os import listdir, makedirs, remove
from os.path import exists, join
from zipfile import ZipFile
import h5py
import numpy as np
import pandas as pd
from torch.utils.data import Dataset
from utils.pcutil import rand_rotation_matrix
all_classes = ['airplane', 'bathtub', 'bed', 'bench',... | soft_intro_vae_3d/datasets/modelnet40.py | import urllib
import shutil
from os import listdir, makedirs, remove
from os.path import exists, join
from zipfile import ZipFile
import h5py
import numpy as np
import pandas as pd
from torch.utils.data import Dataset
from utils.pcutil import rand_rotation_matrix
all_classes = ['airplane', 'bathtub', 'bed', 'bench',... | 0.585931 | 0.393443 |
from collections import OrderedDict
from datetime import date
from flask import Flask, make_response, request
import json
import selectStock_datetime # db 조회하는 함수 집합
import analysis
import datetime
app = Flask(__name__)
print('2조 파이널 프로젝트 입니다.')
@app.route("/", methods=["POST"])
def java_connection(... | src/main.py | from collections import OrderedDict
from datetime import date
from flask import Flask, make_response, request
import json
import selectStock_datetime # db 조회하는 함수 집합
import analysis
import datetime
app = Flask(__name__)
print('2조 파이널 프로젝트 입니다.')
@app.route("/", methods=["POST"])
def java_connection(... | 0.293708 | 0.186836 |
import json
import appVariables
import pymongo
from bson import json_util
class MongoManager(object):
def __init__(self):
self.conn=None
def connect(self):
result = False
try:
self.conn = pymongo.MongoClient('mongodb://localhost:27017/')
msg = "[M... | backend/Modules/mongo_db.py | import json
import appVariables
import pymongo
from bson import json_util
class MongoManager(object):
def __init__(self):
self.conn=None
def connect(self):
result = False
try:
self.conn = pymongo.MongoClient('mongodb://localhost:27017/')
msg = "[M... | 0.133754 | 0.043732 |
import storepass.model
class ListView(storepass.model.ModelVisitor):
"""View that produces a tree with one-line about each visited entry."""
def visit_root(self, root):
"""Process the database root."""
# Do nothing.
def _get_current_indent(self):
"""Obtain current indentation."""
... | storepass/cli/view.py | import storepass.model
class ListView(storepass.model.ModelVisitor):
"""View that produces a tree with one-line about each visited entry."""
def visit_root(self, root):
"""Process the database root."""
# Do nothing.
def _get_current_indent(self):
"""Obtain current indentation."""
... | 0.754101 | 0.238683 |
import argparse,logging,os,csv,subprocess
from activate import activate
from asset_downloader import downloader
from cli_space import space
from os.path import expanduser
from cli_aoi2json import aoijson
from cli_aoi2jsonb import aoijsonb
from idlist_footprint import id2footprint
from idlst import idl
import getpass
o... | planet_batch/planet_batch.py |
import argparse,logging,os,csv,subprocess
from activate import activate
from asset_downloader import downloader
from cli_space import space
from os.path import expanduser
from cli_aoi2json import aoijson
from cli_aoi2jsonb import aoijsonb
from idlist_footprint import id2footprint
from idlst import idl
import getpass
o... | 0.266548 | 0.065336 |
# Return the package information for the current version of
# Google Earth Enterprise Fusion.
import sys
import os
def EnsurePathExists(dir):
"""Make sure dir exists, create it if it does not exist."""
if not os.path.exists(dir):
os.system("mkdir -p " + dir)
def ExecEcho(command):
"""Execute and... | earth_enterprise/installer/packageUtils.py |
# Return the package information for the current version of
# Google Earth Enterprise Fusion.
import sys
import os
def EnsurePathExists(dir):
"""Make sure dir exists, create it if it does not exist."""
if not os.path.exists(dir):
os.system("mkdir -p " + dir)
def ExecEcho(command):
"""Execute and... | 0.64131 | 0.245006 |
from ciscoconfparse import CiscoConfParse
import csv
file_name = input("Enter File Name : ")
file_to_parse = CiscoConfParse(file_name, syntax='ios')
empty_dic = {}
for each_file_to_parse in file_to_parse.find_objects('^interface'):
empty_dic[each_file_to_parse.text] = []
for each_interface in empty_d... | interface_ciscoconfparse.py | from ciscoconfparse import CiscoConfParse
import csv
file_name = input("Enter File Name : ")
file_to_parse = CiscoConfParse(file_name, syntax='ios')
empty_dic = {}
for each_file_to_parse in file_to_parse.find_objects('^interface'):
empty_dic[each_file_to_parse.text] = []
for each_interface in empty_d... | 0.119216 | 0.190009 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
import numpy as np
from torch.nn.utils import weight_norm
import pickle
import sys
from termcolor import colored
from modules.hierarchical_embedding import HierarchicalEmbedding
from modules.embeddings import LearnableEmbedding... | src/graph_transformer.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
import numpy as np
from torch.nn.utils import weight_norm
import pickle
import sys
from termcolor import colored
from modules.hierarchical_embedding import HierarchicalEmbedding
from modules.embeddings import LearnableEmbedding... | 0.811676 | 0.393239 |
import jismesh.utils as ju
import numpy as np
import time
import csv
def getTimestamps(fileName):
last_tid = ''
D = []
with open(fileName, "r") as rf:
reader = csv.reader(rf)
for line in reader:
tid = line[0]
if last_tid != '' and last_tid != tid:
... | meshdynamic/jismesh_mobmap.py | import jismesh.utils as ju
import numpy as np
import time
import csv
def getTimestamps(fileName):
last_tid = ''
D = []
with open(fileName, "r") as rf:
reader = csv.reader(rf)
for line in reader:
tid = line[0]
if last_tid != '' and last_tid != tid:
... | 0.239083 | 0.184565 |
from flask import Flask, render_template, request, escape
from lsearch import search_for_letters
import mysql.connector
app = Flask(__name__)
def log_request(req: 'flask_request', res: str) -> None:
"""Log details of the web request and the results."""
dbconfig = {'host': '127.0.0.1',
'user':... | head_first_v2/web_server/hello_flask.py | from flask import Flask, render_template, request, escape
from lsearch import search_for_letters
import mysql.connector
app = Flask(__name__)
def log_request(req: 'flask_request', res: str) -> None:
"""Log details of the web request and the results."""
dbconfig = {'host': '127.0.0.1',
'user':... | 0.524395 | 0.074332 |
import torch
from torch import nn
from torchts.nn.model import TimeSeriesModel
class Encoder(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers, dropout_rate):
"""
Args:
input_dim: the dimension of input sequences.
hidden_dim: number hidden units.
... | torchts/nn/models/seq2seq.py | import torch
from torch import nn
from torchts.nn.model import TimeSeriesModel
class Encoder(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers, dropout_rate):
"""
Args:
input_dim: the dimension of input sequences.
hidden_dim: number hidden units.
... | 0.964397 | 0.5867 |
from io import StringIO
import pyjion
def test_single_yield():
def gen():
x = 1
yield x
g = gen()
assert next(g) == 1
assert not pyjion.info(gen).failed
def test_double_yield():
def gen():
x = 1
yield x
yield 2
g = gen()
assert next(g) == 1
a... | Tests/test_generators.py | from io import StringIO
import pyjion
def test_single_yield():
def gen():
x = 1
yield x
g = gen()
assert next(g) == 1
assert not pyjion.info(gen).failed
def test_double_yield():
def gen():
x = 1
yield x
yield 2
g = gen()
assert next(g) == 1
a... | 0.539954 | 0.65839 |
import logging
from threading import RLock, Thread
from time import sleep
from typing import Any, Callable, Dict, List, Optional
from . import bf_codecs, bf_errors
from .stubs.zone_statuses import ZONE_STATUS_STREAM_TYPE, ZONE_STATUS_TYPE
class StatusReceiver:
"""A simple wrapper around API.get_zone_status_strea... | brainframe/api/status_receiver.py | import logging
from threading import RLock, Thread
from time import sleep
from typing import Any, Callable, Dict, List, Optional
from . import bf_codecs, bf_errors
from .stubs.zone_statuses import ZONE_STATUS_STREAM_TYPE, ZONE_STATUS_TYPE
class StatusReceiver:
"""A simple wrapper around API.get_zone_status_strea... | 0.871215 | 0.208501 |
import bpy
from bpy.types import Operator
from bl_ui_label import *
from bl_ui_button import *
from bl_ui_checkbox import *
from bl_ui_slider import *
from bl_ui_up_down import *
from bl_ui_drag_panel import *
from bl_ui_draw_op import *
class DP_OT_draw_operator(BL_UI_OT_draw_operator):
bl_idname = "o... | src/drag_panel_op.py | import bpy
from bpy.types import Operator
from bl_ui_label import *
from bl_ui_button import *
from bl_ui_checkbox import *
from bl_ui_slider import *
from bl_ui_up_down import *
from bl_ui_drag_panel import *
from bl_ui_draw_op import *
class DP_OT_draw_operator(BL_UI_OT_draw_operator):
bl_idname = "o... | 0.354992 | 0.08886 |
from torch.distributions import Categorical
from models.GAN.generator_base import GeneratorBase
from utils.data_prep import *
from utils.logger import *
import time
class GeneratorRlStrat(GeneratorBase):
def __init__(self, vocabulary, encoder, decoder, encoder_optimizer, decoder_optimizer, mle_criterion,
... | models/GAN/generator_rl_strat.py | from torch.distributions import Categorical
from models.GAN.generator_base import GeneratorBase
from utils.data_prep import *
from utils.logger import *
import time
class GeneratorRlStrat(GeneratorBase):
def __init__(self, vocabulary, encoder, decoder, encoder_optimizer, decoder_optimizer, mle_criterion,
... | 0.71413 | 0.20347 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Compute the derivative dq from an array of consecutive points q with initial
# derivative dq0 with timestep d
def deriv(q,d=0.001):
dq = (q[1:len(q),:]-q[0:(len(q)-1),:])/d
return dq
# Differential equation of Lorenz ... | 6.5-Lorenz/Lorenz.py | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Compute the derivative dq from an array of consecutive points q with initial
# derivative dq0 with timestep d
def deriv(q,d=0.001):
dq = (q[1:len(q),:]-q[0:(len(q)-1),:])/d
return dq
# Differential equation of Lorenz ... | 0.744749 | 0.744587 |
import logging
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Optional, Type, TypeVar
from thenewboston_node.business_logic.models import AccountState
from thenewboston_node.business_logic.models.base import BaseDataclass
from thenewboston_node.business_logic.models.mixi... | thenewboston_node/business_logic/models/blockchain_state_message.py | import logging
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Optional, Type, TypeVar
from thenewboston_node.business_logic.models import AccountState
from thenewboston_node.business_logic.models.base import BaseDataclass
from thenewboston_node.business_logic.models.mixi... | 0.625781 | 0.383757 |
"""Plug-in to collect information about the Windows timezone settings."""
from plaso.events import windows_events
from plaso.parsers import winreg
from plaso.parsers.winreg_plugins import interface
__author__ = '<NAME> (<EMAIL>)'
class WinRegTimezonePlugin(interface.WindowsRegistryPlugin):
"""Plug-in to collect ... | plaso/parsers/winreg_plugins/timezone.py | """Plug-in to collect information about the Windows timezone settings."""
from plaso.events import windows_events
from plaso.parsers import winreg
from plaso.parsers.winreg_plugins import interface
__author__ = '<NAME> (<EMAIL>)'
class WinRegTimezonePlugin(interface.WindowsRegistryPlugin):
"""Plug-in to collect ... | 0.892393 | 0.257765 |
# Author: NetworkRanger
# Date: 2018/11/4 下午12:40
# 2.9 TensorFlow 实现模型评估
# 1. 加载所需的编程库,创建计算图、数据集、变量和占位符
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
sess = tf.Session()
x_vals = np.random.normal(1, 0.1, 100)
y_vals = np.repeat(10., 100)
x_data = tf.placeholder(shape=[None, 1], dtype=tf... | chapter02/demo_2.9.py |
# Author: NetworkRanger
# Date: 2018/11/4 下午12:40
# 2.9 TensorFlow 实现模型评估
# 1. 加载所需的编程库,创建计算图、数据集、变量和占位符
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
sess = tf.Session()
x_vals = np.random.normal(1, 0.1, 100)
y_vals = np.repeat(10., 100)
x_data = tf.placeholder(shape=[None, 1], dtype=tf... | 0.570092 | 0.66575 |
import math
import numpy as np
from .Bus import Bus
class Branch:
def __init__(self, data : np.ndarray = None) -> None:
if data is None :
self._fbus = None
self._tbus = None
self._r = None
self._x = None
self._b = None
self._rateA = N... | PGSimulator/persistent/Branch.py | import math
import numpy as np
from .Bus import Bus
class Branch:
def __init__(self, data : np.ndarray = None) -> None:
if data is None :
self._fbus = None
self._tbus = None
self._r = None
self._x = None
self._b = None
self._rateA = N... | 0.299208 | 0.375163 |
import numpy as np
from tools import gauss, gauss2
from math import sqrt, pi
from markov_chain import simu_mc, simu_mc_nonstat, calc_probaprio_mc
def forward_neigh(A, p, gauss, g2, g3):
"""
Cette fonction calcule récursivement (mais ce n'est pas une fonction récursive!) les valeurs forward de la chaîne
:pa... | markov_chain_neigh.py | import numpy as np
from tools import gauss, gauss2
from math import sqrt, pi
from markov_chain import simu_mc, simu_mc_nonstat, calc_probaprio_mc
def forward_neigh(A, p, gauss, g2, g3):
"""
Cette fonction calcule récursivement (mais ce n'est pas une fonction récursive!) les valeurs forward de la chaîne
:pa... | 0.658637 | 0.768081 |
import unittest
import tempfile
import os
from FMMC import SDFWriter
class TestSDFWriter(unittest.TestCase):
def test_basics(self):
# Get a new temporary directory for each test in this class
tempdir = tempfile.mkdtemp()
# Assert that it's empty
self.assertEqual(0, len(os.... | tests/test_sdfwriter.py | import unittest
import tempfile
import os
from FMMC import SDFWriter
class TestSDFWriter(unittest.TestCase):
def test_basics(self):
# Get a new temporary directory for each test in this class
tempdir = tempfile.mkdtemp()
# Assert that it's empty
self.assertEqual(0, len(os.... | 0.325628 | 0.391435 |
import random
import threading
import time
from controller.framework.CFx import CFX
from controller.framework.ControllerModule import ControllerModule
from controller.modules.NetworkBuilder import NetworkBuilder
from controller.modules.GraphBuilder import GraphBuilder
class Topology(ControllerModule, CFX):
def __... | controller/modules/Topology.py | import random
import threading
import time
from controller.framework.CFx import CFX
from controller.framework.ControllerModule import ControllerModule
from controller.modules.NetworkBuilder import NetworkBuilder
from controller.modules.GraphBuilder import GraphBuilder
class Topology(ControllerModule, CFX):
def __... | 0.323273 | 0.070304 |
import nltk
import numpy as np
import os
import pickle
import torch
import torch.utils.data as data
from multi_vocab import Vocabulary
class PrecompMultiDataset(data.Dataset):
def __init__(self, data_path, data_split, langs, vocab,
load_img=True, img_dim=2048, cn_seg = True):
self.vocab = ... | srcMutiLang/multi_data.py | import nltk
import numpy as np
import os
import pickle
import torch
import torch.utils.data as data
from multi_vocab import Vocabulary
class PrecompMultiDataset(data.Dataset):
def __init__(self, data_path, data_split, langs, vocab,
load_img=True, img_dim=2048, cn_seg = True):
self.vocab = ... | 0.254694 | 0.275643 |
import logging
from bs4 import BeautifulSoup
import voluptuous as vol
from datetime import timedelta
from homeassistant.components.rest.data import RestData
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
CONF_NAME,
PERCENTAGE,
)
from homeassistant.e... | custom_components/fitx/sensor.py | import logging
from bs4 import BeautifulSoup
import voluptuous as vol
from datetime import timedelta
from homeassistant.components.rest.data import RestData
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
CONF_NAME,
PERCENTAGE,
)
from homeassistant.e... | 0.680242 | 0.149252 |
import logging
import urllib.parse
from datetime import timezone
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
import dateutil.parser
import twitter
from nefelibata.announcers import Announcer
from nefelibata.announcers import Response
from nefelibata.post import Post... | src/nefelibata/announcers/twitter.py | import logging
import urllib.parse
from datetime import timezone
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
import dateutil.parser
import twitter
from nefelibata.announcers import Announcer
from nefelibata.announcers import Response
from nefelibata.post import Post... | 0.697712 | 0.173253 |
def estimator(data):
""" Provide the estimate calulations based on that data received """
#Collect required data from data imput
impact = {}
severeImpact = {}
reportedCases = data['reportedCases']
periodType = data['periodType']
timeToElapse = data['timeToElapse']
totalHospitalBeds = data['totalHospital... | src/estimator.py | def estimator(data):
""" Provide the estimate calulations based on that data received """
#Collect required data from data imput
impact = {}
severeImpact = {}
reportedCases = data['reportedCases']
periodType = data['periodType']
timeToElapse = data['timeToElapse']
totalHospitalBeds = data['totalHospital... | 0.433502 | 0.548915 |
import numpy
from itertools import count
from ratracer.utils import normalize, TOLERANCE, vec3d
_SHADOWING_INDENT = TOLERANCE
_SHADOWING_INDENT_INV = 1 - _SHADOWING_INDENT
_NO_INTERSECTION = numpy.nan, numpy.nan
class Identifiable:
""" A class that intended to be subclassed to provide a brief id. """
_id_gen = c... | ratracer/shape.py | import numpy
from itertools import count
from ratracer.utils import normalize, TOLERANCE, vec3d
_SHADOWING_INDENT = TOLERANCE
_SHADOWING_INDENT_INV = 1 - _SHADOWING_INDENT
_NO_INTERSECTION = numpy.nan, numpy.nan
class Identifiable:
""" A class that intended to be subclassed to provide a brief id. """
_id_gen = c... | 0.907471 | 0.445952 |
import os
import csv
import math
import random
import numpy as np
from copy import deepcopy
from operator import itemgetter
import warnings
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch_geometric.data import Dataset, DataLoader
from torch_geometric.data import Data as PyG_Data
import ... | auglichem/molecule/data/_molecule_dataset.py | import os
import csv
import math
import random
import numpy as np
from copy import deepcopy
from operator import itemgetter
import warnings
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch_geometric.data import Dataset, DataLoader
from torch_geometric.data import Data as PyG_Data
import ... | 0.365004 | 0.265958 |
from __future__ import print_function
import time
import datetime
import os
import sys
import yaml
import numpy as np
import pandas as pd
import influxdb
import libtiepie
parent_path = os.path.abspath(os.path.join(
os.path.abspath(os.path.join(
os.path.realpath(__file__),os.pardir)),
os.pardir))
conf... | tests/power_test.py |
from __future__ import print_function
import time
import datetime
import os
import sys
import yaml
import numpy as np
import pandas as pd
import influxdb
import libtiepie
parent_path = os.path.abspath(os.path.join(
os.path.abspath(os.path.join(
os.path.realpath(__file__),os.pardir)),
os.pardir))
conf... | 0.273963 | 0.113826 |
import argparse
import os
import numpy as np
import autosklearn
import autosklearn.data
import autosklearn.data.competition_data_manager
from autosklearn.pipeline.classification import SimpleClassificationPipeline
parser = argparse.ArgumentParser()
parser.add_argument('input')
parser.add_argument('output')
args = pa... | 003_jannis.py | import argparse
import os
import numpy as np
import autosklearn
import autosklearn.data
import autosklearn.data.competition_data_manager
from autosklearn.pipeline.classification import SimpleClassificationPipeline
parser = argparse.ArgumentParser()
parser.add_argument('input')
parser.add_argument('output')
args = pa... | 0.530236 | 0.143758 |
import os
'''
Python 文件I/O
本章只讲述所有基本的的I/O函数,更多函数请参考Python标准文档。
打印到屏幕
最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式
'''
print "Python 是一个非常棒的语言,不是吗?"
'''
读取键盘输入
Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘
raw_input函数
raw_input([prompt]) 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符)
'''
# str = raw_input("请输入:")
# print "你输入的内容是: ", str
... | 16.py | import os
'''
Python 文件I/O
本章只讲述所有基本的的I/O函数,更多函数请参考Python标准文档。
打印到屏幕
最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式
'''
print "Python 是一个非常棒的语言,不是吗?"
'''
读取键盘输入
Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘
raw_input函数
raw_input([prompt]) 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符)
'''
# str = raw_input("请输入:")
# print "你输入的内容是: ", str
... | 0.085566 | 0.468243 |
import os
import glob
from pathlib import Path
from .textgrid_utils import build_hashtable_textgrid, get_textgrid_sa
import soundfile as sf
import numpy as np
def hash_librispeech(librispeech_traintest):
hashtab = {}
utterances = glob.glob(os.path.join(librispeech_traintest, "**/*.wav"), recursive=True)
... | scripts/utils/librispeech_utils.py | import os
import glob
from pathlib import Path
from .textgrid_utils import build_hashtable_textgrid, get_textgrid_sa
import soundfile as sf
import numpy as np
def hash_librispeech(librispeech_traintest):
hashtab = {}
utterances = glob.glob(os.path.join(librispeech_traintest, "**/*.wav"), recursive=True)
... | 0.236957 | 0.386821 |
name = "Kato"#переменная глобальная, она определена вне любой из функций и доступна любой функции в программе.
def say_hi():
print("Hello", name)
def say_bye():#плохой ли это тон - не оставлять строк между функциями или циклами в одном блоке кода, если он связан смыслом?
print("Good bye", name)
say_hi()
s... | way/python/first_steps/metanit/metanit2_9.py | name = "Kato"#переменная глобальная, она определена вне любой из функций и доступна любой функции в программе.
def say_hi():
print("Hello", name)
def say_bye():#плохой ли это тон - не оставлять строк между функциями или циклами в одном блоке кода, если он связан смыслом?
print("Good bye", name)
say_hi()
s... | 0.035637 | 0.487246 |
import sys
import argparse
import pkg_resources
from playback import __version__
def get_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='OpenStack provisioning and orchestration library with command-line tools'
)
parser.add... | playback/cli/cli.py | import sys
import argparse
import pkg_resources
from playback import __version__
def get_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='OpenStack provisioning and orchestration library with command-line tools'
)
parser.add... | 0.225076 | 0.0559 |
import logging
import codecs
import re
from sortedcontainers import SortedSet
from dse.cqlengine import columns
from dse.cqlengine.models import Model
from dse import ConsistencyLevel
from nltk.corpus import stopwords
class SearchVideo():
def __init__(self, user_id, added_date, video_id, name, preview_image_locat... | killrvideo/search/search_service.py | import logging
import codecs
import re
from sortedcontainers import SortedSet
from dse.cqlengine import columns
from dse.cqlengine.models import Model
from dse import ConsistencyLevel
from nltk.corpus import stopwords
class SearchVideo():
def __init__(self, user_id, added_date, video_id, name, preview_image_locat... | 0.55266 | 0.139016 |
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.graph_objs import Layout
from tqdm import tqdm
from ..utils import STATUS_ARROW
_LAYOUT = Layout(
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='r... | Probe/probe/analyzer/features.py | from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.graph_objs import Layout
from tqdm import tqdm
from ..utils import STATUS_ARROW
_LAYOUT = Layout(
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='r... | 0.596668 | 0.269509 |
from flask_wtf import FlaskForm
from wtforms import RadioField, StringField, FormField
from wtforms.validators import DataRequired, URL, InputRequired, EqualTo
from wtforms.widgets import PasswordInput
from .helpers import password_requirement_check, RequiredIfFieldEqualTo
from .postgres import PostgresForm
class J... | pygluu/kubernetes/gui/forms/jackrabbit.py | from flask_wtf import FlaskForm
from wtforms import RadioField, StringField, FormField
from wtforms.validators import DataRequired, URL, InputRequired, EqualTo
from wtforms.widgets import PasswordInput
from .helpers import password_requirement_check, RequiredIfFieldEqualTo
from .postgres import PostgresForm
class J... | 0.501953 | 0.213685 |
from django.db import migrations, models
import django.db.models.deletion
import labour.models.signup_extras
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0023_auto_20160704_2155'),
]
operations = [
migrations.CreateModel(
name='Night... | events/kawacon2017/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
import labour.models.signup_extras
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0023_auto_20160704_2155'),
]
operations = [
migrations.CreateModel(
name='Night... | 0.453746 | 0.166641 |
import reversion
from django.db import models
from django.urls import reverse_lazy
# Create your models here.
@reversion.register()
class Problem(models.Model):
id = models.AutoField(primary_key=True)
puid = models.CharField(
max_length=24,
help_text="Unique problem identifier, as printed in OTIS handout.",
u... | arch/models.py | import reversion
from django.db import models
from django.urls import reverse_lazy
# Create your models here.
@reversion.register()
class Problem(models.Model):
id = models.AutoField(primary_key=True)
puid = models.CharField(
max_length=24,
help_text="Unique problem identifier, as printed in OTIS handout.",
u... | 0.535827 | 0.173009 |
import torch
import torch.nn as nn
import numpy as np
from torch import optim
import math
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
gamma = 0.99
class Environment():
def __init__(self):
self.a = 1.232
self.b = 1.545
self.prev = np.... | ToyProblems/add_two_value_(Q-Learning).py | import torch
import torch.nn as nn
import numpy as np
from torch import optim
import math
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
gamma = 0.99
class Environment():
def __init__(self):
self.a = 1.232
self.b = 1.545
self.prev = np.... | 0.818011 | 0.521654 |
from math import pi, log
from itertools import accumulate
from typing import Union, List
import numpy as np
import torch as th
from torch import nn
import torch.nn.functional as F
from scipy.signal import lfilter
from ail.common.utils import zip_strict
LOG2PI = log(2 * pi)
def pure_discount_cumsum(x: Union[list, ... | ail/common/math.py | from math import pi, log
from itertools import accumulate
from typing import Union, List
import numpy as np
import torch as th
from torch import nn
import torch.nn.functional as F
from scipy.signal import lfilter
from ail.common.utils import zip_strict
LOG2PI = log(2 * pi)
def pure_discount_cumsum(x: Union[list, ... | 0.891129 | 0.675513 |
import functools
import json
import random
import string
import threading
from dataclasses import make_dataclass
import pika
import pika.exceptions
import urlpath
from cortex.utils.logging import get_logger, get_module_logger, log_exception
LOGGER = get_module_logger(__file__)
SCHEME = 'rabbitmq'
def get_consumer... | cortex/utils/dispatchers/rabbit_consumer.py |
import functools
import json
import random
import string
import threading
from dataclasses import make_dataclass
import pika
import pika.exceptions
import urlpath
from cortex.utils.logging import get_logger, get_module_logger, log_exception
LOGGER = get_module_logger(__file__)
SCHEME = 'rabbitmq'
def get_consumer... | 0.607314 | 0.122891 |
from pathlib import Path
from unittest import mock
import pytest
from pytest_cases import THIS_MODULE, parametrize_with_cases
from statue.configuration import Configuration
from statue.constants import (
ADD_ARGS,
ARGS,
CLEAR_ARGS,
COMMANDS,
CONTEXTS,
HELP,
OVERRIDE,
SOURCES,
STATU... | tests/configuration/test_load_configuration.py | from pathlib import Path
from unittest import mock
import pytest
from pytest_cases import THIS_MODULE, parametrize_with_cases
from statue.configuration import Configuration
from statue.constants import (
ADD_ARGS,
ARGS,
CLEAR_ARGS,
COMMANDS,
CONTEXTS,
HELP,
OVERRIDE,
SOURCES,
STATU... | 0.563618 | 0.267387 |
from unittest.mock import Mock
import numpy as np
from miplearn import PrimalSolutionComponent
from miplearn.classifiers import Classifier
from miplearn.tests import get_test_pyomo_instances
def test_predict():
instances, models = get_test_pyomo_instances()
comp = PrimalSolutionComponent()
comp.fit(inst... | miplearn/components/tests/test_primal.py |
from unittest.mock import Mock
import numpy as np
from miplearn import PrimalSolutionComponent
from miplearn.classifiers import Classifier
from miplearn.tests import get_test_pyomo_instances
def test_predict():
instances, models = get_test_pyomo_instances()
comp = PrimalSolutionComponent()
comp.fit(inst... | 0.799873 | 0.776708 |
from abc import ABCMeta
from abc import abstractmethod
from collections import defaultdict
__all__ = ['BaseBackend', 'BaseVersion', 'BaseVnode']
class BaseBackend(metaclass=ABCMeta):
""" Abstract base class for persistence backends
Timetree's general goal is to express persistent data structures:
struct... | src/timetree/backend/base.py | from abc import ABCMeta
from abc import abstractmethod
from collections import defaultdict
__all__ = ['BaseBackend', 'BaseVersion', 'BaseVnode']
class BaseBackend(metaclass=ABCMeta):
""" Abstract base class for persistence backends
Timetree's general goal is to express persistent data structures:
struct... | 0.889307 | 0.561275 |
import sys
import shutil
from rectpack import newPacker
from configparser import ConfigParser
from pathlib import Path
def main() -> int:
packer = newPacker()
plateconfig = ConfigParser()
autoplate_ini = ConfigParser()
try:
plateconfig.read('.plateconfig')
plate_size_x = float(platecon... | scripts/autoplate/__main__.py | import sys
import shutil
from rectpack import newPacker
from configparser import ConfigParser
from pathlib import Path
def main() -> int:
packer = newPacker()
plateconfig = ConfigParser()
autoplate_ini = ConfigParser()
try:
plateconfig.read('.plateconfig')
plate_size_x = float(platecon... | 0.429669 | 0.164449 |
import Queue
import RPi.GPIO as GPIO
import threading
import time
class Channel(threading.Thread):
def __init__(self, pulse_pin, dir_pin, base_pulse_period = 0.001, steps_finished_callback = False, backwards_orientation = False):
threading.Thread.__init__(self)
self.queue = Queue.Queue()
se... | adapters/Actuators/stepper_pulses_general.py | import Queue
import RPi.GPIO as GPIO
import threading
import time
class Channel(threading.Thread):
def __init__(self, pulse_pin, dir_pin, base_pulse_period = 0.001, steps_finished_callback = False, backwards_orientation = False):
threading.Thread.__init__(self)
self.queue = Queue.Queue()
se... | 0.379838 | 0.201754 |
import os
import sys
import subprocess
from argparse import Namespace, ArgumentParser
import glob
import numpy as np
import re
import datetime as dt
import time
import uuid
from netCDF4 import Dataset, date2num
import pyproj
from osgeo import osr, gdal
import logging
home = os.path.expanduser("~")
print("Home director... | utils/convert_gtiff.py | import os
import sys
import subprocess
from argparse import Namespace, ArgumentParser
import glob
import numpy as np
import re
import datetime as dt
import time
import uuid
from netCDF4 import Dataset, date2num
import pyproj
from osgeo import osr, gdal
import logging
home = os.path.expanduser("~")
print("Home director... | 0.478041 | 0.225672 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from utils.losses import AMSoftmax, Softmax
class SelfAttention(nn.Module):
def __init__(self, hidden_size):
super(SelfAttention, self).__init__()
#self.output_size = output_size
self.hidden_size = hidden_size
sel... | asv/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from utils.losses import AMSoftmax, Softmax
class SelfAttention(nn.Module):
def __init__(self, hidden_size):
super(SelfAttention, self).__init__()
#self.output_size = output_size
self.hidden_size = hidden_size
sel... | 0.958207 | 0.594345 |
from paddle.trainer.config_parser import *
__all__ = ['ParamAttr', 'ExtraAttr', 'ParameterAttribute',
'ExtraLayerAttribute']
class ParameterAttribute(object):
"""
Parameter Attributes object. To fine-tuning network training process, user
can set attribute to control training details, such as l... | python/paddle/trainer_config_helpers/attrs.py |
from paddle.trainer.config_parser import *
__all__ = ['ParamAttr', 'ExtraAttr', 'ParameterAttribute',
'ExtraLayerAttribute']
class ParameterAttribute(object):
"""
Parameter Attributes object. To fine-tuning network training process, user
can set attribute to control training details, such as l... | 0.848596 | 0.561816 |
from os import environ
from flask import Flask
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import redirect
from flask import url_for
import os
from PIL import Image, ImageFont, ImageDraw
app = Flask(__name__)
app.config['ROOT_DIR'] = os.path.dirname(... | cc.py | from os import environ
from flask import Flask
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import redirect
from flask import url_for
import os
from PIL import Image, ImageFont, ImageDraw
app = Flask(__name__)
app.config['ROOT_DIR'] = os.path.dirname(... | 0.345657 | 0.058993 |
# v 0.0.4 Tlek
import random
import datetime
import sys
from libs import respond
from libs import sql_query as sql
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import KeyboardButton, ReplyKeyboardMarkup
token = str(sys.argv[1])
respond.token = token
updater = Updater(token... | bot.py |
# v 0.0.4 Tlek
import random
import datetime
import sys
from libs import respond
from libs import sql_query as sql
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import KeyboardButton, ReplyKeyboardMarkup
token = str(sys.argv[1])
respond.token = token
updater = Updater(token... | 0.093093 | 0.101233 |
import argparse
import nltk
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from tqdm import tqdm
def lemmatize(words):
lemmatizer = WordNetLemmatizer()
maps = {"J": wordnet.ADJ, "N": wordnet.NOUN, "V": wordnet.VERB, "R": wordnet.ADV}
return [lemmatizer.lemmatize(w, maps[p[0].upp... | scripts/prop2conllu.py |
import argparse
import nltk
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from tqdm import tqdm
def lemmatize(words):
lemmatizer = WordNetLemmatizer()
maps = {"J": wordnet.ADJ, "N": wordnet.NOUN, "V": wordnet.VERB, "R": wordnet.ADV}
return [lemmatizer.lemmatize(w, maps[p[0].upp... | 0.373533 | 0.215929 |
import six
import random as rnd
from bpe import BpePair, PAR_CHILD_PAIR, ORD_PAIR, UNORD_PAIR
TOK_WORD = '<?>'
SKP_WORD = '<sk>'
RIG_WORD = '<]>'
SKIP_OP_LIST = ['lambda', 'exists', 'argmin', 'argmax',
'min', 'max', 'count', 'sum', 'the']
class STree(object):
def __init__(self, in... | logical/tree.py | import six
import random as rnd
from bpe import BpePair, PAR_CHILD_PAIR, ORD_PAIR, UNORD_PAIR
TOK_WORD = '<?>'
SKP_WORD = '<sk>'
RIG_WORD = '<]>'
SKIP_OP_LIST = ['lambda', 'exists', 'argmin', 'argmax',
'min', 'max', 'count', 'sum', 'the']
class STree(object):
def __init__(self, in... | 0.14439 | 0.143038 |
import lsst.pipe.base as pipeBase
import lsst.pipe.base.connectionTypes as cT
from lsst.ip.isr import Defects
from .eoCalibBase import EoDetRunCalibTaskConfig, EoDetRunCalibTaskConnections, EoDetRunCalibTask
__all__ = ["EoDefectsTaskConfig", "EoDefectsTask"]
class EoDefectsTaskConnections(EoDetRunCalibTaskConnect... | python/lsst/eotask_gen3/eoDefects.py | import lsst.pipe.base as pipeBase
import lsst.pipe.base.connectionTypes as cT
from lsst.ip.isr import Defects
from .eoCalibBase import EoDetRunCalibTaskConfig, EoDetRunCalibTaskConnections, EoDetRunCalibTask
__all__ = ["EoDefectsTaskConfig", "EoDefectsTask"]
class EoDefectsTaskConnections(EoDetRunCalibTaskConnect... | 0.647575 | 0.272563 |
import numpy as np
import re
from collections import OrderedDict
def get_info_tags(vcf):
"""Get info tags from a vcf file
Args:
vcf: cyvcf2.VCF object
Returns:
a list of ids's
"""
return [x for x in vcf.header_iter()
if x['HeaderType'] == 'INFO']
def get_info_ids(info_tag... | kipoi_veff/parsers.py | import numpy as np
import re
from collections import OrderedDict
def get_info_tags(vcf):
"""Get info tags from a vcf file
Args:
vcf: cyvcf2.VCF object
Returns:
a list of ids's
"""
return [x for x in vcf.header_iter()
if x['HeaderType'] == 'INFO']
def get_info_ids(info_tag... | 0.584153 | 0.738422 |
from decouple import config
from dotenv import load_dotenv
from flask import Flask, render_template, request
from .models import DB, Tweet, User
from .twitter import add_or_update_user
from .predict import predict_user
load_dotenv()
#Now we make the app factory
def create_app():
"""Create and configure an instan... | twitoff/app.py |
from decouple import config
from dotenv import load_dotenv
from flask import Flask, render_template, request
from .models import DB, Tweet, User
from .twitter import add_or_update_user
from .predict import predict_user
load_dotenv()
#Now we make the app factory
def create_app():
"""Create and configure an instan... | 0.339061 | 0.072999 |
from __future__ import print_function
import rospy
from std_msgs.msg import Int16
from pfoe_cartpole.msg import ButtonValues
import datetime
import csv
file_directory = "/home/mt/work/pfoe_cartpole/test_log/"
file_name = "replay_"
file_extention = ".csv"
class Logger():
def __init__(self):
# rospy.Subscri... | scripts/result_logger.py |
from __future__ import print_function
import rospy
from std_msgs.msg import Int16
from pfoe_cartpole.msg import ButtonValues
import datetime
import csv
file_directory = "/home/mt/work/pfoe_cartpole/test_log/"
file_name = "replay_"
file_extention = ".csv"
class Logger():
def __init__(self):
# rospy.Subscri... | 0.145798 | 0.065217 |
import base64
from collections import OrderedDict
import hashlib
import hmac
import json
import requests
import time
# Initial code is taken from https://github.com/BTCMarkets/api-v3-client-python/blob/master/main.py
# And has been modified to include all API v3 endpoints as at 30 Jan 2021.
class Client(object):
... | btcmarkets/client.py | import base64
from collections import OrderedDict
import hashlib
import hmac
import json
import requests
import time
# Initial code is taken from https://github.com/BTCMarkets/api-v3-client-python/blob/master/main.py
# And has been modified to include all API v3 endpoints as at 30 Jan 2021.
class Client(object):
... | 0.50293 | 0.133726 |
import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import openslide
import PIL
import cv2
import matplotlib.pyplot as plt
from scipy import ndimage
from torch.utils.data import DataLoader
import math
import json
import logging
import time
import tensorflow as tf
from tensorfl... | code_cm17/inference/probs_map.py | import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import openslide
import PIL
import cv2
import matplotlib.pyplot as plt
from scipy import ndimage
from torch.utils.data import DataLoader
import math
import json
import logging
import time
import tensorflow as tf
from tensorfl... | 0.321247 | 0.149842 |
try:
import traceback
import json
import sqlite3
import sqlalchemy as sa
import pandas as pd
import sys
from os import path
import requests
import argparse
from termcolor import colored,cprint
import colorama
colorama.init()
parser = argparse.ArgumentParser(descriptio... | nsrl_client.py | try:
import traceback
import json
import sqlite3
import sqlalchemy as sa
import pandas as pd
import sys
from os import path
import requests
import argparse
from termcolor import colored,cprint
import colorama
colorama.init()
parser = argparse.ArgumentParser(descriptio... | 0.182134 | 0.097048 |
from starthinker.util.project import project
from starthinker.util.bigquery import query_to_table, query_to_view
from starthinker.task.census.fields import CENSUS_FIELDS
def census_normalize(census_geography, census_year, census_span):
query = 'SELECT\n'
for segment in CENSUS_FIELDS:
if segment['denominator... | starthinker/task/census/run.py |
from starthinker.util.project import project
from starthinker.util.bigquery import query_to_table, query_to_view
from starthinker.task.census.fields import CENSUS_FIELDS
def census_normalize(census_geography, census_year, census_span):
query = 'SELECT\n'
for segment in CENSUS_FIELDS:
if segment['denominator... | 0.703142 | 0.374333 |
from typing import Dict
from typing import List
from typing import Union
from datetime import date
from datetime import datetime
from enum import Enum
from edgar.session import EdgarSession
from edgar.utilis import EdgarUtilities
from edgar.parser import EdgarParser
class MutualFunds():
"""
## Overview:
... | edgar/mutual_funds.py | from typing import Dict
from typing import List
from typing import Union
from datetime import date
from datetime import datetime
from enum import Enum
from edgar.session import EdgarSession
from edgar.utilis import EdgarUtilities
from edgar.parser import EdgarParser
class MutualFunds():
"""
## Overview:
... | 0.918494 | 0.229276 |
import pytest
from unittest import mock
from paths_cli.tests.compiling.utils import mock_compiler
import numpy as np
import yaml
import openpathsampling as paths
from paths_cli.compiling.networks import *
_COMPILERS_LOC = 'paths_cli.compiling.root_compiler._COMPILERS'
def check_unidirectional_tis(results, state_A,... | paths_cli/tests/compiling/test_networks.py | import pytest
from unittest import mock
from paths_cli.tests.compiling.utils import mock_compiler
import numpy as np
import yaml
import openpathsampling as paths
from paths_cli.compiling.networks import *
_COMPILERS_LOC = 'paths_cli.compiling.root_compiler._COMPILERS'
def check_unidirectional_tis(results, state_A,... | 0.504639 | 0.672157 |
import numpy as np
from projectq.meta import Dagger
from projectq.ops import Rz, Rx
from src.topology.limited_gates.qft import qft, qft_inverse
from src.topology.limited_gates.rotate import calculate_phase
from src.topology.limited_gates.simple import CRz, CNOT
def add(eng, circuit, qubits, value):
len... | src/topology/limited_gates/add.py | import numpy as np
from projectq.meta import Dagger
from projectq.ops import Rz, Rx
from src.topology.limited_gates.qft import qft, qft_inverse
from src.topology.limited_gates.rotate import calculate_phase
from src.topology.limited_gates.simple import CRz, CNOT
def add(eng, circuit, qubits, value):
len... | 0.499023 | 0.500488 |
import os, json, errno, codecs
import ConfigParser
import types
import re
_config = ConfigParser.ConfigParser()
_config.read('testconfig.ini')
base_path = _config.get("fix", "root_path")
out_path = _config.get("fix", "out_path")
if out_path == None:
out_path = base_path
def goodPayloadSchema(ps):
isGood = ... | utils/fix.py | import os, json, errno, codecs
import ConfigParser
import types
import re
_config = ConfigParser.ConfigParser()
_config.read('testconfig.ini')
base_path = _config.get("fix", "root_path")
out_path = _config.get("fix", "out_path")
if out_path == None:
out_path = base_path
def goodPayloadSchema(ps):
isGood = ... | 0.081431 | 0.073264 |
import logging
from typing import List, Tuple, Union, Set
from ontobio import Ontology
from genedescriptions.commons import CommonAncestor
logger = logging.getLogger(__name__)
def find_set_covering(subsets: List[CommonAncestor], ontology: Ontology = None, value: List[float] = None,
max_num_s... | genedescriptions/optimization.py | import logging
from typing import List, Tuple, Union, Set
from ontobio import Ontology
from genedescriptions.commons import CommonAncestor
logger = logging.getLogger(__name__)
def find_set_covering(subsets: List[CommonAncestor], ontology: Ontology = None, value: List[float] = None,
max_num_s... | 0.833596 | 0.500916 |
import sys
import typing
from datetime import datetime
import discord
from discord.ext import commands
from sweeperbot.utilities.helpers import set_sentry_scope
class UserStats(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["us", "user"])
@commands.guild_only(... | sweeperbot/cogs/profile/userstats.py | import sys
import typing
from datetime import datetime
import discord
from discord.ext import commands
from sweeperbot.utilities.helpers import set_sentry_scope
class UserStats(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["us", "user"])
@commands.guild_only(... | 0.457379 | 0.083703 |
import Tkinter as tk
class NatnetView:
def __init__(self, parent, reader):
self.parent = parent
self.reader = reader
self.setup()
def __del__(self):
self.destroy()
def destroy(self):
self.frame.grid_forget()
def setup(self):
# container
self.fr... | pymocap/gui/natnet_view.py | import Tkinter as tk
class NatnetView:
def __init__(self, parent, reader):
self.parent = parent
self.reader = reader
self.setup()
def __del__(self):
self.destroy()
def destroy(self):
self.frame.grid_forget()
def setup(self):
# container
self.fr... | 0.505371 | 0.10923 |
import os
import json
import time
from datetime import date, datetime, timedelta
from pytz import timezone
import requests
from bs4 import BeautifulSoup
import traceback
tz = timezone("EST")
timerstart = datetime.now()
# ===== Read =====
print("-----> Reading old data.")
file = open("allimdbpolls.json", "r", encoding... | pollData/imdbpollreport.py | import os
import json
import time
from datetime import date, datetime, timedelta
from pytz import timezone
import requests
from bs4 import BeautifulSoup
import traceback
tz = timezone("EST")
timerstart = datetime.now()
# ===== Read =====
print("-----> Reading old data.")
file = open("allimdbpolls.json", "r", encoding... | 0.069704 | 0.054601 |
import pytest
import shutil
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from artists.models import Artists
pytestmark = pytest.mark.django_db
def test_create_artists(api_client):
data = {
"username": "foobar",
"e... | was/artists/tests/test_views.py | import pytest
import shutil
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from artists.models import Artists
pytestmark = pytest.mark.django_db
def test_create_artists(api_client):
data = {
"username": "foobar",
"e... | 0.437343 | 0.477554 |
from os import path, mkdir, unlink
from glob import glob
from scipy import io
import numpy as np
import pandas as pd
from pandas.io.pytables import HDFStore
import warnings
import re
from digits.utils import dotdict
class UnmatchedDimensions(Exception): pass
class UnmatchedSubjects(Exception): pass
class Inconsistent... | digits/data/matimport.py | from os import path, mkdir, unlink
from glob import glob
from scipy import io
import numpy as np
import pandas as pd
from pandas.io.pytables import HDFStore
import warnings
import re
from digits.utils import dotdict
class UnmatchedDimensions(Exception): pass
class UnmatchedSubjects(Exception): pass
class Inconsistent... | 0.613468 | 0.372334 |
from src.algorithm import *
from src.network import *
from argparse import ArgumentParser
BOOST = True
label2piece = {"0":"b","1":"k","2":"n","3":"p","4":"q","5":"r","6":"B","7":"K","8":"N","9":"P","10":"Q","11":"R","12":"z"}
def most_frequent(List):
return max(set(List), key = List.count)
def make_args():
... | predict.py | from src.algorithm import *
from src.network import *
from argparse import ArgumentParser
BOOST = True
label2piece = {"0":"b","1":"k","2":"n","3":"p","4":"q","5":"r","6":"B","7":"K","8":"N","9":"P","10":"Q","11":"R","12":"z"}
def most_frequent(List):
return max(set(List), key = List.count)
def make_args():
... | 0.442275 | 0.248705 |
import os
import shutil
import argparse
import random
import numpy as np
from pycocotools.coco import COCO
random.seed(42)
index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, ... | convert_coco_to_yolo.py | import os
import shutil
import argparse
import random
import numpy as np
from pycocotools.coco import COCO
random.seed(42)
index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, ... | 0.431704 | 0.200421 |
# encoding: utf-8
'''
@author: <NAME>
@contact: <EMAIL>
@software: PyCharm
@file: predit_mysql.py
@time: 2018/4/10 9:45
@desc:
'''
from __future__ import print_function
import os
import tensorflow as tf
import tensorflow.contrib.keras as kr
from cnn_model import TCNNConfig, TextCNN
from data.cnews_loader imp... | text_classification/server_predict.py |
# encoding: utf-8
'''
@author: <NAME>
@contact: <EMAIL>
@software: PyCharm
@file: predit_mysql.py
@time: 2018/4/10 9:45
@desc:
'''
from __future__ import print_function
import os
import tensorflow as tf
import tensorflow.contrib.keras as kr
from cnn_model import TCNNConfig, TextCNN
from data.cnews_loader imp... | 0.291888 | 0.087955 |
import math
import numpy as np
from hi_rct_utl import *
from hi_rct_dist import HI_RCT_Dist
class HI_RCT_Hist:
@staticmethod
def find_iecs (intents, history, IEC_TOL):
int_corr = np.corrcoef(intents)
# iecs will collect the pairs of variables that meet the correlational
# similarit... | src/hi_rct_hist.py | import math
import numpy as np
from hi_rct_utl import *
from hi_rct_dist import HI_RCT_Dist
class HI_RCT_Hist:
@staticmethod
def find_iecs (intents, history, IEC_TOL):
int_corr = np.corrcoef(intents)
# iecs will collect the pairs of variables that meet the correlational
# similarit... | 0.566858 | 0.278277 |
import os
import glob
import pandas as pd
import re
import string
from collections import OrderedDict
import io
import csv
from itertools import zip_longest
import matplotlib
from matplotlib import pyplot as plt
import cv2
import time
def yes_or_no(question):
reply = str(input(question+' (y/n): ')... | dataset_superscript.py | import os
import glob
import pandas as pd
import re
import string
from collections import OrderedDict
import io
import csv
from itertools import zip_longest
import matplotlib
from matplotlib import pyplot as plt
import cv2
import time
def yes_or_no(question):
reply = str(input(question+' (y/n): ')... | 0.020636 | 0.092033 |
import argparse
import cv2
import xlrd
import torch
import imageio
import warnings
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from utils.Percept import percept
from utils.Det_crash import det_crash
from utils.Vehicle ... | IRM_algorithm/IRM_algorithm.py | import argparse
import cv2
import xlrd
import torch
import imageio
import warnings
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from utils.Percept import percept
from utils.Det_crash import det_crash
from utils.Vehicle ... | 0.692018 | 0.580887 |
import os
import inspect
import re
from powergym.env import Env
# map from system_name to fixed information of the system
_SYS_INFO = {
'13Bus': {
'source_bus': 'sourcebus',
'node_size': 500,
'shift': 10,
'show_node_labels': True
},
'34Bus': {
'so... | powergym/env_register.py |
import os
import inspect
import re
from powergym.env import Env
# map from system_name to fixed information of the system
_SYS_INFO = {
'13Bus': {
'source_bus': 'sourcebus',
'node_size': 500,
'shift': 10,
'show_node_labels': True
},
'34Bus': {
'so... | 0.321673 | 0.143788 |