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 collections
import functools
import itertools
import more_itertools
import operator
import unittest
from more_itertools.recipes import flatten
from darwin import iterable, util
class TestIterable(unittest.TestCase):
def test_map(self):
test_fn = functools.partial(operator.add, 5)
values = range(12)... | tests/test_iterable.py | import collections
import functools
import itertools
import more_itertools
import operator
import unittest
from more_itertools.recipes import flatten
from darwin import iterable, util
class TestIterable(unittest.TestCase):
def test_map(self):
test_fn = functools.partial(operator.add, 5)
values = range(12)... | 0.466116 | 0.53783 |
import argparse
import os
import numpy as np
import json
import yolo
import tensorflow as tf
from _common.utils import normalize, evaluate, makedirs, init_session, unfreeze_model
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard
from tensorflow.keras.optimizers import Adam, SGD, RMSp... | TSD/src/train_grid.py |
import argparse
import os
import numpy as np
import json
import yolo
import tensorflow as tf
from _common.utils import normalize, evaluate, makedirs, init_session, unfreeze_model
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard
from tensorflow.keras.optimizers import Adam, SGD, RMSp... | 0.622459 | 0.154026 |
from sklearn.preprocessing import StandardScaler
from abc import ABC, abstractmethod
import numpy as np
class DistanceMetric(ABC):
"""Computes distances and defines the optimization model for both
exploration and penalty.
Parameters
----------
-
Attributes
----------
-
"""
... | entmoot/learning/distance_based_std.py | from sklearn.preprocessing import StandardScaler
from abc import ABC, abstractmethod
import numpy as np
class DistanceMetric(ABC):
"""Computes distances and defines the optimization model for both
exploration and penalty.
Parameters
----------
-
Attributes
----------
-
"""
... | 0.965406 | 0.844858 |
import tensorflow as tf
def get_model(X, opts):
"""Given input tensor and opts, return output Tensor of a CNN"""
conv1 = tf.layers.conv2d(
tf.reshape(X, [opts.batch_size, 3, 160, 320]),
filters=16,
kernel_size=(8, 8),
strides=(4, 4),
padding='same',
kernel_initi... | models/model.py | import tensorflow as tf
def get_model(X, opts):
"""Given input tensor and opts, return output Tensor of a CNN"""
conv1 = tf.layers.conv2d(
tf.reshape(X, [opts.batch_size, 3, 160, 320]),
filters=16,
kernel_size=(8, 8),
strides=(4, 4),
padding='same',
kernel_initi... | 0.908715 | 0.571229 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('dcolumns', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Author',... | example_site/books/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 = [
('dcolumns', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Author',... | 0.602646 | 0.133218 |
try:
import logging
except:
from simpletal import DummyLogger as logging
from pubtal import SiteUtils
import updateSite
import unittest, copy, os.path
if __name__ == '__main__':
logging.basicConfig()
LOCATION=''
else:
LOCATION=os.path.join(os.getcwd(), "tests", "Content", "Catalogue")
root = logging.getLogger(... | tests/Content/Catalogue/XHTMLTests.py | try:
import logging
except:
from simpletal import DummyLogger as logging
from pubtal import SiteUtils
import updateSite
import unittest, copy, os.path
if __name__ == '__main__':
logging.basicConfig()
LOCATION=''
else:
LOCATION=os.path.join(os.getcwd(), "tests", "Content", "Catalogue")
root = logging.getLogger(... | 0.279337 | 0.080792 |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app
column1 = dbc.Col(
[
dcc.Markdown(
"""
## Insights
The figure below shows ... | pages/insights_long.py | import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app
column1 = dbc.Col(
[
dcc.Markdown(
"""
## Insights
The figure below shows ... | 0.50415 | 0.317294 |
from impedance.models.circuits import BaseCircuit, CustomCircuit, Randles
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import pytest
# get example data
data = np.genfromtxt(os.path.join("./data/", "exampleData.csv"), delimiter=",")
f = data[:, 0]
Z = data[:, 1] + 1j * data[:, 2]
def test... | src/elchempy/experiments/_EIS/impedancepy/impedance/tests/test_circuits.py | from impedance.models.circuits import BaseCircuit, CustomCircuit, Randles
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import pytest
# get example data
data = np.genfromtxt(os.path.join("./data/", "exampleData.csv"), delimiter=",")
f = data[:, 0]
Z = data[:, 1] + 1j * data[:, 2]
def test... | 0.761538 | 0.706368 |
import os
import sys
import popen2
import configuration_client
import pprint
def get_movers(config):
movers = {}
for key in config.keys():
if key.find('.mover') > 0 and key.find('null') == -1:
movers[key] = config[key]
return movers
def get_config(host, port):
dict = configuratio... | sbin/drives_info.py | import os
import sys
import popen2
import configuration_client
import pprint
def get_movers(config):
movers = {}
for key in config.keys():
if key.find('.mover') > 0 and key.find('null') == -1:
movers[key] = config[key]
return movers
def get_config(host, port):
dict = configuratio... | 0.07321 | 0.065635 |
import os, pwd, logging,tempfile, re
from fabric import task
from gwaportal_hpc_pipeline import *
SBATCH_PATTERN = re.compile(r"Submitted batch job ([0-9]*)")
USER = os.environ.get('HPC_USER',pwd.getpwuid(os.getuid()).pw_name)
HOME = '/users/%s' % USER
SCRIPTS_FOLDER = os.path.join(HOME,"scripts/gwaportal")
GWAS_SCRI... | gwaportal_hpc_pipeline/fabfile.py | import os, pwd, logging,tempfile, re
from fabric import task
from gwaportal_hpc_pipeline import *
SBATCH_PATTERN = re.compile(r"Submitted batch job ([0-9]*)")
USER = os.environ.get('HPC_USER',pwd.getpwuid(os.getuid()).pw_name)
HOME = '/users/%s' % USER
SCRIPTS_FOLDER = os.path.join(HOME,"scripts/gwaportal")
GWAS_SCRI... | 0.152001 | 0.087447 |
import io
import pstats
import cProfile
import lib_hook
from .init import init
def main():
"""
Entrypoint of clang-hook command. It support both standalone mode and network mode.
"""
args, compiler, logger, output_handler, sock, debug = init()
mode, input_base_ext = lib_hook.get_mode(args, logge... | clang_hook/main.py | import io
import pstats
import cProfile
import lib_hook
from .init import init
def main():
"""
Entrypoint of clang-hook command. It support both standalone mode and network mode.
"""
args, compiler, logger, output_handler, sock, debug = init()
mode, input_base_ext = lib_hook.get_mode(args, logge... | 0.176033 | 0.068226 |
SCRIPT_NAME = "buffer_swap"
SCRIPT_AUTHOR = "<NAME>. 'FiXato' Slagter <fixato [at] gmail [dot] com>"
SCRIPT_VERSION = "0.3"
SCRIPT_LICENSE = "MIT"
SCRIPT_DESC = "Swaps given 2 buffers"
SCRIPT_COMMAND = "swap"
SCRIPT_CLOSE_CB = "close_cb"
import_ok = True
try:
import weechat
except ImportError:
print ... | buffer_swap.py | SCRIPT_NAME = "buffer_swap"
SCRIPT_AUTHOR = "<NAME>. 'FiXato' Slagter <fixato [at] gmail [dot] com>"
SCRIPT_VERSION = "0.3"
SCRIPT_LICENSE = "MIT"
SCRIPT_DESC = "Swaps given 2 buffers"
SCRIPT_COMMAND = "swap"
SCRIPT_CLOSE_CB = "close_cb"
import_ok = True
try:
import weechat
except ImportError:
print ... | 0.303009 | 0.091707 |
import os
import sys
import base64
import logger
import generator.savtools as savtools
import generator.savdecoder as savdecoder
from config import SAV_DIRECTORY
TAG = "CompilerPostProcess"
def perform(session):
with open(SAV_DIRECTORY + '/bin/main_sram0.bin', 'rb') as f:
s0 = f.read()
with open(SAV... | server/generator/postprocess.py | import os
import sys
import base64
import logger
import generator.savtools as savtools
import generator.savdecoder as savdecoder
from config import SAV_DIRECTORY
TAG = "CompilerPostProcess"
def perform(session):
with open(SAV_DIRECTORY + '/bin/main_sram0.bin', 'rb') as f:
s0 = f.read()
with open(SAV... | 0.170854 | 0.104432 |
from django.test import TestCase
from . models import *
# Create your tests here.
class NeighbourhoodTestClass(TestCase):
'''
This is a class that perform unnittest behaviour on the Image Model.
'''
def setUp(self):
self.neighbourhood_one = Neighbourhood(name='bombklat',location='Alab... | neighbour/tests.py | from django.test import TestCase
from . models import *
# Create your tests here.
class NeighbourhoodTestClass(TestCase):
'''
This is a class that perform unnittest behaviour on the Image Model.
'''
def setUp(self):
self.neighbourhood_one = Neighbourhood(name='bombklat',location='Alab... | 0.434821 | 0.498962 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Creat... | voting/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Creat... | 0.538983 | 0.147248 |
from six.moves import range
import tensorflow as tf
from cleverhans.picklable_model import MLP, Dropout
def test_no_drop():
"""test_no_drop: Make sure dropout does nothing by default (so it does not
cause stochasticity at test time)"""
model = MLP(input_shape=[1, 1], layers=[Dropout(name='output')])
x = tf.c... | cleverhans/tests/test_dropout.py | from six.moves import range
import tensorflow as tf
from cleverhans.picklable_model import MLP, Dropout
def test_no_drop():
"""test_no_drop: Make sure dropout does nothing by default (so it does not
cause stochasticity at test time)"""
model = MLP(input_shape=[1, 1], layers=[Dropout(name='output')])
x = tf.c... | 0.773345 | 0.411939 |
"""A very simple MNIST classifier."""
import argparse
import sys
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
ce_with_logits = tf.nn.softmax_cross_entropy_with_logits
FLAGS = None
def inference(x):
"""
Build the inference graph.
Parameters
----------
x : p... | ML/mnist/tensorflow-example/mnist_softmax.py | """A very simple MNIST classifier."""
import argparse
import sys
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
ce_with_logits = tf.nn.softmax_cross_entropy_with_logits
FLAGS = None
def inference(x):
"""
Build the inference graph.
Parameters
----------
x : p... | 0.869174 | 0.699049 |
import logging
from .exception import SyntaxException
from .lexer import Token
from .primitives import Rule, \
Optional, Repetition, Grouping, Alternation, Concatenation
logger = logging.getLogger('ebnf')
class Parser:
EQUALS = Token('=', Token.SYMBOL)
SEMICOLON = Token(';', Token.SYMBOL)
def __ini... | ebnf/parser.py |
import logging
from .exception import SyntaxException
from .lexer import Token
from .primitives import Rule, \
Optional, Repetition, Grouping, Alternation, Concatenation
logger = logging.getLogger('ebnf')
class Parser:
EQUALS = Token('=', Token.SYMBOL)
SEMICOLON = Token(';', Token.SYMBOL)
def __ini... | 0.665084 | 0.123815 |
import unittest
from extensions.front.ATenToEmbeddingBag import AtenToEmbeddingBag
from mo.utils.ir_engine.compare_graphs import compare_graphs
from mo.utils.unittest.graph import build_graph
nodes_attributes = {
'weights_inp': {'shape': None, 'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'indices_in... | model-optimizer/extensions/front/ATenToEmbeddingBag_test.py | import unittest
from extensions.front.ATenToEmbeddingBag import AtenToEmbeddingBag
from mo.utils.ir_engine.compare_graphs import compare_graphs
from mo.utils.unittest.graph import build_graph
nodes_attributes = {
'weights_inp': {'shape': None, 'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'indices_in... | 0.545286 | 0.47591 |
from __future__ import division
import logging
from numpy import sqrt
from numpy import clip
def make_sure_reasonable_conditioning(S):
max_cond = 1e6
cond = S.max() / S.min()
if cond > max_cond:
eps = (max_cond * S.min() - S.max()) / (1 - max_cond)
logger = logging.getLogger(__name__)
... | limix_qep/ep/util.py | from __future__ import division
import logging
from numpy import sqrt
from numpy import clip
def make_sure_reasonable_conditioning(S):
max_cond = 1e6
cond = S.max() / S.min()
if cond > max_cond:
eps = (max_cond * S.min() - S.max()) / (1 - max_cond)
logger = logging.getLogger(__name__)
... | 0.77343 | 0.594492 |
import json
import os
from datetime import date, time
import numpy as np
from dicom_parser.utils.value_representation import ValueRepresentation
from tests.fixtures import TEST_FILES_PATH
#: Expected parsed values to test age string (AS) data elements with.
AGE_STRINGS = {
"PatientAge": 27.0,
}
#: Expected pars... | tests/data_elements/fixtures.py | import json
import os
from datetime import date, time
import numpy as np
from dicom_parser.utils.value_representation import ValueRepresentation
from tests.fixtures import TEST_FILES_PATH
#: Expected parsed values to test age string (AS) data elements with.
AGE_STRINGS = {
"PatientAge": 27.0,
}
#: Expected pars... | 0.37605 | 0.419707 |
import os
import tempfile
import shutil
import pandas
from pysnpimpute.utils import (check_installation_of_required_softwares,
check_existence_of_paths,
run_cmd,
run_cmd_and_check)
def check_alignment_to_ref_panel(bfile, re... | pysnpimpute/strand_alignment.py | import os
import tempfile
import shutil
import pandas
from pysnpimpute.utils import (check_installation_of_required_softwares,
check_existence_of_paths,
run_cmd,
run_cmd_and_check)
def check_alignment_to_ref_panel(bfile, re... | 0.662906 | 0.272811 |
import dataclasses
from copy import deepcopy
from typing import Optional
from testcase import TestCase
from testcase import CT_REST_DEBUG
DEFAULT_LEN = 15
LOWEST_LEN = 8
MAXIMUM_LEN = 4095
@dataclasses.dataclass
class PasswordFlagTest:
flag: str
query: Optional[str] = None
# TODO: add positive regex her... | tests/pytest/test_generate.py | import dataclasses
from copy import deepcopy
from typing import Optional
from testcase import TestCase
from testcase import CT_REST_DEBUG
DEFAULT_LEN = 15
LOWEST_LEN = 8
MAXIMUM_LEN = 4095
@dataclasses.dataclass
class PasswordFlagTest:
flag: str
query: Optional[str] = None
# TODO: add positive regex her... | 0.5083 | 0.296272 |
import re
from typing import List, Union
from api import db
from api.models.card import Card, CardConjuration
from api.models.release import Release
from api.utils.helpers import str_or_int, stubify
from .stream import create_entity
MAGIC_COSTS = (
"basic",
"ceremonial",
"charm",
"illusion",
"nat... | api/services/card.py | import re
from typing import List, Union
from api import db
from api.models.card import Card, CardConjuration
from api.models.release import Release
from api.utils.helpers import str_or_int, stubify
from .stream import create_entity
MAGIC_COSTS = (
"basic",
"ceremonial",
"charm",
"illusion",
"nat... | 0.733833 | 0.417153 |
from unittest import TestCase
from mock import patch, ANY
from aws_lambda_builders.actions import (
BaseAction,
CopySourceAction,
Purpose,
CopyDependenciesAction,
MoveDependenciesAction,
CleanUpAction,
)
class TestBaseActionInheritance(TestCase):
def test_must_inherit(self):
class... | tests/unit/test_actions.py | from unittest import TestCase
from mock import patch, ANY
from aws_lambda_builders.actions import (
BaseAction,
CopySourceAction,
Purpose,
CopyDependenciesAction,
MoveDependenciesAction,
CleanUpAction,
)
class TestBaseActionInheritance(TestCase):
def test_must_inherit(self):
class... | 0.609524 | 0.334291 |
from unittest.mock import MagicMock
import pytest
from datastore.shared.di import injector
from datastore.shared.services import ReadDatabase
from datastore.shared.util import META_DELETED, META_POSITION, BadCodingError
from datastore.writer.core import (
DbCreateEvent,
DbDeleteEvent,
DbDeleteFieldsEvent,... | tests/writer/unit/core/test_event_executor.py | from unittest.mock import MagicMock
import pytest
from datastore.shared.di import injector
from datastore.shared.services import ReadDatabase
from datastore.shared.util import META_DELETED, META_POSITION, BadCodingError
from datastore.writer.core import (
DbCreateEvent,
DbDeleteEvent,
DbDeleteFieldsEvent,... | 0.72086 | 0.413773 |
import matplotlib.pyplot as plt
import pandas as pd
class Simulator_Core:
def __init__(self,optimizer,partner_reader):
self.optimizer=optimizer
self.partner_reader=partner_reader
self.optimizer.partner_id=self.partner_reader.partner_id
self.profits=[]
self.sustainded=[]
... | simulator_core.py | import matplotlib.pyplot as plt
import pandas as pd
class Simulator_Core:
def __init__(self,optimizer,partner_reader):
self.optimizer=optimizer
self.partner_reader=partner_reader
self.optimizer.partner_id=self.partner_reader.partner_id
self.profits=[]
self.sustainded=[]
... | 0.620507 | 0.320502 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from scipy.stats import pearsonr
cc = pd.read_excel('classify.xlsx', index_col = 'city', sheet_name = 'first')
print(cc.head())
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import mak... | city_classification/city_classification.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from scipy.stats import pearsonr
cc = pd.read_excel('classify.xlsx', index_col = 'city', sheet_name = 'first')
print(cc.head())
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import mak... | 0.79909 | 0.577376 |
import re
from typing import Any
from typing import Optional
from ._compat import basestring
def parse_string(value, nullable=True): # type: (Any, bool) -> Optional[str]
if nullable and (value is None or value == "null"):
return
if value is None:
return "null"
if isinstance(value, boo... | src/clikit/utils/string.py | import re
from typing import Any
from typing import Optional
from ._compat import basestring
def parse_string(value, nullable=True): # type: (Any, bool) -> Optional[str]
if nullable and (value is None or value == "null"):
return
if value is None:
return "null"
if isinstance(value, boo... | 0.736116 | 0.32162 |
from django.urls import reverse
from django_rq import enqueue
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import NotFound
from rest_framework.parsers import FileUploadParser
from rest_framework.permissions impor... | toucan/canary_files/views.py | from django.urls import reverse
from django_rq import enqueue
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import NotFound
from rest_framework.parsers import FileUploadParser
from rest_framework.permissions impor... | 0.68658 | 0.106319 |
import pandas as pd
import reciprocalspaceship as rs
class DataSeries(pd.Series):
"""
One-dimensional ndarray with axis labels, representing a slice
of a DataSet. DataSeries objects inherit methods from ``pd.Series``,
and as such have support for statistical methods that automatically
exclude missi... | reciprocalspaceship/dataseries.py | import pandas as pd
import reciprocalspaceship as rs
class DataSeries(pd.Series):
"""
One-dimensional ndarray with axis labels, representing a slice
of a DataSet. DataSeries objects inherit methods from ``pd.Series``,
and as such have support for statistical methods that automatically
exclude missi... | 0.899602 | 0.793306 |
from pathlib import Path
import unittest
import tempfile
from . import BaseTest
from src.epjson_handler import EPJSON
# must import exceptions directly from test code
from src.epjson_handler import UniqueNameException, PyExpandObjectsTypeError, \
PyExpandObjectsFileNotFoundError, PyExpandObjectsSchemaError, Invali... | tests/test_epjson.py | from pathlib import Path
import unittest
import tempfile
from . import BaseTest
from src.epjson_handler import EPJSON
# must import exceptions directly from test code
from src.epjson_handler import UniqueNameException, PyExpandObjectsTypeError, \
PyExpandObjectsFileNotFoundError, PyExpandObjectsSchemaError, Invali... | 0.632389 | 0.486149 |
import datetime
import pytest
from badabump.changelog import (
ChangeLog,
COMMIT_TYPE_FEATURE,
ConventionalCommit,
version_header,
)
from badabump.enums import ChangeLogTypeEnum, FormatTypeEnum
CI_BREAKING_COMMIT = "ci!: Use badabump release bot for pushing tags"
DOCS_SCOPE_COMMIT = """docs(openapi... | tests/test_changelog.py | import datetime
import pytest
from badabump.changelog import (
ChangeLog,
COMMIT_TYPE_FEATURE,
ConventionalCommit,
version_header,
)
from badabump.enums import ChangeLogTypeEnum, FormatTypeEnum
CI_BREAKING_COMMIT = "ci!: Use badabump release bot for pushing tags"
DOCS_SCOPE_COMMIT = """docs(openapi... | 0.466116 | 0.321939 |
from __future__ import absolute_import, print_function, division
import unittest
import warnings
import numpy as np
try:
from numcodecs.msgpacks import LegacyMsgPack, MsgPack
default_codec = MsgPack()
# N.B., legacy codec is broken, see tests below. Also legacy code generates
# PendingDeprecationWar... | numcodecs/tests/test_msgpacks.py | from __future__ import absolute_import, print_function, division
import unittest
import warnings
import numpy as np
try:
from numcodecs.msgpacks import LegacyMsgPack, MsgPack
default_codec = MsgPack()
# N.B., legacy codec is broken, see tests below. Also legacy code generates
# PendingDeprecationWar... | 0.683102 | 0.419707 |
import cv2 as cv
import numpy as np
class ImageUtil(object):
@staticmethod
def crop_frame(frame, coordinate, normalized=True):
"""
Crop Frame
:param frame: cv mat object
:param coordinate: x,y coordinates [xmin, ymin, xmax, ymax]
:param normalized: if values normalized... | inference_services/facedetection/utils/image_utils.py |
import cv2 as cv
import numpy as np
class ImageUtil(object):
@staticmethod
def crop_frame(frame, coordinate, normalized=True):
"""
Crop Frame
:param frame: cv mat object
:param coordinate: x,y coordinates [xmin, ymin, xmax, ymax]
:param normalized: if values normalized... | 0.941741 | 0.562417 |
import matplotlib.pyplot as plt
import numpy as np
import os
from matplotlib import colors
import palettable.cartocolors.qualitative as qual_palettes
import pandas as pd
import pickle
import scipy
import seaborn as sns
blue = sns.color_palette()[0]
green = sns.color_palette()[1]
red = sns.color_palette()[2]
def make... | spatial_lda/visualization.py | import matplotlib.pyplot as plt
import numpy as np
import os
from matplotlib import colors
import palettable.cartocolors.qualitative as qual_palettes
import pandas as pd
import pickle
import scipy
import seaborn as sns
blue = sns.color_palette()[0]
green = sns.color_palette()[1]
red = sns.color_palette()[2]
def make... | 0.480966 | 0.465145 |
'''
Used for reading from Lake.Exercise table
'''
# First party classes
import os, sys
import logging
import logging.config
import datetime
# Third party classes
import psycopg2
# Custom classes
import dao.WrktCmnDAO as cmnDAO
def getExercises(dbConfig, strt_dt=datetime.datetime(1,1,1), end_dt=datetime.datetime(999... | dao/ReadLakeExercises.py | '''
Used for reading from Lake.Exercise table
'''
# First party classes
import os, sys
import logging
import logging.config
import datetime
# Third party classes
import psycopg2
# Custom classes
import dao.WrktCmnDAO as cmnDAO
def getExercises(dbConfig, strt_dt=datetime.datetime(1,1,1), end_dt=datetime.datetime(999... | 0.257205 | 0.267677 |
import os
import numpy as np
import time
import pickle
import tensorflow as tf
def load_data(data_name, path, labels = None, conv = False, seed = 0):
if data_name == 'mnist':
from import_data_mnist import load_data_mnist
data_train, data_test, labels_train, labels_test = \
load_data_mni... | dgm/models/utils.py | import os
import numpy as np
import time
import pickle
import tensorflow as tf
def load_data(data_name, path, labels = None, conv = False, seed = 0):
if data_name == 'mnist':
from import_data_mnist import load_data_mnist
data_train, data_test, labels_train, labels_test = \
load_data_mni... | 0.215516 | 0.398816 |
from jssp_ga import jssp_instance
class Schedule:
def __init__(self, schedule, jssp_instance):
self.schedule = schedule
self.decomposed_tasks = self.decompose_tasks(jssp_instance)
self.task_durations = {}
self.get_task_times()
def __getitem__(self, index):
return self.... | jssp_ga/scheduler.py | from jssp_ga import jssp_instance
class Schedule:
def __init__(self, schedule, jssp_instance):
self.schedule = schedule
self.decomposed_tasks = self.decompose_tasks(jssp_instance)
self.task_durations = {}
self.get_task_times()
def __getitem__(self, index):
return self.... | 0.501465 | 0.287152 |
import typing as t
from dataclasses import dataclass
from os import listdir
from json import loads
from itertools import chain, groupby
from datetime import datetime
Vertex = (float, float)
BoxVertices = (Vertex, Vertex, Vertex, Vertex)
PRECISION = 2
PRINT_SCALE = 0.05
EMPTY_VERTICES: BoxVertices = ((0, 0), (0, 0), (0... | visionary.py | import typing as t
from dataclasses import dataclass
from os import listdir
from json import loads
from itertools import chain, groupby
from datetime import datetime
Vertex = (float, float)
BoxVertices = (Vertex, Vertex, Vertex, Vertex)
PRECISION = 2
PRINT_SCALE = 0.05
EMPTY_VERTICES: BoxVertices = ((0, 0), (0, 0), (0... | 0.804828 | 0.517327 |
import os
import sys
import re
from jade2.basic.general import *
from jade2.basic.path import *
def rm_features_dbs(outdir, out_names):
for out_name in out_names:
db_name = outdir+'/'+out_name
if os.path.exists(db_name):
os.remove(db_name)
def create_features_db(pdb_list,
... | jade2/rosetta_jade/features.py | import os
import sys
import re
from jade2.basic.general import *
from jade2.basic.path import *
def rm_features_dbs(outdir, out_names):
for out_name in out_names:
db_name = outdir+'/'+out_name
if os.path.exists(db_name):
os.remove(db_name)
def create_features_db(pdb_list,
... | 0.13215 | 0.041852 |
from pygame import *
from random import randint
mixer.init()
font.init()
font1 = font.SysFont('Arial', 50)
font2 = font.SysFont('Arial', 70)
win_width = 1024
win_height = 800
x1 = 512
y1 = 650
score = 0
lost = 0
Next = False
window = display.set_mode((win_width,win_height))
display.set_captio... | main.py | from pygame import *
from random import randint
mixer.init()
font.init()
font1 = font.SysFont('Arial', 50)
font2 = font.SysFont('Arial', 70)
win_width = 1024
win_height = 800
x1 = 512
y1 = 650
score = 0
lost = 0
Next = False
window = display.set_mode((win_width,win_height))
display.set_captio... | 0.075402 | 0.133415 |
import numpy as np
import random
import perception
max_cycle_length = 200
cycle_steps = 100
slow_speed = 0.2
max_slow_frames = 100
max_turning_frames = 120
collected_sample_positions = []
def is_collected(x, y):
for i in range(len(collected_sample_positions)):
cx = collected_sample_positions[i][0]
... | Rover-Search_and_Sample_Return/code/decision.py | import numpy as np
import random
import perception
max_cycle_length = 200
cycle_steps = 100
slow_speed = 0.2
max_slow_frames = 100
max_turning_frames = 120
collected_sample_positions = []
def is_collected(x, y):
for i in range(len(collected_sample_positions)):
cx = collected_sample_positions[i][0]
... | 0.498047 | 0.433262 |
import argparse
import os
import sys
def basic_parser():
parser = argparse.ArgumentParser(description='cli for user management')
parser.add_argument('-c', '--config', default="api.json", help="config file, can be overridden by parameters")
parser.add_argument('-d', '--database', default=None)
subparser... | kbr/args_utils.py | import argparse
import os
import sys
def basic_parser():
parser = argparse.ArgumentParser(description='cli for user management')
parser.add_argument('-c', '--config', default="api.json", help="config file, can be overridden by parameters")
parser.add_argument('-d', '--database', default=None)
subparser... | 0.146392 | 0.056418 |
import sys
import glob, os
import re
import argparse
import subprocess
from contextlib import closing
def GetDavaVersion( pathToFramework ):
os.chdir(pathToFramework)
file = open("Sources/Internal/DAVAVersion.h");
p = re.compile('DAVAENGINE_VERSION "([\w\.]+)"');
davaVersion = p.findall(fi... | RepoTools/Scripts/create_pack_file.py | import sys
import glob, os
import re
import argparse
import subprocess
from contextlib import closing
def GetDavaVersion( pathToFramework ):
os.chdir(pathToFramework)
file = open("Sources/Internal/DAVAVersion.h");
p = re.compile('DAVAENGINE_VERSION "([\w\.]+)"');
davaVersion = p.findall(fi... | 0.096594 | 0.05647 |
import os
import shutil
test_256_path = 'result_set/256/test/'
result_path = 'test_sets/'
subset_0 = '000000/'
subset_1 = '000001/'
subset_2 = '000002/'
flist_name = 'filelist.txt'
assert os.path.exists(test_256_path + subset_0)
assert os.path.exists(test_256_path + subset_1)
assert os.path.exists(test_256_path + sub... | divide_by_classes.py | import os
import shutil
test_256_path = 'result_set/256/test/'
result_path = 'test_sets/'
subset_0 = '000000/'
subset_1 = '000001/'
subset_2 = '000002/'
flist_name = 'filelist.txt'
assert os.path.exists(test_256_path + subset_0)
assert os.path.exists(test_256_path + subset_1)
assert os.path.exists(test_256_path + sub... | 0.056405 | 0.439206 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'EntryBigqueryDateShardedSpec',
'EntryBigqueryTableSpec',
'EntryBigqueryTableSpecTableSpec',
'EntryBigqueryTableS... | sdk/python/pulumi_gcp/datacatalog/outputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'EntryBigqueryDateShardedSpec',
'EntryBigqueryTableSpec',
'EntryBigqueryTableSpecTableSpec',
'EntryBigqueryTableS... | 0.775945 | 0.071949 |
import importlib
from office365.runtime.odata.odata_metadata_level import ODataMetadataLevel
# Fixes some issues with TLS
import os
os.environ['REQUESTS_CA_BUNDLE'] = 'ca.pem';
class ClientObject(object):
"""Base client object"""
def __init__(self, context, resource_path=None, properties=None):
if p... | office365/runtime/client_object.py | import importlib
from office365.runtime.odata.odata_metadata_level import ODataMetadataLevel
# Fixes some issues with TLS
import os
os.environ['REQUESTS_CA_BUNDLE'] = 'ca.pem';
class ClientObject(object):
"""Base client object"""
def __init__(self, context, resource_path=None, properties=None):
if p... | 0.660391 | 0.081119 |
from __future__ import absolute_import
try:
import asyncio
except ImportError:
asyncio = None
import inspect
import sys
__all__ = [
'asyncio',
'IS_PY3',
'STRING_TYPES', 'casefold',
'metaclass',
'getargspec',
]
IS_PY3 = sys.version_info[0] == 3
STRING_TYPES = (str,) if IS_PY3 else (base... | calleee/_compat.py | from __future__ import absolute_import
try:
import asyncio
except ImportError:
asyncio = None
import inspect
import sys
__all__ = [
'asyncio',
'IS_PY3',
'STRING_TYPES', 'casefold',
'metaclass',
'getargspec',
]
IS_PY3 = sys.version_info[0] == 3
STRING_TYPES = (str,) if IS_PY3 else (base... | 0.532668 | 0.151372 |
from functools import partial
from typing import Tuple
import torch.nn as nn
from flash.core.registry import FlashRegistry
from flash.core.utilities.imports import _TORCHVISION_AVAILABLE
from flash.core.utilities.url_error import catch_url_error
from flash.image.classification.backbones.resnet import RESNET_MODELS
M... | flash/image/classification/backbones/torchvision.py | from functools import partial
from typing import Tuple
import torch.nn as nn
from flash.core.registry import FlashRegistry
from flash.core.utilities.imports import _TORCHVISION_AVAILABLE
from flash.core.utilities.url_error import catch_url_error
from flash.image.classification.backbones.resnet import RESNET_MODELS
M... | 0.875162 | 0.141637 |
import numpy as np
from math import floor
import Weight as wei
import Neuron as neu
import Network as net
from decimal import *
class Layer:
"""Class defining the layers found in a network:
- its type (dense layer, Convolutional layer ...) called type
- a list of Neurons called neuronList
-... | Layer.py | import numpy as np
from math import floor
import Weight as wei
import Neuron as neu
import Network as net
from decimal import *
class Layer:
"""Class defining the layers found in a network:
- its type (dense layer, Convolutional layer ...) called type
- a list of Neurons called neuronList
-... | 0.768907 | 0.577197 |
from .. import fileio
from ...weights import W
__author__ = "<NAME> <<EMAIL>>"
__all__ = ["StataTextIO"]
class StataTextIO(fileio.FileIO):
"""
Opens, reads, and writes weights file objects in STATA text format.
Spatial weights objects in the STATA text format are used in
STATA sppack library through... | pysal/lib/io/iohandlers/stata_txt.py | from .. import fileio
from ...weights import W
__author__ = "<NAME> <<EMAIL>>"
__all__ = ["StataTextIO"]
class StataTextIO(fileio.FileIO):
"""
Opens, reads, and writes weights file objects in STATA text format.
Spatial weights objects in the STATA text format are used in
STATA sppack library through... | 0.809427 | 0.534855 |
from bdgenomics.adam.rdd import AlignmentRecordRDD, \
CoverageRDD, \
FeatureRDD, \
FragmentRDD, \
GenotypeRDD, \
NucleotideContigFragmentRDD, \
VariantRDD
from bdgenomics.adam.stringency import STRICT, _toJava
class ADAMContext(object):
"""
The ADAMContext provides functions on top of... | adam-python/bdgenomics/adam/adamContext.py |
from bdgenomics.adam.rdd import AlignmentRecordRDD, \
CoverageRDD, \
FeatureRDD, \
FragmentRDD, \
GenotypeRDD, \
NucleotideContigFragmentRDD, \
VariantRDD
from bdgenomics.adam.stringency import STRICT, _toJava
class ADAMContext(object):
"""
The ADAMContext provides functions on top of... | 0.756358 | 0.495239 |
import autoslug.fields
from django.conf import settings
import django.contrib.postgres.fields
import django.contrib.postgres.fields.hstore
from django.db import migrations, models
import django.db.models.constraints
import django.db.models.deletion
import django.db.models.expressions
class Migration(migrations.Migra... | backend/structure/migrations/0001_initial.py |
import autoslug.fields
from django.conf import settings
import django.contrib.postgres.fields
import django.contrib.postgres.fields.hstore
from django.db import migrations, models
import django.db.models.constraints
import django.db.models.deletion
import django.db.models.expressions
class Migration(migrations.Migra... | 0.572603 | 0.176601 |
from __future__ import print_function
import os
os.environ['ENABLE_CNNL_TRYCATCH'] = 'OFF' # pylint: disable=all
import sys
import logging
import unittest
import torch
import torch_mlu.core.mlu_model as ct # pylint: disable=W0611
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cur_dir+"/../.... | test/cnnl/op_test/test_expand.py | from __future__ import print_function
import os
os.environ['ENABLE_CNNL_TRYCATCH'] = 'OFF' # pylint: disable=all
import sys
import logging
import unittest
import torch
import torch_mlu.core.mlu_model as ct # pylint: disable=W0611
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cur_dir+"/../.... | 0.403214 | 0.413004 |
import tensorflow as tf
from tensorflow.keras import Input
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import Reshape, Dense, Dropout, Flatten, LeakyReLU, Conv2D, MaxPooling2D
class CNNClassifier:
"""CNN classifier to classify images produced by different GAN models
The classif... | classifier/cnn_classifier.py |
import tensorflow as tf
from tensorflow.keras import Input
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import Reshape, Dense, Dropout, Flatten, LeakyReLU, Conv2D, MaxPooling2D
class CNNClassifier:
"""CNN classifier to classify images produced by different GAN models
The classif... | 0.973355 | 0.700075 |
import argparse
import collections
import copy
import functools
import json
import logging
import sys
import time
import docker
import json
DEFAULT_CONFIG_FILE = '/etc/arvados/docker-cleaner/docker-cleaner.json'
SUFFIX_SIZES = {suffix: 1024 ** exp for exp, suffix in enumerate('kmgt', 1)}
logger = logging.getLogger(... | services/dockercleaner/arvados_docker/cleaner.py | import argparse
import collections
import copy
import functools
import json
import logging
import sys
import time
import docker
import json
DEFAULT_CONFIG_FILE = '/etc/arvados/docker-cleaner/docker-cleaner.json'
SUFFIX_SIZES = {suffix: 1024 ** exp for exp, suffix in enumerate('kmgt', 1)}
logger = logging.getLogger(... | 0.449151 | 0.149128 |
# %% Imports
import numpy as np
from tqdm import tqdm
from pyTG import torusGraphs
from scipy.io import loadmat, savemat
# %% Each area has 'beta' and 'theta' keyed phases
# shape: i.e. phases['V1']['theta']['shape'] is (4, 2, 129) - (locations, time points, trials)
phases = {}
for area in ['V1', 'LM']:
phases[a... | neuropixels/fit_torus_graph.py |
# %% Imports
import numpy as np
from tqdm import tqdm
from pyTG import torusGraphs
from scipy.io import loadmat, savemat
# %% Each area has 'beta' and 'theta' keyed phases
# shape: i.e. phases['V1']['theta']['shape'] is (4, 2, 129) - (locations, time points, trials)
phases = {}
for area in ['V1', 'LM']:
phases[a... | 0.320821 | 0.398992 |
from pathlib import Path
import os, glob, random
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image, ImageFilter
from torchvision import transforms, datasets
from torch.utils.data import Dataset
n_bits = 8
def preprocess(x):
# Follows:
# https://github.com/tensorflow/tens... | datasets.py | from pathlib import Path
import os, glob, random
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image, ImageFilter
from torchvision import transforms, datasets
from torch.utils.data import Dataset
n_bits = 8
def preprocess(x):
# Follows:
# https://github.com/tensorflow/tens... | 0.79909 | 0.436682 |
__all__ = ('test_component',)
def test_component():
import pytest
from qsdsan import Chemical, Component, Components, set_thermo, \
_waste_stream as ws_module
from chemicals.elements import molecular_weight
from math import isclose
S_NH4 = Component('S_NH4', formula='NH4+', measured_as='N'... | tests/test_component_.py | __all__ = ('test_component',)
def test_component():
import pytest
from qsdsan import Chemical, Component, Components, set_thermo, \
_waste_stream as ws_module
from chemicals.elements import molecular_weight
from math import isclose
S_NH4 = Component('S_NH4', formula='NH4+', measured_as='N'... | 0.746416 | 0.543833 |
import os
import re
from oelint_parser.cls_item import Variable
from oelint_adv.cls_rule import Rule
class VarDependsOrdered(Rule):
def __init__(self):
super().__init__(id="oelint.vars.dependsordered",
severity="warning",
message="'{VAR}' entries should b... | oelint_adv/rule_base/rule_var_depends_ordered.py | import os
import re
from oelint_parser.cls_item import Variable
from oelint_adv.cls_rule import Rule
class VarDependsOrdered(Rule):
def __init__(self):
super().__init__(id="oelint.vars.dependsordered",
severity="warning",
message="'{VAR}' entries should b... | 0.310381 | 0.123868 |
import numpy as np
import scipy
from scipy.linalg import block_diag
import math
import quaternion
class rJoint:
def __init__(self, alpha, a, theta, offset, d, type, inertia, m, r):
self.alpha = alpha
self.a = a
self.offset = offset
self.theta = theta
self.d = d
self... | python-code/robot.py | import numpy as np
import scipy
from scipy.linalg import block_diag
import math
import quaternion
class rJoint:
def __init__(self, alpha, a, theta, offset, d, type, inertia, m, r):
self.alpha = alpha
self.a = a
self.offset = offset
self.theta = theta
self.d = d
self... | 0.717012 | 0.429011 |
import data.model as model
import urllib.request
import os.path
import pickle
ingest_directory = os.path.join(os.path.dirname(__file__), 'ingest')
ingest_manifest = 'ingest_urls.csv'
class IngestDataFile:
def __init__(self, filename, url):
self.filename = filename
self.url = url
self.dat... | data/ingest.py | import data.model as model
import urllib.request
import os.path
import pickle
ingest_directory = os.path.join(os.path.dirname(__file__), 'ingest')
ingest_manifest = 'ingest_urls.csv'
class IngestDataFile:
def __init__(self, filename, url):
self.filename = filename
self.url = url
self.dat... | 0.214938 | 0.143758 |
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from locators.locators import LoginPageLocators
from ... | amazsel/pages/login_page.py | import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from locators.locators import LoginPageLocators
from ... | 0.111398 | 0.096578 |
import requests
import pandas as pd
import xml.etree.ElementTree as ET
import sqlite3 as sql
from bs4 import BeautifulSoup
import re
def games(year,month,day):
'''This is a function that will return the all the pitches for all the games played on a single day.'''
url = f'http://gd2.mlb.com/components/ga... | dataCollection.py | import requests
import pandas as pd
import xml.etree.ElementTree as ET
import sqlite3 as sql
from bs4 import BeautifulSoup
import re
def games(year,month,day):
'''This is a function that will return the all the pitches for all the games played on a single day.'''
url = f'http://gd2.mlb.com/components/ga... | 0.265024 | 0.137475 |
import torch
import torch.nn as nn
from ...ops.pointnet2.pointnet2_batch import pointnet2_modules
from ...ops.roipoint_pool3d import roipoint_pool3d_utils
from ...utils import common_utils
from ...ops.iou3d_nms import iou3d_nms_utils
from .roi_head_template import RoIHeadTemplate
class PointRCNNIoUHead(RoIHeadTemplat... | pcdet/models/roi_heads/pointrcnniou_head.py | import torch
import torch.nn as nn
from ...ops.pointnet2.pointnet2_batch import pointnet2_modules
from ...ops.roipoint_pool3d import roipoint_pool3d_utils
from ...utils import common_utils
from ...ops.iou3d_nms import iou3d_nms_utils
from .roi_head_template import RoIHeadTemplate
class PointRCNNIoUHead(RoIHeadTemplat... | 0.829665 | 0.190442 |
"""Linux based DSLite server using ISC AFTR."""
import atexit
import logging
import re
from ast import literal_eval
from typing import List
import pexpect
from boardfarm.devices.profiles import base_profile
from boardfarm.exceptions import CodeError
from boardfarm.lib.installers import apt_install
logger = logging.g... | boardfarm/devices/profiles/mitm.py | """Linux based DSLite server using ISC AFTR."""
import atexit
import logging
import re
from ast import literal_eval
from typing import List
import pexpect
from boardfarm.devices.profiles import base_profile
from boardfarm.exceptions import CodeError
from boardfarm.lib.installers import apt_install
logger = logging.g... | 0.784113 | 0.145297 |
# Credits for this code goes to https://github.com/dcos/dcos-cli. Please
# note, it might have been slightly edited.
import requests
from requests.auth import AuthBase
from six.moves.urllib.parse import urlparse
from mesos import util
from mesos.errors import (MesosAuthenticationException,
... | src/python/mesos/http.py |
# Credits for this code goes to https://github.com/dcos/dcos-cli. Please
# note, it might have been slightly edited.
import requests
from requests.auth import AuthBase
from six.moves.urllib.parse import urlparse
from mesos import util
from mesos.errors import (MesosAuthenticationException,
... | 0.709321 | 0.17515 |
import numpy as np
import cv2
import tensorflow as tf
def image_preprocess(image, bboxes, train_input_size):
"""Rescales images to the correct size whilst also adjusting the bounding boxes accordingly.
Args:
image (np.ndarray): The image to be resized.
bboxes (np.ndarray): The bounding boxes ... | utils.py | import numpy as np
import cv2
import tensorflow as tf
def image_preprocess(image, bboxes, train_input_size):
"""Rescales images to the correct size whilst also adjusting the bounding boxes accordingly.
Args:
image (np.ndarray): The image to be resized.
bboxes (np.ndarray): The bounding boxes ... | 0.93488 | 0.457076 |
from __future__ import print_function, division
import os
import shutil
import tempfile
import numpy as np
from numpy.testing import assert_array_almost_equal_nulp
import pytest
import six
from .. import Model
from ..sed import SED
from ...util.functions import random_id
from .test_helpers import get_test_dust
cl... | hyperion/model/tests/test_sed.py | from __future__ import print_function, division
import os
import shutil
import tempfile
import numpy as np
from numpy.testing import assert_array_almost_equal_nulp
import pytest
import six
from .. import Model
from ..sed import SED
from ...util.functions import random_id
from .test_helpers import get_test_dust
cl... | 0.55447 | 0.449513 |
import colorsys
import copy
import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerTuple
from matplotlib.lines import Line2D
from scipy.cluster.hierarchy import dendrogram
from sklearn.cluster import Agg... | atomic/util/plot.py | import colorsys
import copy
import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerTuple
from matplotlib.lines import Line2D
from scipy.cluster.hierarchy import dendrogram
from sklearn.cluster import Agg... | 0.863492 | 0.636189 |
import itertools
import logging
import math
import random
from collections import namedtuple
from itertools import chain
from django.core.management.base import BaseCommand
from mailsnake import MailSnake
from opaque_keys.edx.keys import CourseKey
from common.djangoapps.student.models import UserProfile, unique_id_fo... | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/mailing/management/commands/mailchimp_sync_course.py | import itertools
import logging
import math
import random
from collections import namedtuple
from itertools import chain
from django.core.management.base import BaseCommand
from mailsnake import MailSnake
from opaque_keys.edx.keys import CourseKey
from common.djangoapps.student.models import UserProfile, unique_id_fo... | 0.503418 | 0.147034 |
from graphObj import Graph
from graphObj import Node
from queue import Queue
from collections import defaultdict
import time
timestart = time.time()
def BFS(mygraph,source,group = None):
mygraph.nodes[source].explored = True
mygraph.nodes[source].layer = 0
mygraph.nodes[source].group = group
Q = Queue(... | BFS.py | from graphObj import Graph
from graphObj import Node
from queue import Queue
from collections import defaultdict
import time
timestart = time.time()
def BFS(mygraph,source,group = None):
mygraph.nodes[source].explored = True
mygraph.nodes[source].layer = 0
mygraph.nodes[source].group = group
Q = Queue(... | 0.21984 | 0.223695 |
from test.test_support import verbose, TestSkipped
import locale
import sys
if sys.platform == 'darwin':
raise TestSkipped("Locale support on MacOSX is minimal and cannot be tested")
oldlocale = locale.setlocale(locale.LC_NUMERIC)
if sys.platform.startswith("win"):
tlocs = ("en",)
else:
tlocs = ("en_US.UT... | dev/tools/leveleditor/python/Lib/test/test_locale.py | from test.test_support import verbose, TestSkipped
import locale
import sys
if sys.platform == 'darwin':
raise TestSkipped("Locale support on MacOSX is minimal and cannot be tested")
oldlocale = locale.setlocale(locale.LC_NUMERIC)
if sys.platform.startswith("win"):
tlocs = ("en",)
else:
tlocs = ("en_US.UT... | 0.182025 | 0.172625 |
from statistics import fmean, median
from typing import List, Tuple
from auto_editor.timeline import Timeline
from auto_editor.utils.func import to_timecode
from auto_editor.utils.log import Log
def display(secs: float) -> str:
return to_timecode(round(secs), "rass")
def time_frame(title: str, frames: float, f... | auto_editor/preview.py | from statistics import fmean, median
from typing import List, Tuple
from auto_editor.timeline import Timeline
from auto_editor.utils.func import to_timecode
from auto_editor.utils.log import Log
def display(secs: float) -> str:
return to_timecode(round(secs), "rass")
def time_frame(title: str, frames: float, f... | 0.620852 | 0.440469 |
import functools
import logging
import os
import sys
@functools.lru_cache() # so that calling setup_logger multiple times won't add many handlers
def setup_logger(output_dir, distributed_rank=0, name="monoflex", file_name="log.txt"):
'''
Args:
output_dir (str): a directory saves output log files
... | utils/logger.py | import functools
import logging
import os
import sys
@functools.lru_cache() # so that calling setup_logger multiple times won't add many handlers
def setup_logger(output_dir, distributed_rank=0, name="monoflex", file_name="log.txt"):
'''
Args:
output_dir (str): a directory saves output log files
... | 0.463444 | 0.122025 |
SUCCEED = 200
PARTIAL_SUCCEED = 206
SERVER_ERROR = 500
PARAM_ERROR = 1000
HTTP_CONNECT_ERROR = 1001
UNKNOWN_ERROR = 1002
DATABASE_CONNECT_ERROR = 1101
DATABASE_INSERT_ERROR = 1102
DATABASE_DELETE_ERROR = 1103
DATABASE_QUERY_ERROR = 1104
DATA_EXIST = 1105
DATA_DEPENDENCY_ERROR = 1106
DATABASE_UPDATE_ERROR = 1107
LOGIN_E... | aops-utils/aops_utils/restful/status.py | SUCCEED = 200
PARTIAL_SUCCEED = 206
SERVER_ERROR = 500
PARAM_ERROR = 1000
HTTP_CONNECT_ERROR = 1001
UNKNOWN_ERROR = 1002
DATABASE_CONNECT_ERROR = 1101
DATABASE_INSERT_ERROR = 1102
DATABASE_DELETE_ERROR = 1103
DATABASE_QUERY_ERROR = 1104
DATA_EXIST = 1105
DATA_DEPENDENCY_ERROR = 1106
DATABASE_UPDATE_ERROR = 1107
LOGIN_E... | 0.572962 | 0.137822 |
import torch
from torch import nn, optim, multiprocessing
from torch.utils.data import DataLoader
import numpy as np
from tensorboardX import SummaryWriter
from time import time
from utils.train_utils import CheckpointManager, make_grid_triplet, make_k_grid
from utils.run_utils import get_logger
class ModelTrainer... | train/model_trainers/model_trainer_K2I.py | import torch
from torch import nn, optim, multiprocessing
from torch.utils.data import DataLoader
import numpy as np
from tensorboardX import SummaryWriter
from time import time
from utils.train_utils import CheckpointManager, make_grid_triplet, make_k_grid
from utils.run_utils import get_logger
class ModelTrainer... | 0.925991 | 0.428174 |
from unittest import TestCase
from utils_for_test import get_test_quota, get_test_metadata
from job_params_util import make_job_params
class TestRegularJobParams(TestCase):
def setUp(self):
self.quota = get_test_quota()
self.metadata = get_test_metadata()
self.params = {
"jobt... | src/utils/test_job_params_util.py |
from unittest import TestCase
from utils_for_test import get_test_quota, get_test_metadata
from job_params_util import make_job_params
class TestRegularJobParams(TestCase):
def setUp(self):
self.quota = get_test_quota()
self.metadata = get_test_metadata()
self.params = {
"jobt... | 0.644673 | 0.566918 |
import string
# -----------------------------------------------------
# Exporting Methods
# -----------------------------------------------------
def numeric(minimum, maximum):
return NumericMetadata(minimum, maximum)
def category(categories):
return CategoricalMetadata(categories)
def sequence(length, voc... | armchem/metadata.py |
import string
# -----------------------------------------------------
# Exporting Methods
# -----------------------------------------------------
def numeric(minimum, maximum):
return NumericMetadata(minimum, maximum)
def category(categories):
return CategoricalMetadata(categories)
def sequence(length, voc... | 0.61682 | 0.241836 |
import random, re
import numpy as np
import torch
import torch.utils.data
import nlpaug.augmenter.word as naw
import nlpaug.augmenter.char as nac
import nlpaug.flow as naf
from .custom_aug import CapitalizeAug, AbbrAug, RepeatCharAug
from tqdm import tqdm
def _tokenizer(text, token_pattern=r"(?u)\b\w\w+\b"):
tok... | utils/T5_dataset.py |
import random, re
import numpy as np
import torch
import torch.utils.data
import nlpaug.augmenter.word as naw
import nlpaug.augmenter.char as nac
import nlpaug.flow as naf
from .custom_aug import CapitalizeAug, AbbrAug, RepeatCharAug
from tqdm import tqdm
def _tokenizer(text, token_pattern=r"(?u)\b\w\w+\b"):
tok... | 0.367497 | 0.203569 |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectMultipleField, widgets, SelectField, TextAreaField
import pycountry
from wtforms.validators import DataRequired, Email, Length
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(... | app/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectMultipleField, widgets, SelectField, TextAreaField
import pycountry
from wtforms.validators import DataRequired, Email, Length
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(... | 0.541894 | 0.13201 |
# Copyright 2011, 2012, 2013, 2014, 2015 <NAME>
# This file is part of armspeech.
# See `License` for details of license and warranty.
from codedep import codeDeps
from bisque.distribute import liftLocal, lit, lift
import armspeech.modelling.dist as d
@codeDeps()
def accumulate(distPrev, corpus, uttIds, createAcc)... | armspeech/modelling/jobs_train.py |
# Copyright 2011, 2012, 2013, 2014, 2015 <NAME>
# This file is part of armspeech.
# See `License` for details of license and warranty.
from codedep import codeDeps
from bisque.distribute import liftLocal, lit, lift
import armspeech.modelling.dist as d
@codeDeps()
def accumulate(distPrev, corpus, uttIds, createAcc)... | 0.797675 | 0.178508 |
import os
from functools import wraps
from flask import render_template, jsonify, send_from_directory,\
request, redirect, abort, url_for, flash
from flask_login import current_user, login_user, logout_user, login_required
from app import app, db
from app.events import send_new_submission_event
from app.services ... | app/routes.py | import os
from functools import wraps
from flask import render_template, jsonify, send_from_directory,\
request, redirect, abort, url_for, flash
from flask_login import current_user, login_user, logout_user, login_required
from app import app, db
from app.events import send_new_submission_event
from app.services ... | 0.42179 | 0.046184 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""An example of customizing PPO to leverage a centralized critic with an imitation loss"""
import argparse
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils import try_import_tf
from ... | flow/agents/centralized_imitation_PPO.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""An example of customizing PPO to leverage a centralized critic with an imitation loss"""
import argparse
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils import try_import_tf
from ... | 0.914309 | 0.203668 |
import json
import logging
from urllib2 import urlopen
from tornado.gen import coroutine
from mpikat.core.scpi import ScpiAsyncDeviceServer, scpi_request, raise_or_ok
log = logging.getLogger('mpikat.edd_scpi_interface')
class EddScpiInterfaceError(Exception):
pass
class EddScpiInterface(ScpiAsyncDeviceServer):
... | mpikat/effelsberg/edd/edd_scpi_interface.py | import json
import logging
from urllib2 import urlopen
from tornado.gen import coroutine
from mpikat.core.scpi import ScpiAsyncDeviceServer, scpi_request, raise_or_ok
log = logging.getLogger('mpikat.edd_scpi_interface')
class EddScpiInterfaceError(Exception):
pass
class EddScpiInterface(ScpiAsyncDeviceServer):
... | 0.586404 | 0.074871 |
from asyncio import create_subprocess_shell as asyncrunapp
from asyncio import sleep
from asyncio.subprocess import PIPE as asyncPIPE
from os import remove
from platform import python_version
from telethon import events, version
from telethon.tl.types import MessageEntityMentionName
from uniborg.util import admin_cmd... | stdplugins/misc.py | from asyncio import create_subprocess_shell as asyncrunapp
from asyncio import sleep
from asyncio.subprocess import PIPE as asyncPIPE
from os import remove
from platform import python_version
from telethon import events, version
from telethon.tl.types import MessageEntityMentionName
from uniborg.util import admin_cmd... | 0.512205 | 0.210158 |
import numpy as np
import matplotlib.pyplot as plt
import svgwrite
class Dot:
'''Class containing data for a single dot in the puzzle.
Initiate with coordinates i,j'''
def __init__(self,i,j):
self.color = None
self.active = True
self.empty = True
self.coords = (i,j)
... | __init__.py | import numpy as np
import matplotlib.pyplot as plt
import svgwrite
class Dot:
'''Class containing data for a single dot in the puzzle.
Initiate with coordinates i,j'''
def __init__(self,i,j):
self.color = None
self.active = True
self.empty = True
self.coords = (i,j)
... | 0.537041 | 0.430327 |
import datetime
import requests
from typing import List, Dict, Any, Optional, Union, Tuple
from platypush.plugins import Plugin, action
class FoursquarePlugin(Plugin):
"""
Plugin to interact with the `Foursquare Places API <https://developer.foursquare.com/docs/api>`_.
In order to enable the Foursquare ... | platypush/plugins/foursquare.py | import datetime
import requests
from typing import List, Dict, Any, Optional, Union, Tuple
from platypush.plugins import Plugin, action
class FoursquarePlugin(Plugin):
"""
Plugin to interact with the `Foursquare Places API <https://developer.foursquare.com/docs/api>`_.
In order to enable the Foursquare ... | 0.917469 | 0.418935 |
from collections import defaultdict
import dolfin as df
import numpy as np
from xii.meshing.embedded_mesh import EmbeddedMesh
class SubDomainMesh(EmbeddedMesh):
'''Embedded mesh for cell funcions.'''
def __init__(self, marking_function, markers):
assert marking_function.dim() == marking_function.mesh... | xii/meshing/subdomain_mesh.py | from collections import defaultdict
import dolfin as df
import numpy as np
from xii.meshing.embedded_mesh import EmbeddedMesh
class SubDomainMesh(EmbeddedMesh):
'''Embedded mesh for cell funcions.'''
def __init__(self, marking_function, markers):
assert marking_function.dim() == marking_function.mesh... | 0.754689 | 0.756155 |
from struct import pack, unpack
from threading import Event
from binascii import hexlify
from Queue import Queue
(TR_STATUS_OK,
TR_STATUS_PAGE_INVALID,
TR_STATUS_PAGE_IN_USE,
TR_STATUS_PAGE_CORRUPT,
TR_STATUS_INVALID_FILE_HANDLE) = range(5)
(MSG_TYPE_PAGE_GET,
MSG_TYPE_PAGE_PUT,
MSG_TYPE_FILE_ERASE,
MSG_TYPE_FILE_PROP... | pycentral/bulk_transfer.py | from struct import pack, unpack
from threading import Event
from binascii import hexlify
from Queue import Queue
(TR_STATUS_OK,
TR_STATUS_PAGE_INVALID,
TR_STATUS_PAGE_IN_USE,
TR_STATUS_PAGE_CORRUPT,
TR_STATUS_INVALID_FILE_HANDLE) = range(5)
(MSG_TYPE_PAGE_GET,
MSG_TYPE_PAGE_PUT,
MSG_TYPE_FILE_ERASE,
MSG_TYPE_FILE_PROP... | 0.3863 | 0.106041 |
from __future__ import print_function
import copy
import torch.utils.data
from IPython.core.debugger import Pdb;
from railrl.data_management.images import normalize_image
debug = Pdb().set_trace
# Adapted from pytorch examples
import torch
import torch.utils.data
from torch import nn, optim
from torch.autograd impor... | railrl/torch/vae/acai.py | from __future__ import print_function
import copy
import torch.utils.data
from IPython.core.debugger import Pdb;
from railrl.data_management.images import normalize_image
debug = Pdb().set_trace
# Adapted from pytorch examples
import torch
import torch.utils.data
from torch import nn, optim
from torch.autograd impor... | 0.864009 | 0.316396 |
import nvidia.dali.fn as _fn
import nvidia.dali.pipeline as _pipeline
import nvidia.dali.tensors as _Tensors
import nvidia.dali.types as _types
from nvidia.dali.data_node import DataNode as _DataNode, _arithm_op
import inspect
class DataNodeDebug(_DataNode):
"""Wrapper class around Tensor, implementing all of th... | dali/python/nvidia/dali/_debug_mode.py |
import nvidia.dali.fn as _fn
import nvidia.dali.pipeline as _pipeline
import nvidia.dali.tensors as _Tensors
import nvidia.dali.types as _types
from nvidia.dali.data_node import DataNode as _DataNode, _arithm_op
import inspect
class DataNodeDebug(_DataNode):
"""Wrapper class around Tensor, implementing all of th... | 0.700485 | 0.327883 |
import logging
from django import forms
from chatterbox.utils.youtube import activity_from_dict
from . import (Collector, maybe)
log = logging.getLogger(__name__)
class YouTubeSearchForm(forms.Form):
query = forms.CharField(label='Search Query', max_length=100)
class YouTubeCollector(Collector):
activity_... | chatterbox/collectors/youtube.py | import logging
from django import forms
from chatterbox.utils.youtube import activity_from_dict
from . import (Collector, maybe)
log = logging.getLogger(__name__)
class YouTubeSearchForm(forms.Form):
query = forms.CharField(label='Search Query', max_length=100)
class YouTubeCollector(Collector):
activity_... | 0.428951 | 0.105717 |
from enum import Enum
from datetime import datetime
LATEST_SCATT_DATA_VERSION = '0.5'
class ScattDataUtilsError(Exception):
def __init__(self, message):
self.message = message
class ScattDataForCefrScoring():
DEFAULT_CEFR_SCORE = 5
class CefrQualitativeFeatureNames(Enum):
@classmethod... | langx_tutti_client/scatt_modules/scatt_data_utils.py | from enum import Enum
from datetime import datetime
LATEST_SCATT_DATA_VERSION = '0.5'
class ScattDataUtilsError(Exception):
def __init__(self, message):
self.message = message
class ScattDataForCefrScoring():
DEFAULT_CEFR_SCORE = 5
class CefrQualitativeFeatureNames(Enum):
@classmethod... | 0.549641 | 0.156717 |
from .phase import Phase
import logging
class FieldPrunePhase(Phase):
"""
reduce fields to just those specified for the dataset
"""
def __init__(self, fields):
self.fields = list(
set(fields + ["entity", "organisation", "prefix", "reference"])
)
logging.debug(f"pru... | digital_land/phase/prune.py | from .phase import Phase
import logging
class FieldPrunePhase(Phase):
"""
reduce fields to just those specified for the dataset
"""
def __init__(self, fields):
self.fields = list(
set(fields + ["entity", "organisation", "prefix", "reference"])
)
logging.debug(f"pru... | 0.667798 | 0.210807 |
import numpy as np
import probtorch
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker
class Trainer(BaseTrainer):
"""
Trainer class
"""
def __init__(self, model, criterion, metric_ftns, optimizer, config, data_loader,
... | trainer/trainer.py | import numpy as np
import probtorch
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker
class Trainer(BaseTrainer):
"""
Trainer class
"""
def __init__(self, model, criterion, metric_ftns, optimizer, config, data_loader,
... | 0.852322 | 0.232975 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Serviço',
fields=[
('id', models.AutoField(auto_created=Tr... | clientes/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Serviço',
fields=[
('id', models.AutoField(auto_created=Tr... | 0.588416 | 0.205475 |
import time
import numpy as np
import tensorflow as tf
from data import num_labels
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
def train_model_in_batches(model, datasets, steps, dropout_keep_prob, load_model = False... | train.py | import time
import numpy as np
import tensorflow as tf
from data import num_labels
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
def train_model_in_batches(model, datasets, steps, dropout_keep_prob, load_model = False... | 0.531939 | 0.526891 |
import logging
import numpy
import pandas as pd
from covidactnow.datapublic.common_fields import CommonFields
from libs.datasets import data_source
from libs.datasets import dataset_utils
from libs.us_state_abbrev import US_STATE_ABBREV
from libs.datasets.common_fields import CommonIndexFields
_logger = logging.getLo... | libs/datasets/sources/cds_dataset.py | import logging
import numpy
import pandas as pd
from covidactnow.datapublic.common_fields import CommonFields
from libs.datasets import data_source
from libs.datasets import dataset_utils
from libs.us_state_abbrev import US_STATE_ABBREV
from libs.datasets.common_fields import CommonIndexFields
_logger = logging.getLo... | 0.405566 | 0.276605 |