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 logging
from typing import List
from vdk.api.plugin.hook_markers import hookimpl
from vdk.internal.builtin_plugins.config.job_config import JobConfigKeys
from vdk.internal.builtin_plugins.config.vdk_config import LOG_CONFIG
from vdk.internal.builtin_plugins.notification import notification_base
from vdk.interna... | projects/vdk-core/src/vdk/internal/builtin_plugins/notification/notification.py | import logging
from typing import List
from vdk.api.plugin.hook_markers import hookimpl
from vdk.internal.builtin_plugins.config.job_config import JobConfigKeys
from vdk.internal.builtin_plugins.config.vdk_config import LOG_CONFIG
from vdk.internal.builtin_plugins.notification import notification_base
from vdk.interna... | 0.446495 | 0.052449 |
import socket
class PyCololight:
COMMAND_PREFIX = "535a30300000000000"
COMMAND_CONFIG = "20000000000000000000000000000000000100000000000000000004010301c"
COMMAND_EFFECT = "23000000000000000000000000000000000100000000000000000004010602ff"
CUSTOM_EFFECT_COLOURS = {
"Breath": {
"decima... | light/Cololight.py | import socket
class PyCololight:
COMMAND_PREFIX = "535a30300000000000"
COMMAND_CONFIG = "20000000000000000000000000000000000100000000000000000004010301c"
COMMAND_EFFECT = "23000000000000000000000000000000000100000000000000000004010602ff"
CUSTOM_EFFECT_COLOURS = {
"Breath": {
"decima... | 0.695855 | 0.213787 |
import pandas as pd
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
from matplotlib import pyplot as plt
file=pd.read_csv('/home/Documents/Acads/CompGenomics/Proj_ComparitiveGenomics/vf_merged_results.tsv', sep='\t')
VF=list(file['Virulence factor'])
Is=list(file['Isolate'])
genes=['eae... | source/comparative_genomics/heatmap_VF.py | import pandas as pd
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
from matplotlib import pyplot as plt
file=pd.read_csv('/home/Documents/Acads/CompGenomics/Proj_ComparitiveGenomics/vf_merged_results.tsv', sep='\t')
VF=list(file['Virulence factor'])
Is=list(file['Isolate'])
genes=['eae... | 0.067839 | 0.125333 |
from __future__ import print_function, division, absolute_import
__author__ = "<NAME>"
__license__ = "MIT"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import os
import sys
import json
import math
from . import control
from . import utils
import maya.cmds as mc
import tpDccLib as tp
from tpMayaLib.core import s... | solstice/tools/proprigger/rig.py | from __future__ import print_function, division, absolute_import
__author__ = "<NAME>"
__license__ = "MIT"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import os
import sys
import json
import math
from . import control
from . import utils
import maya.cmds as mc
import tpDccLib as tp
from tpMayaLib.core import s... | 0.401336 | 0.097048 |
import infra.e2e_args
import infra.network
import infra.proc
import time
import http
from ccf.tx_status import TxStatus
from loguru import logger as LOG
def wait_for_pending(client, view, seqno, timeout=3):
end_time = time.time() + timeout
while time.time() < end_time:
r = client.get(f"/node/tx?view=... | tests/committable.py | import infra.e2e_args
import infra.network
import infra.proc
import time
import http
from ccf.tx_status import TxStatus
from loguru import logger as LOG
def wait_for_pending(client, view, seqno, timeout=3):
end_time = time.time() + timeout
while time.time() < end_time:
r = client.get(f"/node/tx?view=... | 0.378919 | 0.188978 |
import os
import sys
import PyInstaller.bindepend
from PyInstaller.compat import is_py24, is_win, is_darwin, is_unix, is_virtualenv
from PyInstaller.build import Tree
from PyInstaller.hooks.hookutils import exec_statement, logger
def _handle_broken_tk():
"""
Workaround for broken Tcl/Tk detection in virtu... | SWIM-Executables/Windows/pyinstaller-2.0 for windows/PyInstaller/hooks/hook-_tkinter.py |
import os
import sys
import PyInstaller.bindepend
from PyInstaller.compat import is_py24, is_win, is_darwin, is_unix, is_virtualenv
from PyInstaller.build import Tree
from PyInstaller.hooks.hookutils import exec_statement, logger
def _handle_broken_tk():
"""
Workaround for broken Tcl/Tk detection in virtu... | 0.403214 | 0.123842 |
from collections import OrderedDict
from random import Random
from urllib.parse import unquote
from faker import Faker
def create_team(num=1, team_role="Accountant", team_size=Faker().random_int(min=3, max=10),
team_company=Faker().last_name(), team_name=""):
def get_personality():
return... | scripts/create_team.py | from collections import OrderedDict
from random import Random
from urllib.parse import unquote
from faker import Faker
def create_team(num=1, team_role="Accountant", team_size=Faker().random_int(min=3, max=10),
team_company=Faker().last_name(), team_name=""):
def get_personality():
return... | 0.493897 | 0.28172 |
import os
import argparse
import copy
import paddle
import paddlehub as hub
from paddlehub.module.module import moduleinfo, runnable, serving
import numpy as np
import cv2
from .model import Wav2LipPredictor
@moduleinfo(name="wav2lip", type="CV/generation", author="paddlepaddle", author_email="", summary="", versi... | modules/image/Image_gan/gan/wav2lip/module.py |
import os
import argparse
import copy
import paddle
import paddlehub as hub
from paddlehub.module.module import moduleinfo, runnable, serving
import numpy as np
import cv2
from .model import Wav2LipPredictor
@moduleinfo(name="wav2lip", type="CV/generation", author="paddlepaddle", author_email="", summary="", versi... | 0.567937 | 0.106133 |
import pandas as pd
import json
import string
import spacy
from tensorflow import keras
from keras_preprocessing.text import tokenizer_from_json
def full_form(word):
if word == 'nt': word = 'not'
if word == 're': word = 'are'
if word == 's': word = 'is'
if word == 'd': word = 'would'... | deploy/flask-app/preprocessing.py | import pandas as pd
import json
import string
import spacy
from tensorflow import keras
from keras_preprocessing.text import tokenizer_from_json
def full_form(word):
if word == 'nt': word = 'not'
if word == 're': word = 'are'
if word == 's': word = 'is'
if word == 'd': word = 'would'... | 0.340376 | 0.150778 |
from manim import *
class v1t1(Scene):
def construct(self):
plane = NumberPlane(x_range=[-7,7,1], y_range=[-4,4,1])
plane.add_coordinates()
box = Rectangle(stroke_color = GREEN_C, stroke_opacity=0.7, fill_color = RED_B, fill_opacity = 0.5, height=1, width=1)
dot = always_redr... | BrianAmedee/tutorials/t1.py | from manim import *
class v1t1(Scene):
def construct(self):
plane = NumberPlane(x_range=[-7,7,1], y_range=[-4,4,1])
plane.add_coordinates()
box = Rectangle(stroke_color = GREEN_C, stroke_opacity=0.7, fill_color = RED_B, fill_opacity = 0.5, height=1, width=1)
dot = always_redr... | 0.619817 | 0.313118 |
import argparse
import os
import warnings
import isce3
from nisar.products.readers import SLC
def cmdLineParse():
"""
Command line parser.
"""
parser = argparse.ArgumentParser(description="""
Run topo for reference product.""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)... | python/packages/nisar/workflows/rdr2geo.py |
import argparse
import os
import warnings
import isce3
from nisar.products.readers import SLC
def cmdLineParse():
"""
Command line parser.
"""
parser = argparse.ArgumentParser(description="""
Run topo for reference product.""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)... | 0.650134 | 0.160332 |
import numpy as np
import pylab as P
from rfwrapper import rf
import matplotlib.patches
import matplotlib.cm
import matplotlib.ticker
from radiofisher.units import *
import os
from radiofisher import euclid
cosmo = rf.experiments.cosmo
sarea_vals = [100, 250, 500, 750, 1000, 1500, 2000, 2500, 3000, 4000, 5000,
... | plotting/plot_fom_ska_galaxy.py | import numpy as np
import pylab as P
from rfwrapper import rf
import matplotlib.patches
import matplotlib.cm
import matplotlib.ticker
from radiofisher.units import *
import os
from radiofisher import euclid
cosmo = rf.experiments.cosmo
sarea_vals = [100, 250, 500, 750, 1000, 1500, 2000, 2500, 3000, 4000, 5000,
... | 0.39257 | 0.255396 |
import sys
import os
import json
import random
import datetime
import boto3
start_time = datetime.datetime.now()
no_of_days = 30
workload_contexts_distribution = [2, 15, 20, 18, 30, 15]
workload_contexts = {
"OnBoardingApplication": ['TenantCreation', 'UserCreation'],
"AuthApplication": ['Login', 'Logout', '... | metrics-generator/application-metrics-generator.py |
import sys
import os
import json
import random
import datetime
import boto3
start_time = datetime.datetime.now()
no_of_days = 30
workload_contexts_distribution = [2, 15, 20, 18, 30, 15]
workload_contexts = {
"OnBoardingApplication": ['TenantCreation', 'UserCreation'],
"AuthApplication": ['Login', 'Logout', '... | 0.260201 | 0.120361 |
from flask_uploads import UploadSet, IMAGES
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed
from wtforms import ValidationError
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from wtforms.fields import PasswordField, StringField, SubmitField, BooleanField, In... | app/blueprints/admin/forms.py | from flask_uploads import UploadSet, IMAGES
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed
from wtforms import ValidationError
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from wtforms.fields import PasswordField, StringField, SubmitField, BooleanField, In... | 0.565539 | 0.144662 |
from . import astree
from .lexer import Lexer
from . import tok
# rules:
# factor: INTEGER | variable
# value: factor | paren | (PLUS | MINUS) value
# paren: LPAREN expr RPAREN
# power: value (POW value)*
# mul: power ((MUL | DIV) power)*
# addition: mul ((PLUS | MINUS) mul)*
# expr: additon
# pascal rules
# program:... | spi/interpreter.py | from . import astree
from .lexer import Lexer
from . import tok
# rules:
# factor: INTEGER | variable
# value: factor | paren | (PLUS | MINUS) value
# paren: LPAREN expr RPAREN
# power: value (POW value)*
# mul: power ((MUL | DIV) power)*
# addition: mul ((PLUS | MINUS) mul)*
# expr: additon
# pascal rules
# program:... | 0.61855 | 0.382776 |
import connect
def add_watched_user(username, reason, author, authorid, email):
"""
Add user to watched user list for tracking.
Inputs
------
username : str
Username to track
reason : str
Reason to track user
author : str
User adding tracking entry
authorid : i... | osmhm/manage.py | import connect
def add_watched_user(username, reason, author, authorid, email):
"""
Add user to watched user list for tracking.
Inputs
------
username : str
Username to track
reason : str
Reason to track user
author : str
User adding tracking entry
authorid : i... | 0.228243 | 0.113089 |
import os
from webassets import filter
from flask_assets import Environment, Bundle
from flask_site.libraries.csscompressor_webassets import CSSCompressor
def register_filters():
# This compressor is better than the one built into webassets
filter.register_filter(CSSCompressor)
def compile_assets(app, bu... | flask_site/helpers/assets.py | import os
from webassets import filter
from flask_assets import Environment, Bundle
from flask_site.libraries.csscompressor_webassets import CSSCompressor
def register_filters():
# This compressor is better than the one built into webassets
filter.register_filter(CSSCompressor)
def compile_assets(app, bu... | 0.4917 | 0.154121 |
import tensorflow as tf
import numpy as np
import os
# %% Reading data
def read_cifar10(data_dir, is_train, batch_size, shuffle):
"""Read CIFAR10
Args:
data_dir: the directory of CIFAR10
is_train: boolen
batch_size:
shuffle:
Returns:
label: 1D tensor, tf.int32
... | tensorflow_learning/example_02/cifar10_readdata.py | import tensorflow as tf
import numpy as np
import os
# %% Reading data
def read_cifar10(data_dir, is_train, batch_size, shuffle):
"""Read CIFAR10
Args:
data_dir: the directory of CIFAR10
is_train: boolen
batch_size:
shuffle:
Returns:
label: 1D tensor, tf.int32
... | 0.810291 | 0.430686 |
import argparse
import numpy as np
import gym
import messenger
def numpy_formatter(i: int):
''' Format function passed to numpy print to make things pretty.
'''
id_map = {}
for ent in messenger.envs.config.ALL_ENTITIES:
id_map[ent.id] = ent.name[:2].upper()
id_map[0] = ' '
id_map[15] =... | play_msgr.py | import argparse
import numpy as np
import gym
import messenger
def numpy_formatter(i: int):
''' Format function passed to numpy print to make things pretty.
'''
id_map = {}
for ent in messenger.envs.config.ALL_ENTITIES:
id_map[ent.id] = ent.name[:2].upper()
id_map[0] = ' '
id_map[15] =... | 0.207455 | 0.270739 |
import os
import click
import numpy as np
import vtk
from tqdm import tqdm
import pandas as pd
@click.command()
@click.argument("file_name", nargs=1)
def main(file_name):
reader = vtk.vtkPolyDataReader()
reader.SetFileName(file_name)
reader.Update()
polygon = reader.GetOutput()
n = polygon.GetNumb... | local_postprocessing/mesh_to_histograms.py | import os
import click
import numpy as np
import vtk
from tqdm import tqdm
import pandas as pd
@click.command()
@click.argument("file_name", nargs=1)
def main(file_name):
reader = vtk.vtkPolyDataReader()
reader.SetFileName(file_name)
reader.Update()
polygon = reader.GetOutput()
n = polygon.GetNumb... | 0.243103 | 0.441011 |
class Car():
"""Tentativa simples de modelar um carro."""
def __init__(self, make, model, year):
"""Inicializa os atributos de um carro."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
""" Ret... | cap_9/exercicios/9.9.py | class Car():
"""Tentativa simples de modelar um carro."""
def __init__(self, make, model, year):
"""Inicializa os atributos de um carro."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
""" Ret... | 0.750553 | 0.431524 |
from __future__ import division
from __future__ import print_function
import os
import warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
warnings.filterwarnings('ignore')
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
import time
import logging
from utils import *
from models im... | train_test.py | from __future__ import division
from __future__ import print_function
import os
import warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
warnings.filterwarnings('ignore')
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
import time
import logging
from utils import *
from models im... | 0.754553 | 0.220154 |
import json
from twisted.internet import protocol, reactor
from txws import WebSocketFactory
MESSAGE_TYPES = ('login', 'message')
PORT = 8080
class Chatter(protocol.Protocol):
def __init__(self, factory, id):
self.factory = factory
self.id = id
self.handle = 'unknown'
def _build(sel... | server/server.py | import json
from twisted.internet import protocol, reactor
from txws import WebSocketFactory
MESSAGE_TYPES = ('login', 'message')
PORT = 8080
class Chatter(protocol.Protocol):
def __init__(self, factory, id):
self.factory = factory
self.id = id
self.handle = 'unknown'
def _build(sel... | 0.305076 | 0.060724 |
import os
from qtstyles import errors
class Sheet(object):
'''
Keeps key information related to style sheets, particularly the path
and contents as a string.
>>> import os
>>> dirpath = os.path.dirname(os.path.abspath(__file__))
>>> path = os.path.join(dirpath, "style_sheets", "defau... | qtstyles/sheet.py | import os
from qtstyles import errors
class Sheet(object):
'''
Keeps key information related to style sheets, particularly the path
and contents as a string.
>>> import os
>>> dirpath = os.path.dirname(os.path.abspath(__file__))
>>> path = os.path.join(dirpath, "style_sheets", "defau... | 0.515376 | 0.180829 |
import csv
import os
import json
import pandas as pd
import pickle
from util.tokenization import *
import re
import sys
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a Inp... | code/util/processor.py | import csv
import os
import json
import pandas as pd
import pickle
from util.tokenization import *
import re
import sys
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a Inp... | 0.668772 | 0.437824 |
from altair.utils.schemapi import SchemaBase, Undefined
import os
import json
def load_schema():
"""Load the json schema associated with this module's functions"""
directory = os.path.dirname(__file__)
with open(os.path.join(directory, '..', 'vega-lite-schema.json')) as f:
return json.load(f)
c... | altair/vegalite/v2/schema/core.py |
from altair.utils.schemapi import SchemaBase, Undefined
import os
import json
def load_schema():
"""Load the json schema associated with this module's functions"""
directory = os.path.dirname(__file__)
with open(os.path.join(directory, '..', 'vega-lite-schema.json')) as f:
return json.load(f)
c... | 0.827026 | 0.419588 |
from flask import Flask, request, redirect, render_template, session
from flask_socketio import SocketIO
# custom imports
from helpers.twilio import process_response, send_mass_message, send_chat_message
from helpers.database import get_all_students, get_alert_names, get_alert_template, get_audience_names, get_last_rea... | app.py | from flask import Flask, request, redirect, render_template, session
from flask_socketio import SocketIO
# custom imports
from helpers.twilio import process_response, send_mass_message, send_chat_message
from helpers.database import get_all_students, get_alert_names, get_alert_template, get_audience_names, get_last_rea... | 0.161717 | 0.068913 |
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class DataSafeClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.data_safe.DataSafeClient` and offers convenience methods
for operations that would otherwise need to be chained tog... | src/oci/data_safe/data_safe_client_composite_operations.py |
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class DataSafeClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.data_safe.DataSafeClient` and offers convenience methods
for operations that would otherwise need to be chained tog... | 0.775647 | 0.403391 |
from PyQt5.QtWidgets import QPushButton, \
QGridLayout, QDialog, QListWidget
import logging
class MainMeasurementDialog:
def choose_measurement(self): #choose measurement
self.MsrDialog = QDialog(self)
foldername = self.folderPath.split("/")[-1]
self.MsrDialog.setWindowT... | app/_mainMeasurementdialog.py | from PyQt5.QtWidgets import QPushButton, \
QGridLayout, QDialog, QListWidget
import logging
class MainMeasurementDialog:
def choose_measurement(self): #choose measurement
self.MsrDialog = QDialog(self)
foldername = self.folderPath.split("/")[-1]
self.MsrDialog.setWindowT... | 0.143938 | 0.075927 |
import os
import logging
import requests
from importlib.machinery import SourceFileLoader
class RedmineLib(object):
_key = ''
_crt = ''
_url = ''
_token = ''
def __init__(self):
cnf=os.path.join(os.getenv('HOME'), '.config', 'redmine_commander', 'env.py')
self._load_config(cnf)
... | src/redmine_commander/redmine_lib.py | import os
import logging
import requests
from importlib.machinery import SourceFileLoader
class RedmineLib(object):
_key = ''
_crt = ''
_url = ''
_token = ''
def __init__(self):
cnf=os.path.join(os.getenv('HOME'), '.config', 'redmine_commander', 'env.py')
self._load_config(cnf)
... | 0.142143 | 0.050447 |
import gzip
import re
from pathlib import Path
from typing import Any, Tuple
from nig.endpoints import FILE_NOT_FOUND, NIGEndpoint
from restapi import decorators
from restapi.connectors import neo4j
from restapi.exceptions import BadRequest, NotFound, ServerError
from restapi.models import Schema, fields
from restapi.... | projects/nig/backend/endpoints/files.py | import gzip
import re
from pathlib import Path
from typing import Any, Tuple
from nig.endpoints import FILE_NOT_FOUND, NIGEndpoint
from restapi import decorators
from restapi.connectors import neo4j
from restapi.exceptions import BadRequest, NotFound, ServerError
from restapi.models import Schema, fields
from restapi.... | 0.54819 | 0.109777 |
from Decision_Tree_CART import DecisionTree_CART
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingRegressor,AdaBoostRegressor
def L(y_train,f):
return np.sum((y_train-f)**2)
def der_L(y_train,f):
return 2*(y_train-f)
def opt_L(y_train,f=0):
... | Supervised Machine Learning Algorithms/Ensemble Methods/Gradient_Boosting.py | from Decision_Tree_CART import DecisionTree_CART
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingRegressor,AdaBoostRegressor
def L(y_train,f):
return np.sum((y_train-f)**2)
def der_L(y_train,f):
return 2*(y_train-f)
def opt_L(y_train,f=0):
... | 0.395251 | 0.379896 |
from flask import url_for
from jinja2 import Markup
from flask import current_app
try:
from html import escape
except ImportError:
from cgi import escape
from wtforms.fields import TextAreaField
from wtforms.widgets import HTMLString, TextArea
from wtforms.compat import text_type
from wtforms.widgets.core impor... | flask_maple/editormd/fields.py | from flask import url_for
from jinja2 import Markup
from flask import current_app
try:
from html import escape
except ImportError:
from cgi import escape
from wtforms.fields import TextAreaField
from wtforms.widgets import HTMLString, TextArea
from wtforms.compat import text_type
from wtforms.widgets.core impor... | 0.444565 | 0.064388 |
from __future__ import unicode_literals, print_function, absolute_import
print("yop")
import unittest
import sqlalchemy as sa
import asgard.expression as expression
import sqlalchemy.sql.expression as saexpr
import sqlalchemy.sql as sql
class ExpressionsParserTest(unittest.TestCase):
def test_identifier(self)... | asgard/test/expressiontest.py |
from __future__ import unicode_literals, print_function, absolute_import
print("yop")
import unittest
import sqlalchemy as sa
import asgard.expression as expression
import sqlalchemy.sql.expression as saexpr
import sqlalchemy.sql as sql
class ExpressionsParserTest(unittest.TestCase):
def test_identifier(self)... | 0.601008 | 0.534612 |
# Authors: <NAME>, <NAME>, <NAME>
# Maintainer: <NAME> <<EMAIL>>
import textwrap
from optparse import OptionParser, IndentedHelpFormatter
from .color import colorize, warning, message
class ColoredOptionParser(OptionParser):
def error(self, message):
msg = colorize(message, 'red')
OptionParser.e... | thirdparty/xacro-1.14.10/src/xacro/cli.py |
# Authors: <NAME>, <NAME>, <NAME>
# Maintainer: <NAME> <<EMAIL>>
import textwrap
from optparse import OptionParser, IndentedHelpFormatter
from .color import colorize, warning, message
class ColoredOptionParser(OptionParser):
def error(self, message):
msg = colorize(message, 'red')
OptionParser.e... | 0.548915 | 0.111676 |
import pytest
import numpy as np
from pbcore.util.statistics import (pb_identity,
blast_identity,
gap_compressed_identity)
from pbcore.io import AlignmentSet, BamReader, IndexedBamReader
from pbtestdata import get_file
def _compare_identity(x1,... | tests/test_mapped_sequence_identity.py | import pytest
import numpy as np
from pbcore.util.statistics import (pb_identity,
blast_identity,
gap_compressed_identity)
from pbcore.io import AlignmentSet, BamReader, IndexedBamReader
from pbtestdata import get_file
def _compare_identity(x1,... | 0.6488 | 0.723993 |
import torch
import os
from models import SR
from utils import myUtils
from evaluation.Evaluation import Evaluation as Base
# Evaluation for any stereo model including SR-Stereo
class Evaluation(Base):
def __init__(self, testImgLoader, evalFcn='l1', ndisLog=1):
super(Evaluation, self).__init__(testImgLoad... | evaluation/SR_eval.py | import torch
import os
from models import SR
from utils import myUtils
from evaluation.Evaluation import Evaluation as Base
# Evaluation for any stereo model including SR-Stereo
class Evaluation(Base):
def __init__(self, testImgLoader, evalFcn='l1', ndisLog=1):
super(Evaluation, self).__init__(testImgLoad... | 0.68056 | 0.249462 |
import os
import argparse
import torch
import utils
import subprocess
def get_args():
parser = argparse.ArgumentParser(description='RL')
'''basic save and log'''
parser.add_argument('--exp', type=str,
help='Give a top description of this experiment')
'''following settings are ... | arguments.py | import os
import argparse
import torch
import utils
import subprocess
def get_args():
parser = argparse.ArgumentParser(description='RL')
'''basic save and log'''
parser.add_argument('--exp', type=str,
help='Give a top description of this experiment')
'''following settings are ... | 0.592784 | 0.087213 |
from __future__ import division
import sys
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from lib.diff_evolution import diff_evolv_3d
from lib.draw_plot import draw_sphere
from lib.potential import coulomb_pot
def main():
# Declare immutable variables
n = 12 # number of... | main.py | from __future__ import division
import sys
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from lib.diff_evolution import diff_evolv_3d
from lib.draw_plot import draw_sphere
from lib.potential import coulomb_pot
def main():
# Declare immutable variables
n = 12 # number of... | 0.309128 | 0.275596 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('geo', '0013_auto_20190524_0958'),
('activities', '0001_initial'),
]
operations = [
migr... | bluebottle/events/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('geo', '0013_auto_20190524_0958'),
('activities', '0001_initial'),
]
operations = [
migr... | 0.640523 | 0.142649 |
import math
import copy
class Vector3:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(' + str(self.x) + ' , ' + str(self.y) + ' , ' + str(self.z) + ')'
def __getitem__(self, key):
if key == 0:
ret... | utils/vector.py | import math
import copy
class Vector3:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(' + str(self.x) + ' , ' + str(self.y) + ' , ' + str(self.z) + ')'
def __getitem__(self, key):
if key == 0:
ret... | 0.822724 | 0.267932 |
import os
import cv2
import scipy
import scipy.ndimage
import scipy.spatial
import numpy as np
import sys
sys.path.append(os.getcwd())
from utils.visualize import *
# input 2-D point gt map, output gt density map
def generate_scale(gt_list, max_size=48):
scale_list = []
gt_count = len(gt_list)
if gt_coun... | data_process/generate_scale_map_and_gt_num.py | import os
import cv2
import scipy
import scipy.ndimage
import scipy.spatial
import numpy as np
import sys
sys.path.append(os.getcwd())
from utils.visualize import *
# input 2-D point gt map, output gt density map
def generate_scale(gt_list, max_size=48):
scale_list = []
gt_count = len(gt_list)
if gt_coun... | 0.210117 | 0.265059 |
import argparse
import torch
class BaseOptions():
def __init__(self):
"""Reset the class; indicates the class hasn't been initailized"""
self.initialized = False
def initialize(self, misc_arg):
# data set
misc_arg.add_argument('--batch_size', type=int,
... | opt/config.py | import argparse
import torch
class BaseOptions():
def __init__(self):
"""Reset the class; indicates the class hasn't been initailized"""
self.initialized = False
def initialize(self, misc_arg):
# data set
misc_arg.add_argument('--batch_size', type=int,
... | 0.708313 | 0.083965 |
import json, re
from collections import namedtuple
from struct import Struct
class Types:
"""
Utility functions for database types.
The 'types' dictionary defines a mapping from user-facing type
primitives to their representation in the Python 'struct' module,
and a boolean indicating whether the type requi... | HW1/dbsys-hw1/Catalog/Schema.py | import json, re
from collections import namedtuple
from struct import Struct
class Types:
"""
Utility functions for database types.
The 'types' dictionary defines a mapping from user-facing type
primitives to their representation in the Python 'struct' module,
and a boolean indicating whether the type requi... | 0.774711 | 0.435661 |
from bs4 import BeautifulSoup, NavigableString
import requests
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutExce... | myvenv/services/services_scraper.py | from bs4 import BeautifulSoup, NavigableString
import requests
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutExce... | 0.081805 | 0.07393 |
import os
import argparse
import sys
import json
import torch
from torch.optim.lr_scheduler import StepLR
import torchtext
from models.trainer import Trainer
from models.seq2seq import Seq2seq
from loss.loss import Perplexity
from dataset import fields
import matplotlib.pyplot as plt
import argparse
par = argparse.... | autoencoder/seq2seq/main/train.py | import os
import argparse
import sys
import json
import torch
from torch.optim.lr_scheduler import StepLR
import torchtext
from models.trainer import Trainer
from models.seq2seq import Seq2seq
from loss.loss import Perplexity
from dataset import fields
import matplotlib.pyplot as plt
import argparse
par = argparse.... | 0.340595 | 0.242598 |
import configparser
import json
from os import path
from typing import Optional, Tuple, List
from envparse import env
from clickhouse_migrate.common.exceptions.config import ConfigError
from clickhouse_migrate.common.meta import Singleton
env.read_envfile()
CLICKHOUSE_MIGRATE_DATABASES = env.str("CLICKHOUSE_MIGRA... | clickhouse_migrate/conf/settings.py | import configparser
import json
from os import path
from typing import Optional, Tuple, List
from envparse import env
from clickhouse_migrate.common.exceptions.config import ConfigError
from clickhouse_migrate.common.meta import Singleton
env.read_envfile()
CLICKHOUSE_MIGRATE_DATABASES = env.str("CLICKHOUSE_MIGRA... | 0.608129 | 0.07477 |
from typing import Union
from fastapi import Depends, FastAPI
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.responses import HTMLResponse, JSONResponse
import fastapimsal
# Notice all docs are removed. We can add behind auth later
app ... | examples/app.py | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.responses import HTMLResponse, JSONResponse
import fastapimsal
# Notice all docs are removed. We can add behind auth later
app ... | 0.751101 | 0.103749 |
from array import array
import sys
from py.test import raises
from pyvx import vx
import pyvx
if sys.version_info > (3,):
unicode = str
class TestVX(object):
def test_context(self):
c = vx.CreateContext()
assert vx.GetStatus(vx.reference(c)) == vx.SUCCESS
assert vx.QueryReference(vx.... | test/test_vx.py | from array import array
import sys
from py.test import raises
from pyvx import vx
import pyvx
if sys.version_info > (3,):
unicode = str
class TestVX(object):
def test_context(self):
c = vx.CreateContext()
assert vx.GetStatus(vx.reference(c)) == vx.SUCCESS
assert vx.QueryReference(vx.... | 0.453988 | 0.536252 |
import json
from enum import Enum
from functools import partial
from pickle import HIGHEST_PROTOCOL, dumps, loads
from typing import Any, Optional
try:
from redis import Redis
except ImportError:
Redis = None # type: ignore
try:
from aioredis import Redis as AioRedis
except ImportError:
AioRedis = No... | starlette_session/backends.py | import json
from enum import Enum
from functools import partial
from pickle import HIGHEST_PROTOCOL, dumps, loads
from typing import Any, Optional
try:
from redis import Redis
except ImportError:
Redis = None # type: ignore
try:
from aioredis import Redis as AioRedis
except ImportError:
AioRedis = No... | 0.745861 | 0.200695 |
import pickle
import pandas as pd
from pyspark.sql import functions as F
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql.types import *
from pyspark.sql.types import StructType
from pyspark.sql.window import Window
def get_orientation_data(ds, wrist, ori=1, is_new_device=False,
... | cerebralcortex/algorithms/brushing/features.py | import pickle
import pandas as pd
from pyspark.sql import functions as F
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql.types import *
from pyspark.sql.types import StructType
from pyspark.sql.window import Window
def get_orientation_data(ds, wrist, ori=1, is_new_device=False,
... | 0.833799 | 0.54153 |
import unittest
import random
import subprocess
import os
import sys
from pathlib import Path
import urllib.request
import zipfile
import io
import shutil
import shlex
import re
import time
import json
import requests
from typing import Optional, Union, Collection, Set, Callable
from datetime import timedelta
from boot... | tests.py | import unittest
import random
import subprocess
import os
import sys
from pathlib import Path
import urllib.request
import zipfile
import io
import shutil
import shlex
import re
import time
import json
import requests
from typing import Optional, Union, Collection, Set, Callable
from datetime import timedelta
from boot... | 0.471953 | 0.131145 |
import csv
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from copy import deepcopy
def load_csv(filename):
with open(filename, "r") as f:
reader = csv.reader(f)
data_list = list(reader)
res... | plot.py | import csv
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from copy import deepcopy
def load_csv(filename):
with open(filename, "r") as f:
reader = csv.reader(f)
data_list = list(reader)
res... | 0.52829 | 0.562056 |
from scipy.integrate import odeint
import os
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import sys
hstep = .01
sstep = .01
hmin = 0.
hmax = 2.
smin = 0.
smax = 3.
rr = np.array([.3,1.,3.])
LL3 = 1.2
LL4 = 0.22
dx = .01
s0 = .01
h0 = .01
y0 = np.array([h0,s0])
x = np.arange(0,1,dx)
... | draftplot_PWrunoff.py | from scipy.integrate import odeint
import os
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import sys
hstep = .01
sstep = .01
hmin = 0.
hmax = 2.
smin = 0.
smax = 3.
rr = np.array([.3,1.,3.])
LL3 = 1.2
LL4 = 0.22
dx = .01
s0 = .01
h0 = .01
y0 = np.array([h0,s0])
x = np.arange(0,1,dx)
... | 0.255065 | 0.298964 |
__author__ = 'isparks'
import unittest
from requests_mauth.client import MAuth
import time
from requests import Request
import os
import json
class RequestMock(object):
"""Simple mock for a request object"""
def __init__(self, method, url, body):
self.method = method
self.url = url
se... | tests/client_test.py | __author__ = 'isparks'
import unittest
from requests_mauth.client import MAuth
import time
from requests import Request
import os
import json
class RequestMock(object):
"""Simple mock for a request object"""
def __init__(self, method, url, body):
self.method = method
self.url = url
se... | 0.562657 | 0.239027 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
from sys import platform
from multiprocessing import Process, Queue
import traceback
import logging
import numpy as np
import random
import requests
"""
from pyvirtualdisplay... | test/parallelize.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
from sys import platform
from multiprocessing import Process, Queue
import traceback
import logging
import numpy as np
import random
import requests
"""
from pyvirtualdisplay... | 0.177989 | 0.078148 |
# http://modo.sdk.thefoundry.co.uk//td-sdk/examples.html
# ----------------------------------------------------------------
# Xfrog Plants for MODO を V-RayのGPUレンダリングに対応させる
#
# 基本的な処理の流れ
# 1. Materialの種類をV-Ray Materialに変更
# 2. Stencilの画像マップをvmtl Opacity Grayscaleに変更
# 3. Stencilの画像マップのInvert設定を解除
# 4. Diffus... | Kz_Tools/Scripts/XFrog_VrayRenderSettings.py |
# http://modo.sdk.thefoundry.co.uk//td-sdk/examples.html
# ----------------------------------------------------------------
# Xfrog Plants for MODO を V-RayのGPUレンダリングに対応させる
#
# 基本的な処理の流れ
# 1. Materialの種類をV-Ray Materialに変更
# 2. Stencilの画像マップをvmtl Opacity Grayscaleに変更
# 3. Stencilの画像マップのInvert設定を解除
# 4. Diffus... | 0.222447 | 0.207998 |
import pandas as pd
#---------------------------------------------------------------------------------------------------
#Creating Data files - DataFrames & Series
#To create DataFrames.
first_df = pd.DataFrame({'A': [50, 21, 34, 99, 21, 231], 'B': [131, 2, 342, 563, 90, 88], 'C' : [12, 22, 55, 98, 94, 21], 'D' : [1... | Pandas_Cheat_Sheet.py | import pandas as pd
#---------------------------------------------------------------------------------------------------
#Creating Data files - DataFrames & Series
#To create DataFrames.
first_df = pd.DataFrame({'A': [50, 21, 34, 99, 21, 231], 'B': [131, 2, 342, 563, 90, 88], 'C' : [12, 22, 55, 98, 94, 21], 'D' : [1... | 0.26971 | 0.490419 |
from __future__ import absolute_import
import cv2
import numpy as np
import torch
import numbers
import torch
def real(img):
return img[..., 0]
def imag(img):
return img[..., 1]
def conj(img):
img = img.copy()
img[..., 1] = -img[..., 1]
return img
def fft2(img):
img = np.float32(img)
... | lib/utils/complex.py | from __future__ import absolute_import
import cv2
import numpy as np
import torch
import numbers
import torch
def real(img):
return img[..., 0]
def imag(img):
return img[..., 1]
def conj(img):
img = img.copy()
img[..., 1] = -img[..., 1]
return img
def fft2(img):
img = np.float32(img)
... | 0.751283 | 0.534005 |
import falcon
from bayesapi.resources import BaseResource
from bayesapi.validation import validate
import bayesapi.history
def add_anomaly_data(cfg, result):
last_q_data = bayesapi.history.read(cfg, "anomaly")
q_data = {}
for r in last_q_data['result']:
q_data[r['row-id']] = r['probability']
... | bayesapi/resources/column_data.py | import falcon
from bayesapi.resources import BaseResource
from bayesapi.validation import validate
import bayesapi.history
def add_anomaly_data(cfg, result):
last_q_data = bayesapi.history.read(cfg, "anomaly")
q_data = {}
for r in last_q_data['result']:
q_data[r['row-id']] = r['probability']
... | 0.226014 | 0.166998 |
class serie(object):
def __init__(self,nome,valor,ano=2020,temporada=1,duracao=40):
self.nome = nome
self.valor = valor
self.ano = ano
self.temporada = temporada
self.duracao = duracao
def get_nome(self):
return self.nome
def get_valor(self):
return s... | faculdade2.0/aula 7/exercicio/Rodrigo_Alaor.py | class serie(object):
def __init__(self,nome,valor,ano=2020,temporada=1,duracao=40):
self.nome = nome
self.valor = valor
self.ano = ano
self.temporada = temporada
self.duracao = duracao
def get_nome(self):
return self.nome
def get_valor(self):
return s... | 0.268941 | 0.169887 |
from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import json
import sys
from pathlib import Path
from io import StringIO
PREFIX = """
## Document Status
Work in Progress
## Well known API endpoints
This document summar... | python_scripts/api2md.py | from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import json
import sys
from pathlib import Path
from io import StringIO
PREFIX = """
## Document Status
Work in Progress
## Well known API endpoints
This document summar... | 0.495606 | 0.198336 |
import kubernetes.client
import os
import event
# Main code path
if 'TAKE_ACTION' not in os.environ:
raise EnvironmentError("Environment variable TAKE_ACTION missing")
TAKE_ACTION = os.getenv('TAKE_ACTION')
if TAKE_ACTION != 'Hibernating' and TAKE_ACTION != 'Running':
raise SyntaxError("TAKE_ACTION must be s... | hibernate-cronjob/action.py |
import kubernetes.client
import os
import event
# Main code path
if 'TAKE_ACTION' not in os.environ:
raise EnvironmentError("Environment variable TAKE_ACTION missing")
TAKE_ACTION = os.getenv('TAKE_ACTION')
if TAKE_ACTION != 'Hibernating' and TAKE_ACTION != 'Running':
raise SyntaxError("TAKE_ACTION must be s... | 0.261897 | 0.090213 |
from model import *
import torch.utils.data
import torchvision.transforms as transforms
import argparse
import torch
import torchvision
import torch.nn as nn
import shutil
import os
device = torch.device("cuda" if use_cuda else "cpu")
class multiNet():
def __init__(self, model_files):
self.model_files = m... | ensemble_model.py | from model import *
import torch.utils.data
import torchvision.transforms as transforms
import argparse
import torch
import torchvision
import torch.nn as nn
import shutil
import os
device = torch.device("cuda" if use_cuda else "cpu")
class multiNet():
def __init__(self, model_files):
self.model_files = m... | 0.68941 | 0.46557 |
from aqt.qt import *
from aqt.utils import showWarning, tooltip
import requests
from aqt import mw
from .forms import user_info
from .config_manager import write_config
class start_user_info(QDialog):
def __init__(self, user_clicked, enabled, parent=None):
self.parent = parent
self.user_clicked = user... | userInfo.py | from aqt.qt import *
from aqt.utils import showWarning, tooltip
import requests
from aqt import mw
from .forms import user_info
from .config_manager import write_config
class start_user_info(QDialog):
def __init__(self, user_clicked, enabled, parent=None):
self.parent = parent
self.user_clicked = user... | 0.247532 | 0.111967 |
# Входные параметры: 1. Путь к файлу change_log.txt 2: Имя ветки
# Идея: Открываем файл chnge_log.txt, считываем первую строку (там должна быть версия(tag) ввиде x.x.x).
# Затем считываем из репозитория (ветка из входных параметров) последние 10 коммитов.
# Проходим по ним и если встречаем коммит с меткой tag и он не... | change_log.py |
# Входные параметры: 1. Путь к файлу change_log.txt 2: Имя ветки
# Идея: Открываем файл chnge_log.txt, считываем первую строку (там должна быть версия(tag) ввиде x.x.x).
# Затем считываем из репозитория (ветка из входных параметров) последние 10 коммитов.
# Проходим по ним и если встречаем коммит с меткой tag и он не... | 0.110399 | 0.522263 |
import sys
t_id=sys.argv[1]
import kanboard
kb = kanboard.Client('http://192.168.100.143/kanboard/jsonrpc.php', 'jsonrpc', '392dc75baf66ae2205e9d0655a3e150c5766d011031658c7a1f3d152f5ef')
AllInternalTaskLinks=kb.getAllTaskLinks(task_id=t_id)
UpdateSwitch=0
for i in range(0,len(AllInternalTaskLinks)):
InternalTaskLi... | UpdateRelatedTaskController.py |
import sys
t_id=sys.argv[1]
import kanboard
kb = kanboard.Client('http://192.168.100.143/kanboard/jsonrpc.php', 'jsonrpc', '392dc75baf66ae2205e9d0655a3e150c5766d011031658c7a1f3d152f5ef')
AllInternalTaskLinks=kb.getAllTaskLinks(task_id=t_id)
UpdateSwitch=0
for i in range(0,len(AllInternalTaskLinks)):
InternalTaskLi... | 0.060411 | 0.038611 |
import tensorflow as tf
__weights_dict = dict()
is_train = False
def load_weights(weight_file):
import numpy as np
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes').item()
return ... | retina_tf.py | import tensorflow as tf
__weights_dict = dict()
is_train = False
def load_weights(weight_file):
import numpy as np
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes').item()
return ... | 0.676299 | 0.419529 |
__version__ = '0.1.0'
from natume.client import WebClient
from natume.parser import DSLParser
from natume.testcase import WebTestCase, DSLWebTestCase
from natume.util import import_module_from_file
__all__ = [
'WebClient',
'DSLParser',
'WebClient',
'WebTestCase',
'DSLWebTestCase',
'Natume']... | natume/__init__.py |
__version__ = '0.1.0'
from natume.client import WebClient
from natume.parser import DSLParser
from natume.testcase import WebTestCase, DSLWebTestCase
from natume.util import import_module_from_file
__all__ = [
'WebClient',
'DSLParser',
'WebClient',
'WebTestCase',
'DSLWebTestCase',
'Natume']... | 0.395251 | 0.154249 |
from datetime import date, timedelta
# All capitalized variables used in the project are declared here.
# [REDMINE]
# [Required]
# Parameters used to connect to Redmine server
# Redmine URL
REDMINE_URL = 'http://www.redmine.org'
# Redmine API Key
REDMINE_KEY = ''
# [Optional]
# Other settings, default values provi... | settings.py | from datetime import date, timedelta
# All capitalized variables used in the project are declared here.
# [REDMINE]
# [Required]
# Parameters used to connect to Redmine server
# Redmine URL
REDMINE_URL = 'http://www.redmine.org'
# Redmine API Key
REDMINE_KEY = ''
# [Optional]
# Other settings, default values provi... | 0.628521 | 0.160661 |
import sys
import os
import os.path
from svn import repos, fs, delta, core
### DEAR USER: Please populate the test_props() and test_path_change()
### to do your bidding.
def test_props(props):
"""Validate the PROPS (a dictionary mapping property names to
values) set on the transaction. Return 0 if all is wel... | contrib/hook-scripts/pre-commit-check.py |
import sys
import os
import os.path
from svn import repos, fs, delta, core
### DEAR USER: Please populate the test_props() and test_path_change()
### to do your bidding.
def test_props(props):
"""Validate the PROPS (a dictionary mapping property names to
values) set on the transaction. Return 0 if all is wel... | 0.498047 | 0.273951 |
from sixtypical.ast import Program
from sixtypical.model import RoutineType, VectorType
def find_routines_matching_type(program, type_):
"""Return the subset of routines of the program whose value
may be assigned to a location of the given type_ (typically
a vector)."""
return [r for r in program.rout... | src/sixtypical/callgraph.py | from sixtypical.ast import Program
from sixtypical.model import RoutineType, VectorType
def find_routines_matching_type(program, type_):
"""Return the subset of routines of the program whose value
may be assigned to a location of the given type_ (typically
a vector)."""
return [r for r in program.rout... | 0.706899 | 0.34798 |
import torch.nn as nn
import numpy as np
import torch
import time
"""
name:window-based two prediction results fusion function
paramaters:
method: 1 standard deviation all bands;
2 standard deviation each band;
3 mean all bands;
4 mean each band;
rimgx: t1... | twopredictions_fusion_window.py | import torch.nn as nn
import numpy as np
import torch
import time
"""
name:window-based two prediction results fusion function
paramaters:
method: 1 standard deviation all bands;
2 standard deviation each band;
3 mean all bands;
4 mean each band;
rimgx: t1... | 0.287868 | 0.473779 |
import random
import evennia
from enum import Enum
from evennia.utils import create
from evennia.contrib import gendersub
from world.languages import Language
from world.occupations import Occupation
from world.occupations import OccupationTable
import typeclasses.auras as auras
from world.birthaugur import BirthAugur... | typeclasses/characters.py | import random
import evennia
from enum import Enum
from evennia.utils import create
from evennia.contrib import gendersub
from world.languages import Language
from world.occupations import Occupation
from world.occupations import OccupationTable
import typeclasses.auras as auras
from world.birthaugur import BirthAugur... | 0.48121 | 0.223007 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from omsignal.utils.transform.preprocessor import Preprocessor
class gaussian_noise(nn.Module):
def __init__(self, device, std=0.1, is_relative_detach=True):
super().__init__()
self.device = device
self.std = std
... | omsignal/models/lstm.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from omsignal.utils.transform.preprocessor import Preprocessor
class gaussian_noise(nn.Module):
def __init__(self, device, std=0.1, is_relative_detach=True):
super().__init__()
self.device = device
self.std = std
... | 0.957445 | 0.33512 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .blocks import *
class SegNet(nn.Module):
def __init__(self,
nb_channel=3,
nb_class=1,
base_kernel=64,):
super(SegNet, self).__init__()
kernels = [x * base_... | src/models/segnet.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .blocks import *
class SegNet(nn.Module):
def __init__(self,
nb_channel=3,
nb_class=1,
base_kernel=64,):
super(SegNet, self).__init__()
kernels = [x * base_... | 0.900581 | 0.428712 |
from functional import softmax
from datatype import Tensor
import numpy as np
class Loss:
"""Placeholder class for losses."""
def __init__(self):
"""Initialize the class with 0 gradient."""
self.grad = 0.0
def grad_fn(self, pred: Tensor, true: Tensor) -> Tensor:
"""Create placeho... | numpy_learn/loss.py | from functional import softmax
from datatype import Tensor
import numpy as np
class Loss:
"""Placeholder class for losses."""
def __init__(self):
"""Initialize the class with 0 gradient."""
self.grad = 0.0
def grad_fn(self, pred: Tensor, true: Tensor) -> Tensor:
"""Create placeho... | 0.954361 | 0.746971 |
import socketio
from aiohttp import web
import aiohttp_cors
import asyncio
from time import sleep
import input_jack as input_jack
from App import App
import numpy as np
mgr = socketio.AsyncRedisManager('redis://')
sio = socketio.AsyncServer(
client_manager=mgr,
ping_timeout=120,
pi... | src/SocketIOServer.py | import socketio
from aiohttp import web
import aiohttp_cors
import asyncio
from time import sleep
import input_jack as input_jack
from App import App
import numpy as np
mgr = socketio.AsyncRedisManager('redis://')
sio = socketio.AsyncServer(
client_manager=mgr,
ping_timeout=120,
pi... | 0.342791 | 0.080864 |
from functools import partial
from shapely.geometry import Polygon, MultiPolygon, MultiLineString, \
LineString, LinearRing, Point, MultiPoint
import pyproj
import numpy as np
from .feature import Feature, FeatureCollection
GEOJSON_PROJ = 'EPSG:4326' # Default/only projection used by GeoJSON
def get_projector(... | cogj/reproject.py | from functools import partial
from shapely.geometry import Polygon, MultiPolygon, MultiLineString, \
LineString, LinearRing, Point, MultiPoint
import pyproj
import numpy as np
from .feature import Feature, FeatureCollection
GEOJSON_PROJ = 'EPSG:4326' # Default/only projection used by GeoJSON
def get_projector(... | 0.896075 | 0.594904 |
import os
posts = os.listdir('../md_posts')
# print(posts)
# sort posts by date ---------------------------------------
# convert dates to days
def convertDateToDays(post):
date = post[:post.find(' ')]
DMY = date.split('-')
day = int(DMY[0])
month = int(DMY[1])
year = int(DMY[2])
return day + ... | generate/genFiles.py | import os
posts = os.listdir('../md_posts')
# print(posts)
# sort posts by date ---------------------------------------
# convert dates to days
def convertDateToDays(post):
date = post[:post.find(' ')]
DMY = date.split('-')
day = int(DMY[0])
month = int(DMY[1])
year = int(DMY[2])
return day + ... | 0.05719 | 0.082883 |
import pandas as pd
import numpy as np
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Panel, CheckboxGroup
from bokeh.models.widgets import TableColumn, DataTable
from unidecode import unidecode
from scripts.analyser import ConvoStats
def total_stats_tab(convoStats):
conversati... | fbmessages/scripts/total_stats.py | import pandas as pd
import numpy as np
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Panel, CheckboxGroup
from bokeh.models.widgets import TableColumn, DataTable
from unidecode import unidecode
from scripts.analyser import ConvoStats
def total_stats_tab(convoStats):
conversati... | 0.522689 | 0.415314 |
import pandas as pd
from ne.stats import Stats
def read(fd, f, key):
l = fd.readline().strip()
if l[:len(key)] != key:
raise Exception('malformed, expected "{}" but got "{}"'.format(key, l))
return f(l[len(key)+2:])
def parse_neat(fname):
with open(fname, 'r') as fd:
config = { }
... | parse.py | import pandas as pd
from ne.stats import Stats
def read(fd, f, key):
l = fd.readline().strip()
if l[:len(key)] != key:
raise Exception('malformed, expected "{}" but got "{}"'.format(key, l))
return f(l[len(key)+2:])
def parse_neat(fname):
with open(fname, 'r') as fd:
config = { }
... | 0.447943 | 0.225033 |
import pytest
import ezdxf
from ezdxf.entities import is_dxf_object
@pytest.fixture(scope="module")
def collection_ro():
"""Creates a read only document"""
doc = ezdxf.new()
doc.entitydb.locked = True
return doc.mleader_styles
class TestGetterMethods:
def test_len(self, collection_ro):
... | tests/test_04_dxf_high_level_structs/test_404b_object_collections.py | import pytest
import ezdxf
from ezdxf.entities import is_dxf_object
@pytest.fixture(scope="module")
def collection_ro():
"""Creates a read only document"""
doc = ezdxf.new()
doc.entitydb.locked = True
return doc.mleader_styles
class TestGetterMethods:
def test_len(self, collection_ro):
... | 0.634656 | 0.568356 |
from django.contrib.admin import SimpleListFilter
from django.core.paginator import Paginator
from django.db import connections
from django.db.models.sql.datastructures import EmptyResultSet
from django.utils.functional import cached_property
from django.urls import reverse
from django.utils.html import format_html
fr... | share/admin/util.py | from django.contrib.admin import SimpleListFilter
from django.core.paginator import Paginator
from django.db import connections
from django.db.models.sql.datastructures import EmptyResultSet
from django.utils.functional import cached_property
from django.urls import reverse
from django.utils.html import format_html
fr... | 0.508056 | 0.102664 |
import socket
import time
import xml.etree.ElementTree as ET
import graphiteeagle
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright 2017 <NAME>'
__license__ = 'Apache License, Version 2.0'
class CarbonHost(object):
"""
Object Class for a Carbon Host.
"""
def __init__(self, host, port=No... | graphiteeagle/classes.py | import socket
import time
import xml.etree.ElementTree as ET
import graphiteeagle
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright 2017 <NAME>'
__license__ = 'Apache License, Version 2.0'
class CarbonHost(object):
"""
Object Class for a Carbon Host.
"""
def __init__(self, host, port=No... | 0.527803 | 0.080502 |
from datetime import datetime
from city_scrapers_core.constants import BOARD
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
class PaLiquorboardSpider(CityScrapersSpider):
"""Spider is a class that scapy provides to us,
this spider will inherit prope... | city_scrapers/spiders/pa_liquorboard.py | from datetime import datetime
from city_scrapers_core.constants import BOARD
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
class PaLiquorboardSpider(CityScrapersSpider):
"""Spider is a class that scapy provides to us,
this spider will inherit prope... | 0.747524 | 0.291851 |
import ctypes
import sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def block(url):
file = open("C://Windows//System32//drivers//etc//hosts", 'a+')
file.seek(0)
content = file.read()
if url in content:
print(... | WebBlock.py | import ctypes
import sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def block(url):
file = open("C://Windows//System32//drivers//etc//hosts", 'a+')
file.seek(0)
content = file.read()
if url in content:
print(... | 0.062922 | 0.054299 |
import os
import sys
import re
from math import ceil
from subprocess import PIPE, Popen, TimeoutExpired
script_directory_path = os.path.dirname(__file__)
rules_directory_path = os.path.join(os.path.dirname(os.path.dirname(script_directory_path)), 'rules')
script_path = os.path.join(script_directory_path, 'regexp-asse... | util/regexp-assemble/regexp-compare.py |
import os
import sys
import re
from math import ceil
from subprocess import PIPE, Popen, TimeoutExpired
script_directory_path = os.path.dirname(__file__)
rules_directory_path = os.path.join(os.path.dirname(os.path.dirname(script_directory_path)), 'rules')
script_path = os.path.join(script_directory_path, 'regexp-asse... | 0.079449 | 0.09645 |
import torch as th
import torchlib as tl
import matplotlib
matplotlib.use('Tkagg')
import matplotlib.pyplot as plt
lr, num_epochs, batch_size, num_batch = 5e-3, 500, 8, 750
# lr, num_epochs, batch_size, num_batch = 1e-2, 1000, 8, 750
params = {th.nn.parameter.Parameter(th.zeros(128), requires_grad=True),
th... | examples/optim/demo_plot_lr.py | import torch as th
import torchlib as tl
import matplotlib
matplotlib.use('Tkagg')
import matplotlib.pyplot as plt
lr, num_epochs, batch_size, num_batch = 5e-3, 500, 8, 750
# lr, num_epochs, batch_size, num_batch = 1e-2, 1000, 8, 750
params = {th.nn.parameter.Parameter(th.zeros(128), requires_grad=True),
th... | 0.470493 | 0.352731 |
from sstcam_simulation.data import get_data
from sstcam_simulation.utils.photon_incidence_angles import PhotonIncidenceAnglesWindow
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
class Window:
def __init__(self, incidence_angles, transmission):
... | sstcam_simulation/utils/window_durham_needle.py | from sstcam_simulation.data import get_data
from sstcam_simulation.utils.photon_incidence_angles import PhotonIncidenceAnglesWindow
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
class Window:
def __init__(self, incidence_angles, transmission):
... | 0.579995 | 0.427098 |
import boto3
import botocore
from botocore import exceptions
import datetime
import re
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
REGION = '{}'
DB_INSTANCE_CLASS = '{}'
DB_SUBNET = '{}'
PRODUCTION_INSTANCE = '{}'
PRE_PRODUCTION_INSTANCE = 'preproduction-{}'.format(PRODUCTION_INSTANCE)
... | lambda_function.py | import boto3
import botocore
from botocore import exceptions
import datetime
import re
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
REGION = '{}'
DB_INSTANCE_CLASS = '{}'
DB_SUBNET = '{}'
PRODUCTION_INSTANCE = '{}'
PRE_PRODUCTION_INSTANCE = 'preproduction-{}'.format(PRODUCTION_INSTANCE)
... | 0.273671 | 0.061763 |
from optparse import OptionParser
import os
import subprocess
this_directory = os.path.dirname(os.path.realpath(__file__)) + "/"
import sys
sys.path.insert(0,os.path.join(this_directory,"..","job_launching"))
import common
import re
import shutil
import glob
import datetime
import yaml
parser = OptionParser()
parser.... | util/correlation/get_hw_stats.py |
from optparse import OptionParser
import os
import subprocess
this_directory = os.path.dirname(os.path.realpath(__file__)) + "/"
import sys
sys.path.insert(0,os.path.join(this_directory,"..","job_launching"))
import common
import re
import shutil
import glob
import datetime
import yaml
parser = OptionParser()
parser.... | 0.191365 | 0.096323 |
from fastai2.vision.all import *
from fastai2.basics import *
from sklearn.metrics import recall_score
def get_labels(x): return tensor(x[1:4].astype('uint8'))
def construct_vocab(df):
return L(L(o for o in df[class_name].unique() if o==o).sorted() for class_name in df.columns.tolist())
clas... | src/train_utils/bengali_funcs.py | from fastai2.vision.all import *
from fastai2.basics import *
from sklearn.metrics import recall_score
def get_labels(x): return tensor(x[1:4].astype('uint8'))
def construct_vocab(df):
return L(L(o for o in df[class_name].unique() if o==o).sorted() for class_name in df.columns.tolist())
clas... | 0.847084 | 0.40925 |
import os
import skimage.io
from skimage.color import rgb2gray
from scipy.io import loadmat
import numpy as np
import cv2
import math
import warnings
import random
import h5py
import scipy
warnings.filterwarnings("ignore")
root = "../../data/shtu_dataset"
def gaussian_kernel(image, points):
if image.shape[-1] ==... | Deep-Learning/Crowd-Count/src/data_preprocess/crop.py |
import os
import skimage.io
from skimage.color import rgb2gray
from scipy.io import loadmat
import numpy as np
import cv2
import math
import warnings
import random
import h5py
import scipy
warnings.filterwarnings("ignore")
root = "../../data/shtu_dataset"
def gaussian_kernel(image, points):
if image.shape[-1] ==... | 0.363647 | 0.398231 |
from colorama import Fore, Style
from .logic_actions_utils import execute_command, upload_file, change_fileorfolder_user_owner, restart_service
def rsyslog_client(instance, arg, verbose=True):
""" Configure rsyslog client to send log to log server on the remote instance """
facility = 1
execute_command(ins... | logic_actions/logic_actions_rsyslog.py | from colorama import Fore, Style
from .logic_actions_utils import execute_command, upload_file, change_fileorfolder_user_owner, restart_service
def rsyslog_client(instance, arg, verbose=True):
""" Configure rsyslog client to send log to log server on the remote instance """
facility = 1
execute_command(ins... | 0.140013 | 0.10079 |
from openstack import exceptions
from openstack import resource
from openstack import utils
from otcextensions.common import format as otc_format
class Snapshot(resource.Resource):
base_path = '/clusters/%(cluster_id)s/index_snapshots'
resources_key = 'backups'
resource_key = '/index_snapshot'
allo... | otcextensions/sdk/css/v1/snapshot.py | from openstack import exceptions
from openstack import resource
from openstack import utils
from otcextensions.common import format as otc_format
class Snapshot(resource.Resource):
base_path = '/clusters/%(cluster_id)s/index_snapshots'
resources_key = 'backups'
resource_key = '/index_snapshot'
allo... | 0.749546 | 0.171928 |
import sys, time, math, matplotlib, sys, os, pygame
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)))
from amrrt.space import StateSpace
from amrrt.diffusion_map import DiffusionMap, GridGraph
... | demos/shortest.py | import sys, time, math, matplotlib, sys, os, pygame
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)))
from amrrt.space import StateSpace
from amrrt.diffusion_map import DiffusionMap, GridGraph
... | 0.080878 | 0.47993 |
class FizzBuzz:
def __init__(self):
self.custom_fizzbuzz_array = {
"custom_fizzbuzz":[
{"word":"fizz", "divisors":[3]},
{"word":"buzz", "divisors":[5]},
{"word":"fizzbuzz", "divisors":[3,5]}
]
}
def __is_divisor(self, num,... | fizzbuzz_api/FizzBuzz.py |
class FizzBuzz:
def __init__(self):
self.custom_fizzbuzz_array = {
"custom_fizzbuzz":[
{"word":"fizz", "divisors":[3]},
{"word":"buzz", "divisors":[5]},
{"word":"fizzbuzz", "divisors":[3,5]}
]
}
def __is_divisor(self, num,... | 0.720368 | 0.299316 |
from aws_cdk import (
aws_cloudformation as cfn,
aws_logs as cw_logs,
aws_lambda as _lambda,
aws_apigateway as api_gw,
core
)
class Apigateway(cfn.NestedStack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
api_log... | the-waf-apigateway/python/the_waf_apigateway/apigateway.py | from aws_cdk import (
aws_cloudformation as cfn,
aws_logs as cw_logs,
aws_lambda as _lambda,
aws_apigateway as api_gw,
core
)
class Apigateway(cfn.NestedStack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
api_log... | 0.662032 | 0.05752 |
from Exscript import Account
from Exscript.stdlib.util import secure_function
@secure_function
def authenticate(scope):
"""
Looks for any username/password prompts on the current connection
and logs in using the login information that was passed to Exscript.
"""
scope.get('__connection__').app_aut... | Exscript/stdlib/connection.py | from Exscript import Account
from Exscript.stdlib.util import secure_function
@secure_function
def authenticate(scope):
"""
Looks for any username/password prompts on the current connection
and logs in using the login information that was passed to Exscript.
"""
scope.get('__connection__').app_aut... | 0.707809 | 0.391871 |