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 |
|---|---|---|---|---|
from zlib import crc32
import struct
import json
import time
import numpy
import brownian_sheet
def match_pattern(pattern, roi):
return (
(roi[pattern == 0] == 0).all()
and (roi[pattern == 1] > 0).all()
and (roi[(pattern >= 2) & (pattern <= 4)] >= 0).all()
# 2, 3 or 4: land (i.e.... | generate.py | from zlib import crc32
import struct
import json
import time
import numpy
import brownian_sheet
def match_pattern(pattern, roi):
return (
(roi[pattern == 0] == 0).all()
and (roi[pattern == 1] > 0).all()
and (roi[(pattern >= 2) & (pattern <= 4)] >= 0).all()
# 2, 3 or 4: land (i.e.... | 0.370453 | 0.378919 |
import random
import time
import logging
from typing import Optional, Union
from solana.account import Account
from solana.publickey import PublicKey
from solana.rpc.api import Client
from src.utils.config import shared_config
logger = logging.getLogger(__name__)
SOLANA_ENDPOINTS = shared_config["solana"]["endpoint"]... | discovery-provider/src/solana/solana_client_manager.py | import random
import time
import logging
from typing import Optional, Union
from solana.account import Account
from solana.publickey import PublicKey
from solana.rpc.api import Client
from src.utils.config import shared_config
logger = logging.getLogger(__name__)
SOLANA_ENDPOINTS = shared_config["solana"]["endpoint"]... | 0.839306 | 0.106133 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import json
def main():
dataset = {
'events': ['a000', 'b000', 'b001', 'c000', 'c001', 'c002', 'c003',
'c004', 'd000', 'd001', 'd002', 'f000', 'f001', 'h000',
... | daqa-gen/daqa_outline.py |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import json
def main():
dataset = {
'events': ['a000', 'b000', 'b001', 'c000', 'c001', 'c002', 'c003',
'c004', 'd000', 'd001', 'd002', 'f000', 'f001', 'h000',
... | 0.565059 | 0.301169 |
from unittest import mock
import responses
from django.test import TestCase, Client
from django.urls import reverse
from model_mommy import mommy
from battles.models import Battle
from common.constants import POKEAPI_BASE_URL
from users.models import User
class BattleListViewTests(TestCase):
def setUp(self):
... | backend/battles/tests/test_views.py | from unittest import mock
import responses
from django.test import TestCase, Client
from django.urls import reverse
from model_mommy import mommy
from battles.models import Battle
from common.constants import POKEAPI_BASE_URL
from users.models import User
class BattleListViewTests(TestCase):
def setUp(self):
... | 0.464902 | 0.329419 |
import datetime
import math
from ref import umux_screener_assembly_path
from waferscreen.data_io.s21_metadata import num_format, MetaDataDict
def read_umux_screener(path):
# initialize the variables to return to screening program
package_state_date = None
box_position_header = None
all_boxes_dict = {... | waferscreen/data_io/screener_read.py |
import datetime
import math
from ref import umux_screener_assembly_path
from waferscreen.data_io.s21_metadata import num_format, MetaDataDict
def read_umux_screener(path):
# initialize the variables to return to screening program
package_state_date = None
box_position_header = None
all_boxes_dict = {... | 0.421909 | 0.222215 |
from time import sleep
from datetime import datetime
from psycopg2.extras import execute_values
from pandas import DataFrame, to_datetime, notnull
from toolz import groupby
from . import helpers
from .connection import Connection
class Postgre(object):
"""This class will contain special methods to perform over ... | pysoni/core.py | from time import sleep
from datetime import datetime
from psycopg2.extras import execute_values
from pandas import DataFrame, to_datetime, notnull
from toolz import groupby
from . import helpers
from .connection import Connection
class Postgre(object):
"""This class will contain special methods to perform over ... | 0.656878 | 0.309898 |
with open("input.txt") as file:
data = file.read()
import re
import itertools
spoon = []
pattern = r"(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)"
for teaspoon, capacity, durability, flavor, texture, calories in re.findall(pattern, data):
capacity = int(ca... | 2015/15/solve.py | with open("input.txt") as file:
data = file.read()
import re
import itertools
spoon = []
pattern = r"(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)"
for teaspoon, capacity, durability, flavor, texture, calories in re.findall(pattern, data):
capacity = int(ca... | 0.186947 | 0.335378 |
import json
import os
import pickle
import re
from collections import namedtuple
import numpy as np
import pandas as pd
from django.contrib.auth.models import User
from django.db import transaction
from django.db.models import F
from django.shortcuts import HttpResponse, render
from django.template.loader import rende... | fake_news_classifier/Dashboard/views.py | import json
import os
import pickle
import re
from collections import namedtuple
import numpy as np
import pandas as pd
from django.contrib.auth.models import User
from django.db import transaction
from django.db.models import F
from django.shortcuts import HttpResponse, render
from django.template.loader import rende... | 0.251556 | 0.058319 |
import time
import os
import re
import platform
def directory_location():
"""directory_location
Looks for a file in the home directory which contains a name for the
data directory. There should be one line in this file, which will point
to the location of the directory in which all othe... | trunk/MOPS_Misc.py | import time
import os
import re
import platform
def directory_location():
"""directory_location
Looks for a file in the home directory which contains a name for the
data directory. There should be one line in this file, which will point
to the location of the directory in which all othe... | 0.290377 | 0.114369 |
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR, CyclicLR
def step_lr(optimizer, step_size, gamma=0.1, last_epoch=-1):
"""Create LR step scheduler.
Args:
optimizer (torch.optim): Model optimizer.
step_size (int): Frequency for changing learning rate.
gamma (... | tensornet/engine/ops/lr_scheduler.py | from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR, CyclicLR
def step_lr(optimizer, step_size, gamma=0.1, last_epoch=-1):
"""Create LR step scheduler.
Args:
optimizer (torch.optim): Model optimizer.
step_size (int): Frequency for changing learning rate.
gamma (... | 0.978925 | 0.568536 |
import base64
import filecmp
import os
import sys
from _unittest.conftest import BasisTest
from _unittest.conftest import local_path
from pyaedt.generic.LoadAEDTFile import load_entire_aedt_file
def _write_jpg(design_info, scratch):
"""writes the jpg Image64 property of the design info
to a temporary file an... | _unittest/test_13_LoadAEDTFile.py | import base64
import filecmp
import os
import sys
from _unittest.conftest import BasisTest
from _unittest.conftest import local_path
from pyaedt.generic.LoadAEDTFile import load_entire_aedt_file
def _write_jpg(design_info, scratch):
"""writes the jpg Image64 property of the design info
to a temporary file an... | 0.38549 | 0.429071 |
import os
import sys
import random
import string
import logging
import json
import unittest
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
import os.path
from os import path
class TestBotoClient(unittest.TestCase):
s3 = None
s3_client = None
setup_done = False... | hadoop-ozone/dist/src/main/smoketest/s3/boto_client.py |
import os
import sys
import random
import string
import logging
import json
import unittest
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
import os.path
from os import path
class TestBotoClient(unittest.TestCase):
s3 = None
s3_client = None
setup_done = False... | 0.207094 | 0.207255 |
from copy import deepcopy
from statistics import median, stdev
from config import default_weight_func
class Block:
def __init__(self, word_list, middle_index, radius):
start = max(0, middle_index - radius)
end = min(len(word_list), middle_index + radius+1)
self.before_wing = word_list[s... | code/truncators/assoc_dic.py | from copy import deepcopy
from statistics import median, stdev
from config import default_weight_func
class Block:
def __init__(self, word_list, middle_index, radius):
start = max(0, middle_index - radius)
end = min(len(word_list), middle_index + radius+1)
self.before_wing = word_list[s... | 0.545891 | 0.325655 |
import numpy as np
import cv2
from scipy.interpolate import interpn
from scipy.ndimage import zoom
import matplotlib as mpl
mpl.use("Agg")
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
def plot_heatmap_img(batch_segm... | segmappy/segmappy/tools/heatmap.py | import numpy as np
import cv2
from scipy.interpolate import interpn
from scipy.ndimage import zoom
import matplotlib as mpl
mpl.use("Agg")
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
def plot_heatmap_img(batch_segm... | 0.694406 | 0.493958 |
import tcod as T
from settings import *
from map import *
from mob import *
from item import *
from util import in_map
import ui
KEYS = [
(['y', '7', T.KEY_KP7], ('walk', (-1, -1))),
(['k', '8', T.KEY_KP8, T.KEY_UP], ('walk', (0, -1))),
(['u', '9', T.KEY_KP9], ('walk', (1, -1))),
(['h', '4', T.KEY_KP4... | game.py | import tcod as T
from settings import *
from map import *
from mob import *
from item import *
from util import in_map
import ui
KEYS = [
(['y', '7', T.KEY_KP7], ('walk', (-1, -1))),
(['k', '8', T.KEY_KP8, T.KEY_UP], ('walk', (0, -1))),
(['u', '9', T.KEY_KP9], ('walk', (1, -1))),
(['h', '4', T.KEY_KP4... | 0.275325 | 0.109706 |
import numpy as np
import qaoa
from qaoa.circuit.validation import *
from qaoa.util.number_format import spaced_decim
from scipy.optimize import minimize
import matplotlib.pyplot as plt
if __name__ == '__main__':
np.set_printoptions(precision=4,linewidth=200)
nq = 12 # Number of Qubits
p = 3 # Number ... | test/circuit/qaoa_circuit.py | import numpy as np
import qaoa
from qaoa.circuit.validation import *
from qaoa.util.number_format import spaced_decim
from scipy.optimize import minimize
import matplotlib.pyplot as plt
if __name__ == '__main__':
np.set_printoptions(precision=4,linewidth=200)
nq = 12 # Number of Qubits
p = 3 # Number ... | 0.619817 | 0.393735 |
__author__ = '<NAME>'
__license__ = "GPL"
__version__ = "0.1.0"
__email__ = "<EMAIL>"
import pprint as pp
import pandas as pd
import numpy as np
import re
import json, time, sys, csv
from HTMLParser import HTMLParser
import sys, os, argparse
import traceback
import time, datetime
import ast
import glob
import matpl... | procjson_clean.py |
__author__ = '<NAME>'
__license__ = "GPL"
__version__ = "0.1.0"
__email__ = "<EMAIL>"
import pprint as pp
import pandas as pd
import numpy as np
import re
import json, time, sys, csv
from HTMLParser import HTMLParser
import sys, os, argparse
import traceback
import time, datetime
import ast
import glob
import matpl... | 0.146301 | 0.06489 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('onlinecourse', '0002_auto_20211026_0302'),
]
operations = [
migrations.AlterField(
model_name='choice',
name='id',
field=models.BigAutoField(auto_create... | onlinecourse/migrations/0003_auto_20211105_0012.py |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('onlinecourse', '0002_auto_20211026_0302'),
]
operations = [
migrations.AlterField(
model_name='choice',
name='id',
field=models.BigAutoField(auto_create... | 0.649356 | 0.16502 |
import azure.functions as func
from onefuzztypes.enums import ErrorCode, VmState
from onefuzztypes.models import Error, ReproConfig
from onefuzztypes.requests import ReproGet
from ..onefuzzlib.repro import Repro
from ..onefuzzlib.request import not_ok, ok, parse_request
def get(req: func.HttpRequest) -> func.HttpRe... | src/api-service/__app__/repro_vms/__init__.py |
import azure.functions as func
from onefuzztypes.enums import ErrorCode, VmState
from onefuzztypes.models import Error, ReproConfig
from onefuzztypes.requests import ReproGet
from ..onefuzzlib.repro import Repro
from ..onefuzzlib.request import not_ok, ok, parse_request
def get(req: func.HttpRequest) -> func.HttpRe... | 0.379953 | 0.096323 |
#Imports
import bs4
from urllib.request import Request,urlopen
from bs4 import BeautifulSoup as soup
class Anime(): # Storing the anime data
def __init__(self,title,link): # Intialises the anime class
self.title = title # Title
self.link = link # Link
def searchResults(term): # Searc... | GogoAPI.py |
#Imports
import bs4
from urllib.request import Request,urlopen
from bs4 import BeautifulSoup as soup
class Anime(): # Storing the anime data
def __init__(self,title,link): # Intialises the anime class
self.title = title # Title
self.link = link # Link
def searchResults(term): # Searc... | 0.376967 | 0.117395 |
import jax.numpy as np
import numpy as onp
import qtensornetwork.components as qtnc
import copy
import math
class BaseAnsatz:
def __init__(self, q_support, is_updated, name=None):
self._q_support = q_support
self._is_updated = is_updated
self._name = name
self._gates = []
se... | qtensornetwork/ansatz.py | import jax.numpy as np
import numpy as onp
import qtensornetwork.components as qtnc
import copy
import math
class BaseAnsatz:
def __init__(self, q_support, is_updated, name=None):
self._q_support = q_support
self._is_updated = is_updated
self._name = name
self._gates = []
se... | 0.70202 | 0.176725 |
from .core import Core, etree
class Headers(Core):
__enumerations = {}
__endpoint_list = []
__parent = None
def __init__(self, generate_strings=False) -> None:
super().__init__()
self.generate_strings = generate_strings
def generate(self, service):
child = None
i... | ews_builder/headers.py | from .core import Core, etree
class Headers(Core):
__enumerations = {}
__endpoint_list = []
__parent = None
def __init__(self, generate_strings=False) -> None:
super().__init__()
self.generate_strings = generate_strings
def generate(self, service):
child = None
i... | 0.378344 | 0.062474 |
from colorama import Fore,Back,Style
import os, sys
def show_options(require):
#print Back.WHITE + Fore.WHITE + "Module parameters" + Style.RESET_ALL
for line in require:
if require[line][0]["value"] == "":
value = "No value"
else:
value = require[line][0]["value"]
if require[line][0]["req... | operative-framework-master/core/load.py |
from colorama import Fore,Back,Style
import os, sys
def show_options(require):
#print Back.WHITE + Fore.WHITE + "Module parameters" + Style.RESET_ALL
for line in require:
if require[line][0]["value"] == "":
value = "No value"
else:
value = require[line][0]["value"]
if require[line][0]["req... | 0.099121 | 0.082475 |
from inspect import currentframe, getfile
import os
import sys
from typing import Dict, Union
from pytest import raises
# Used to import from parent directory
current_dir: str = os.path.dirname(os.path.abspath(getfile(currentframe())))
parent_dir: str = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
from... | advanced/tests/test_obs_utils.py | from inspect import currentframe, getfile
import os
import sys
from typing import Dict, Union
from pytest import raises
# Used to import from parent directory
current_dir: str = os.path.dirname(os.path.abspath(getfile(currentframe())))
parent_dir: str = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
from... | 0.636918 | 0.434341 |
from object_library import all_couplings, Coupling
from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot
R2GC_365_1 = Coupling(name = 'R2GC_365_1',
value = '-(complex(0,1)*G**2)/(16.*cmath.pi**2)',
order = {'QCD':2})
R2GC_366_2 = Coupling(nam... | ZEE_NLO/CT_couplings.py |
from object_library import all_couplings, Coupling
from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot
R2GC_365_1 = Coupling(name = 'R2GC_365_1',
value = '-(complex(0,1)*G**2)/(16.*cmath.pi**2)',
order = {'QCD':2})
R2GC_366_2 = Coupling(nam... | 0.291082 | 0.21819 |
import os
from collections import defaultdict
import sys
import glob
import time
import math
import multiprocessing
import signal
import re
from intron_recovery_performance import indels_introns_and_exons
def init_worker():
""" Prevents KeyboardInterrupt from reaching a pool's workers.
Exiting gracefully ... | eval/unique_introns.py | import os
from collections import defaultdict
import sys
import glob
import time
import math
import multiprocessing
import signal
import re
from intron_recovery_performance import indels_introns_and_exons
def init_worker():
""" Prevents KeyboardInterrupt from reaching a pool's workers.
Exiting gracefully ... | 0.516108 | 0.361982 |
from .base_setup import Base
from rest_framework import status
from django.urls import reverse
class ArticleTests(Base):
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
def test_create_article(self):
"""
Tests that a user can create a new article
... | authors/apps/articles/tests/test_create_article.py | from .base_setup import Base
from rest_framework import status
from django.urls import reverse
class ArticleTests(Base):
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
def test_create_article(self):
"""
Tests that a user can create a new article
... | 0.504639 | 0.199581 |
# Python modules
from typing import Optional, Dict, Callable
from threading import Lock
import inspect
# Third-party modules
from pydantic import BaseModel
# NOC modules
from noc.core.expr import get_fn
from .base import BaseCDAGNode, ValueType, Category
MAX31 = 0x7FFFFFFF
MAX32 = 0xFFFFFFFF
MAX64 = 0xFFFFFFFFFFFFF... | core/cdag/node/probe.py |
# Python modules
from typing import Optional, Dict, Callable
from threading import Lock
import inspect
# Third-party modules
from pydantic import BaseModel
# NOC modules
from noc.core.expr import get_fn
from .base import BaseCDAGNode, ValueType, Category
MAX31 = 0x7FFFFFFF
MAX32 = 0xFFFFFFFF
MAX64 = 0xFFFFFFFFFFFFF... | 0.87168 | 0.274736 |
import pyglet
class Manager:
def __init__(self, win: pyglet.window.Window, frame: pyglet.gui.Frame):
self.scenes = {}
self.win = win
self.active_scene = None
self.frame = frame
@win.event
def on_draw():
self.on_draw_func(self.win)
@win.event
... | sceneManager.py | import pyglet
class Manager:
def __init__(self, win: pyglet.window.Window, frame: pyglet.gui.Frame):
self.scenes = {}
self.win = win
self.active_scene = None
self.frame = frame
@win.event
def on_draw():
self.on_draw_func(self.win)
@win.event
... | 0.293 | 0.290779 |
import json
import os
import pytest
import unittest
from mock import patch
from ml.common.svc_checker import ServiceChecker
from ml.utils.logger import get_logger
LOGGER = get_logger('ml.' + __name__)
class ServiceCheckerTester(unittest.TestCase):
@classmethod
def teardown_class(cls):
pass
de... | tests/test_common_svc_checker.py | import json
import os
import pytest
import unittest
from mock import patch
from ml.common.svc_checker import ServiceChecker
from ml.utils.logger import get_logger
LOGGER = get_logger('ml.' + __name__)
class ServiceCheckerTester(unittest.TestCase):
@classmethod
def teardown_class(cls):
pass
de... | 0.387574 | 0.276245 |
import os
import sys
import json
from collections import namedtuple
import requests
import datetime
import yaml
import csv
from app import create_app
from flask import current_app
from flask.cli import FlaskGroup
from flask_gnupg import fetch_gpg_key
from app import db
from app.models import User, Organization, IpRang... | app/fixtures/testfixture.py | import os
import sys
import json
from collections import namedtuple
import requests
import datetime
import yaml
import csv
from app import create_app
from flask import current_app
from flask.cli import FlaskGroup
from flask_gnupg import fetch_gpg_key
from app import db
from app.models import User, Organization, IpRang... | 0.037547 | 0.057361 |
from flask import Blueprint, request, jsonify, g, abort
from tripplanner import db, basic_auth, token_auth
from tripplanner.auth.decorators import allow_superuser
from tripplanner.errors.validation import ValidationError
from tripplanner.users.models import User
user_app = Blueprint('user', __name__)
@user_app.rout... | tripplanner/users/views.py | from flask import Blueprint, request, jsonify, g, abort
from tripplanner import db, basic_auth, token_auth
from tripplanner.auth.decorators import allow_superuser
from tripplanner.errors.validation import ValidationError
from tripplanner.users.models import User
user_app = Blueprint('user', __name__)
@user_app.rout... | 0.38145 | 0.063337 |
from pyflink.testing.test_case_utils import PyFlinkOldBatchTableTestCase
class StreamTableSetOperationTests(PyFlinkOldBatchTableTestCase):
data1 = [(1, "Hi", "Hello")]
data2 = [(3, "Hello", "Hello")]
schema = ["a", "b", "c"]
def test_minus(self):
t_env = self.t_env
t1 = t_env.from_e... | flink-python/pyflink/table/tests/test_set_operation.py |
from pyflink.testing.test_case_utils import PyFlinkOldBatchTableTestCase
class StreamTableSetOperationTests(PyFlinkOldBatchTableTestCase):
data1 = [(1, "Hi", "Hello")]
data2 = [(3, "Hello", "Hello")]
schema = ["a", "b", "c"]
def test_minus(self):
t_env = self.t_env
t1 = t_env.from_e... | 0.647464 | 0.48987 |
import json
from unittest.mock import patch
from federation.hostmeta.fetchers import (
fetch_nodeinfo_document, fetch_nodeinfo2_document, fetch_statisticsjson_document, fetch_mastodon_document,
fetch_matrix_document)
from federation.tests.fixtures.hostmeta import NODEINFO_WELL_KNOWN_BUGGY, NODEINFO_WELL_KNOWN_... | federation/tests/hostmeta/test_fetchers.py | import json
from unittest.mock import patch
from federation.hostmeta.fetchers import (
fetch_nodeinfo_document, fetch_nodeinfo2_document, fetch_statisticsjson_document, fetch_mastodon_document,
fetch_matrix_document)
from federation.tests.fixtures.hostmeta import NODEINFO_WELL_KNOWN_BUGGY, NODEINFO_WELL_KNOWN_... | 0.565059 | 0.411525 |
from collections import defaultdict
def get_bert_mappings(berts):
new_i=0
new_bert=[]
mapping=defaultdict(list)
for bert_i, bert_token in enumerate(berts):
if bert_i==0 or bert_i==len(berts)-1: continue
if bert_i>1 and not bert_token.startswith('##'):
print(new_i, current_to... | tmp_scripts/map_embeddings.py | from collections import defaultdict
def get_bert_mappings(berts):
new_i=0
new_bert=[]
mapping=defaultdict(list)
for bert_i, bert_token in enumerate(berts):
if bert_i==0 or bert_i==len(berts)-1: continue
if bert_i>1 and not bert_token.startswith('##'):
print(new_i, current_to... | 0.300951 | 0.138987 |
import os
import csv
import shutil
import requests
import contextlib
from db import db_insert_stocks, db_search_stocks
#filename = 'data/tmp-stocks/stocks.json'
def download_stocks():
directory = 'data/tmp-stocks/'
file = 'stocks.json'
filename = directory + file
# Oslo Bors, Oslo Axess, and Merku... | download.py | import os
import csv
import shutil
import requests
import contextlib
from db import db_insert_stocks, db_search_stocks
#filename = 'data/tmp-stocks/stocks.json'
def download_stocks():
directory = 'data/tmp-stocks/'
file = 'stocks.json'
filename = directory + file
# Oslo Bors, Oslo Axess, and Merku... | 0.281504 | 0.129761 |
#---------------------------------File Note------------------------------------
#This file defines all the error code and error handler mechanism
#--------------------------------Global Variables------------------------------
UINS_CAT = 100
WIN_REG_SEARCH_FAIL = 101
UNIMPL_APP = 200
SYS_ERR = 300
TIME_OUT = 400
DIM_I... | scripts/perf/old/errorHandler.py |
#---------------------------------File Note------------------------------------
#This file defines all the error code and error handler mechanism
#--------------------------------Global Variables------------------------------
UINS_CAT = 100
WIN_REG_SEARCH_FAIL = 101
UNIMPL_APP = 200
SYS_ERR = 300
TIME_OUT = 400
DIM_I... | 0.285173 | 0.076788 |
from src.utils import *
def serialize_string_descriptor(name_string):
return '?%s aida:hasName "%s" .' % (NODE, decode_name(name_string.strip('"')))
def serialize_text_descriptor(doceid, start, end):
return '''
[ a aida:TextJustification ;
aida:source "%... | src/sparql_utils.py | from src.utils import *
def serialize_string_descriptor(name_string):
return '?%s aida:hasName "%s" .' % (NODE, decode_name(name_string.strip('"')))
def serialize_text_descriptor(doceid, start, end):
return '''
[ a aida:TextJustification ;
aida:source "%... | 0.458349 | 0.173568 |
import click
import logging
import pandas as pd
from IVF_extremes.IVF_func import *
import os
resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
@click.command()
@click.option('--coc', required=True, type=int, help='number of cocs')
@click.option('--mii', required=True, type=int, help='number of ma... | IVF_extremes/single_check.py | import click
import logging
import pandas as pd
from IVF_extremes.IVF_func import *
import os
resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
@click.command()
@click.option('--coc', required=True, type=int, help='number of cocs')
@click.option('--mii', required=True, type=int, help='number of ma... | 0.482429 | 0.168788 |
from __future__ import division
import json
import os
import copy
import collections
import argparse
import csv
import neuroglancer
import neuroglancer.cli
import numpy as np
class State(object):
def __init__(self, path):
self.path = path
self.body_labels = collections.OrderedDict()
def loa... | python/neuroglancer/tool/filter_bodies.py | from __future__ import division
import json
import os
import copy
import collections
import argparse
import csv
import neuroglancer
import neuroglancer.cli
import numpy as np
class State(object):
def __init__(self, path):
self.path = path
self.body_labels = collections.OrderedDict()
def loa... | 0.472927 | 0.18396 |
import numpy as np
from typing import Tuple, List, Union
class ReplayBuffer:
def __init__(self, state_dims: int, action_dims: int, batch_size: int = 64, capacity: int = 1000000) -> None:
self.capacity = capacity
self.batch_size = batch_size
self.buffer_state = np.empty(shape=(capacity, st... | openrl/util/replay_buffer.py | import numpy as np
from typing import Tuple, List, Union
class ReplayBuffer:
def __init__(self, state_dims: int, action_dims: int, batch_size: int = 64, capacity: int = 1000000) -> None:
self.capacity = capacity
self.batch_size = batch_size
self.buffer_state = np.empty(shape=(capacity, st... | 0.780453 | 0.501282 |
import copy
import csv
import numpy as np
import os
import pandas as pd
import pdb
from . import utils
def read_raw_csv(file, target = 'domain1_score'):
'''
Reading the main training file is tricky. We rely on these two posts:
- https://stackoverflow.com/a/37723241/2232265
- https://stackoverflo... | asap_essay_scoring/data.py | import copy
import csv
import numpy as np
import os
import pandas as pd
import pdb
from . import utils
def read_raw_csv(file, target = 'domain1_score'):
'''
Reading the main training file is tricky. We rely on these two posts:
- https://stackoverflow.com/a/37723241/2232265
- https://stackoverflo... | 0.683102 | 0.369884 |
import os
from tron import Misc
location = Misc.location.determine_location()
def getActors(actorName=None, hostName=None):
# Bootstrap the whole configuration system
configPath = os.environ.get('CONFIG_DIR', os.path.join(os.environ['TRON_DIR'], 'config'))
Misc.cfg.init(path=configPath, verbose=False)... | tron/listActors.py |
import os
from tron import Misc
location = Misc.location.determine_location()
def getActors(actorName=None, hostName=None):
# Bootstrap the whole configuration system
configPath = os.environ.get('CONFIG_DIR', os.path.join(os.environ['TRON_DIR'], 'config'))
Misc.cfg.init(path=configPath, verbose=False)... | 0.368406 | 0.087058 |
import numpy as np
from autoarray import decorator_util
@decorator_util.jit()
def constant_regularization_matrix_from_pixel_neighbors(
coefficient, pixel_neighbors, pixel_neighbors_size
):
"""From the pixel-neighbors, setup the regularization matrix using the instance regularization scheme.
Parameters
... | autoarray/util/regularization_util.py | import numpy as np
from autoarray import decorator_util
@decorator_util.jit()
def constant_regularization_matrix_from_pixel_neighbors(
coefficient, pixel_neighbors, pixel_neighbors_size
):
"""From the pixel-neighbors, setup the regularization matrix using the instance regularization scheme.
Parameters
... | 0.95232 | 0.946101 |
import logging
import json
import voluptuous as vol
import requests
from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA)
from homeassistant.components.climate.const import (
STATE_AUTO, STATE_COOL, STATE_ECO, STATE_HEAT,
SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE,
STATE_MAN... | toon_google/climate.py | import logging
import json
import voluptuous as vol
import requests
from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA)
from homeassistant.components.climate.const import (
STATE_AUTO, STATE_COOL, STATE_ECO, STATE_HEAT,
SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE,
STATE_MAN... | 0.730001 | 0.109825 |
import threading
import time
import os
import pytest
from ..logrdis import config
from ..logrdis import db
from ..logrdis.socket import SocketServer
server = SocketServer()
def find_test_yaml(test_file):
for root, dirs, files in os.walk('.'):
if test_file in files:
return os.path.join(root, te... | tests/conftest.py | import threading
import time
import os
import pytest
from ..logrdis import config
from ..logrdis import db
from ..logrdis.socket import SocketServer
server = SocketServer()
def find_test_yaml(test_file):
for root, dirs, files in os.walk('.'):
if test_file in files:
return os.path.join(root, te... | 0.406744 | 0.152158 |
import yaml
from map_cell import MapCell
def parse_yaml():
"""
Parse yaml to python dict
"""
file_path = "./input.yaml"
with open(file_path) as file:
yaml_parsed = yaml.safe_load(file)
return yaml_parsed
def init_map(yaml_content):
"""
Init the game map acco... | Dragons_and_Princesses.py |
import yaml
from map_cell import MapCell
def parse_yaml():
"""
Parse yaml to python dict
"""
file_path = "./input.yaml"
with open(file_path) as file:
yaml_parsed = yaml.safe_load(file)
return yaml_parsed
def init_map(yaml_content):
"""
Init the game map acco... | 0.211743 | 0.359477 |
import time
from math import pi, cos, sin
# Function boundAngle(angle) takes any angle as "angle" and returns the
# equivalent angle bound within 0 <= angle < 2 * Pi
def boundAngle(angle):
return angle % (2 * pi)
# Function relativeAngle(angleRef, angle) returns the shortest relative
# angle from a reference angl... | odometer.py | import time
from math import pi, cos, sin
# Function boundAngle(angle) takes any angle as "angle" and returns the
# equivalent angle bound within 0 <= angle < 2 * Pi
def boundAngle(angle):
return angle % (2 * pi)
# Function relativeAngle(angleRef, angle) returns the shortest relative
# angle from a reference angl... | 0.823328 | 0.674335 |
import matplotlib.pyplot as plt
import numpy as np
import csv
def adjacent_values(vals, q1, q3):
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_valu... | general/violin_plots.py | import matplotlib.pyplot as plt
import numpy as np
import csv
def adjacent_values(vals, q1, q3):
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_valu... | 0.416203 | 0.500732 |
from it_automation.run import read_description_directory, post_description
import os
import pytest
from unittest import mock
def test_read_description_directory():
test_description_directory = os.path.join(
os.path.expanduser('~'),
'Documents/'
'google_class/'
'project_8/'
'... | tests/test_run.py | from it_automation.run import read_description_directory, post_description
import os
import pytest
from unittest import mock
def test_read_description_directory():
test_description_directory = os.path.join(
os.path.expanduser('~'),
'Documents/'
'google_class/'
'project_8/'
'... | 0.501953 | 0.32469 |
import scrapy
import js2py
import logging
from . import util
# spider for dealer.com templated websites
class BimmerDealercomSpider(scrapy.Spider):
name = 'bimmer_dealercom'
dealers = [
{
"name": '<NAME>MW',
"url": 'https://www.paulmillerbmw.com/new-inventory/index.htm?model=X3... | dealers/dealers/spiders/bimmer_dealercom.py | import scrapy
import js2py
import logging
from . import util
# spider for dealer.com templated websites
class BimmerDealercomSpider(scrapy.Spider):
name = 'bimmer_dealercom'
dealers = [
{
"name": '<NAME>MW',
"url": 'https://www.paulmillerbmw.com/new-inventory/index.htm?model=X3... | 0.354545 | 0.23001 |
import cStringIO
import re
class GitParser:
def __init__(self, strem):
self.fake_file = cStringIO.StringIO(strem)
self.commits = []
def run(self):
commit = GitCommit()
for line in self.fake_file:
if line == '' or line == '\n':
pass
elif bool(re.match('commit', line, re.IGNORECASE)):
... | lib/GitParser.py |
import cStringIO
import re
class GitParser:
def __init__(self, strem):
self.fake_file = cStringIO.StringIO(strem)
self.commits = []
def run(self):
commit = GitCommit()
for line in self.fake_file:
if line == '' or line == '\n':
pass
elif bool(re.match('commit', line, re.IGNORECASE)):
... | 0.133556 | 0.123551 |
import os
__here__ = os.path.dirname(__file__)
TEST_DATA = '''\
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegc... | task_08/task.py | import os
__here__ = os.path.dirname(__file__)
TEST_DATA = '''\
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegc... | 0.576661 | 0.278376 |
import doctest
from formencode.htmlgen import html
# A test value that can't be encoded as ascii:
uni_value = u'\xff'
str_value = uni_value if str is unicode else uni_value.encode('utf-8')
def test_basic():
output = '<a href="test">hey there</a>'
assert str(html.a(href='test')('hey there')) == output
as... | formencode/tests/test_htmlgen.py | import doctest
from formencode.htmlgen import html
# A test value that can't be encoded as ascii:
uni_value = u'\xff'
str_value = uni_value if str is unicode else uni_value.encode('utf-8')
def test_basic():
output = '<a href="test">hey there</a>'
assert str(html.a(href='test')('hey there')) == output
as... | 0.52074 | 0.467028 |
GRID_ROWS = GRID_COLUMNS = 9
BOX_ROWS = BOX_COLUMNS = 3
class Grid:
def __init__(self):
self.squares = self._create_grid_squares()
self.boxes = self._create_grid_boxes()
self.rows = self._create_grid_rows()
self.columns = self._create_grid_columns()
self.row_count =... | src/grid.py | GRID_ROWS = GRID_COLUMNS = 9
BOX_ROWS = BOX_COLUMNS = 3
class Grid:
def __init__(self):
self.squares = self._create_grid_squares()
self.boxes = self._create_grid_boxes()
self.rows = self._create_grid_rows()
self.columns = self._create_grid_columns()
self.row_count =... | 0.501953 | 0.282567 |
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
filters = frappe._dict(filters or {})
columns = get_columns(filters)
data = get_data(filters)
return columns, data
def get_columns(filters):
columns = [
{
"label": _("Role"),
"fieldtype": "Link",
"fi... | frappe/core/report/role_permission_report/role_permission_report.py |
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
filters = frappe._dict(filters or {})
columns = get_columns(filters)
data = get_data(filters)
return columns, data
def get_columns(filters):
columns = [
{
"label": _("Role"),
"fieldtype": "Link",
"fi... | 0.500732 | 0.338186 |
from apricot import TestWithServers
from general_utils import bytes_to_human, human_to_bytes
from server_utils import ServerFailed
class PoolTestBase(TestWithServers):
"""Base pool test class.
:avocado: recursive
"""
def setUp(self):
"""Set up each test case."""
# Create test-case-sp... | src/tests/ftest/util/pool_test_base.py | from apricot import TestWithServers
from general_utils import bytes_to_human, human_to_bytes
from server_utils import ServerFailed
class PoolTestBase(TestWithServers):
"""Base pool test class.
:avocado: recursive
"""
def setUp(self):
"""Set up each test case."""
# Create test-case-sp... | 0.92367 | 0.484868 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from pathlib import Path
from PIL import Image
from utils import create_patches_overlap
from plipy.ddl import DDLInpainting
def iter_algo(y, D, A, n_iter, L, algo="fista", lambd=0.1):
out = np.zeros((D.sh... | experiments/others/angle_g1_g2.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from pathlib import Path
from PIL import Image
from utils import create_patches_overlap
from plipy.ddl import DDLInpainting
def iter_algo(y, D, A, n_iter, L, algo="fista", lambd=0.1):
out = np.zeros((D.sh... | 0.8745 | 0.42656 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'ApplicationCSVMappingParametersArgs',
'ApplicationCatalogConfigurationArgs',
'ApplicationCheckpointConfigurationArgs',
'ApplicationCloudWatchL... | sdk/python/pulumi_aws_native/kinesisanalyticsv2/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'ApplicationCSVMappingParametersArgs',
'ApplicationCatalogConfigurationArgs',
'ApplicationCheckpointConfigurationArgs',
'ApplicationCloudWatchL... | 0.819171 | 0.043224 |
from __future__ import division
from nltk.tokenize import word_tokenize
import nltk
from custom_nltk.classify import naivebayes
import json
VERB_TAG_LIST = ['VB','VBZ','VBP','VBG','VBD','VBN']
NOUN_TAG_LIST = ['NN','NNS','NNP','NNPS']
ADJECTIVE_TAG_LIST = ['JJ','JJR','JJS']
ADVERB_TAG_LIST = ['RB','RBR','RBS'... | languageModule.py | from __future__ import division
from nltk.tokenize import word_tokenize
import nltk
from custom_nltk.classify import naivebayes
import json
VERB_TAG_LIST = ['VB','VBZ','VBP','VBG','VBD','VBN']
NOUN_TAG_LIST = ['NN','NNS','NNP','NNPS']
ADJECTIVE_TAG_LIST = ['JJ','JJR','JJS']
ADVERB_TAG_LIST = ['RB','RBR','RBS'... | 0.457864 | 0.227041 |
from armi import settings, runLog
from armi.bookkeeping.report import data
def setData(name, value, group=None, reports=None):
"""
Stores data in accordance with the specified parameters for use later.
Parameters
----------
name : str
value : Object
Any value desired.
group : data... | armi/bookkeeping/report/__init__.py | from armi import settings, runLog
from armi.bookkeeping.report import data
def setData(name, value, group=None, reports=None):
"""
Stores data in accordance with the specified parameters for use later.
Parameters
----------
name : str
value : Object
Any value desired.
group : data... | 0.765506 | 0.336508 |
import csv
import pathlib
from typing import Dict, List
def construct_rows(header: list, rows: list) -> List[Dict]:
"""Construct a list of csv row dicts.\n
Arguments:
header {list} -- csv header\n
rows {list} -- csv contents\n
to warp if there is only a single row, e.g... | csv_tools.py | import csv
import pathlib
from typing import Dict, List
def construct_rows(header: list, rows: list) -> List[Dict]:
"""Construct a list of csv row dicts.\n
Arguments:
header {list} -- csv header\n
rows {list} -- csv contents\n
to warp if there is only a single row, e.g... | 0.837121 | 0.342544 |
import asyncio
import sys
from aiotk import cancel, follow_through
from asyncio import Task
from typing import (
Any,
Awaitable,
ContextManager,
Optional,
overload,
)
from typing_extensions import AsyncContextManager
class EnsureDone:
"""Ensure a background task completes before leaving a ... | src/aiotk/_stack.py |
import asyncio
import sys
from aiotk import cancel, follow_through
from asyncio import Task
from typing import (
Any,
Awaitable,
ContextManager,
Optional,
overload,
)
from typing_extensions import AsyncContextManager
class EnsureDone:
"""Ensure a background task completes before leaving a ... | 0.806662 | 0.408041 |
from BF_generators import *
from pyeda.inter import *
from itertools import combinations
from string import ascii_lowercase
def is_LOF (signs, f, kind):
'''
signs: signs of the inputs as a string i.e 'aaia' where
'a' represents activator and 'i' represents inhibitor
f: BF as a binary string ; the strin... | code/BF_LOFs.py | from BF_generators import *
from pyeda.inter import *
from itertools import combinations
from string import ascii_lowercase
def is_LOF (signs, f, kind):
'''
signs: signs of the inputs as a string i.e 'aaia' where
'a' represents activator and 'i' represents inhibitor
f: BF as a binary string ; the strin... | 0.493409 | 0.343025 |
import time
from torch.utils.data import DataLoader
from dxtorchutils.utils.metrics import accuracy
import numpy as np
from dxtorchutils.utils.utils import state_logger
from dxtorchutils.utils.info_logger import Logger
import random
import torch
class TrainVessel:
def __init__(
self,
datal... | dxtorchutils/utils/train.py | import time
from torch.utils.data import DataLoader
from dxtorchutils.utils.metrics import accuracy
import numpy as np
from dxtorchutils.utils.utils import state_logger
from dxtorchutils.utils.info_logger import Logger
import random
import torch
class TrainVessel:
def __init__(
self,
datal... | 0.814348 | 0.309324 |
import errno
from os import getpid
from os.path import exists
from .libc import libc, get_errno
from .args_aliases import na, pop_all
from contextlib import contextmanager
@contextmanager
def setns(target_pid, parent_pid=0, proc='/proc', *args, **kwargs):
"""Change current namespaces to pid namespaces.
Chang... | pyspaces/setns.py | import errno
from os import getpid
from os.path import exists
from .libc import libc, get_errno
from .args_aliases import na, pop_all
from contextlib import contextmanager
@contextmanager
def setns(target_pid, parent_pid=0, proc='/proc', *args, **kwargs):
"""Change current namespaces to pid namespaces.
Chang... | 0.24015 | 0.115611 |
import platform as arch
from pynotifier import Notification
from urllib.parse import urlparse
from subprocess import Popen, PIPE
import os
import utils.adblock
import utils.bookmark
import utils.mime
import scripts
import confvar
from PyQt5.QtNetwork import QNetworkProxy
from PyQt5.QtCore import (
QUrl,
QObje... | lynx/webkit.py | import platform as arch
from pynotifier import Notification
from urllib.parse import urlparse
from subprocess import Popen, PIPE
import os
import utils.adblock
import utils.bookmark
import utils.mime
import scripts
import confvar
from PyQt5.QtNetwork import QNetworkProxy
from PyQt5.QtCore import (
QUrl,
QObje... | 0.368974 | 0.092565 |
import datetime
import yfinance
import math
import multitasking
import pandas as pd
from .tickers import get_symbols
from .helpers import chunks
from .db import \
get_symbols as get_downloaded, \
get_from_date, \
insert_price_volume_measurement, \
insert_symbols
@multitasking.task
def download_compan... | yfinance2pg/download.py | import datetime
import yfinance
import math
import multitasking
import pandas as pd
from .tickers import get_symbols
from .helpers import chunks
from .db import \
get_symbols as get_downloaded, \
get_from_date, \
insert_price_volume_measurement, \
insert_symbols
@multitasking.task
def download_compan... | 0.21036 | 0.198025 |
import numpy as np
from sklearn.utils import shuffle
class MulticlassLogisticRegression:
"""
Multiclass logreg scikit-learn-like with softmax.
Author:
<NAME>
"""
def __init__(self, learning_rate=1e-3, num_epochs=10000, verbose=True, print_epoch=1000, eps=1e-5,
gd_type='fu... | DeepLearning/log_reg.py | import numpy as np
from sklearn.utils import shuffle
class MulticlassLogisticRegression:
"""
Multiclass logreg scikit-learn-like with softmax.
Author:
<NAME>
"""
def __init__(self, learning_rate=1e-3, num_epochs=10000, verbose=True, print_epoch=1000, eps=1e-5,
gd_type='fu... | 0.71123 | 0.409752 |
import scrapy
import json
import sys
class NordVPNSpider(scrapy.Spider):
name = "nordvpn_spider"
url = "https://nordvpn.com/wp-admin/admin-ajax.php?action=get_user_info_data"
country_ids = {
"Albania":2,
"Argentina":10,
"Australia":13,
"Austria":14,
... | nordvpn_spider/spiders/nordvpn_spider.py | import scrapy
import json
import sys
class NordVPNSpider(scrapy.Spider):
name = "nordvpn_spider"
url = "https://nordvpn.com/wp-admin/admin-ajax.php?action=get_user_info_data"
country_ids = {
"Albania":2,
"Argentina":10,
"Australia":13,
"Austria":14,
... | 0.375592 | 0.211163 |
import pytest
from rest_framework.test import APIClient
from django.utils.timezone import now
from datetime import timedelta
from assertpy import assert_that
from ..models import *
@pytest.mark.django_db
def test_get_device_fake():
"""嵌入式设备可以获取当前位置相关的测试信息"""
group = RegionGroup.objects.create(name="新图 1 楼")
... | libookapi/tests/test_device.py | import pytest
from rest_framework.test import APIClient
from django.utils.timezone import now
from datetime import timedelta
from assertpy import assert_that
from ..models import *
@pytest.mark.django_db
def test_get_device_fake():
"""嵌入式设备可以获取当前位置相关的测试信息"""
group = RegionGroup.objects.create(name="新图 1 楼")
... | 0.381565 | 0.405802 |
import collections
import decimal
import json
import re
import time
from datetime import datetime
from decimal import Decimal
import logging
LOGGER = logging.getLogger()
def validate_config(config):
"""Validates config"""
errors = []
required_config_keys = [
's3_bucket_name',
's3_access_... | airbyte-integrations/connectors/destination-s3-parquet/destination_s3_parquet/utils.py | import collections
import decimal
import json
import re
import time
from datetime import datetime
from decimal import Decimal
import logging
LOGGER = logging.getLogger()
def validate_config(config):
"""Validates config"""
errors = []
required_config_keys = [
's3_bucket_name',
's3_access_... | 0.621656 | 0.183319 |
from decimal import Decimal
import pytest
from stellar_sdk import LiquidityPoolDeposit, Operation, Price
from . import *
class TestLiquidityPoolDeposit:
@pytest.mark.parametrize(
"max_amount_a, max_amount_b, min_price, max_price, source, xdr",
[
pytest.param(
"10",
... | tests/operation/test_liquidity_pool_deposit.py | from decimal import Decimal
import pytest
from stellar_sdk import LiquidityPoolDeposit, Operation, Price
from . import *
class TestLiquidityPoolDeposit:
@pytest.mark.parametrize(
"max_amount_a, max_amount_b, min_price, max_price, source, xdr",
[
pytest.param(
"10",
... | 0.619586 | 0.402803 |
from typing import List, Optional
import os
import threading
from nvidia.dali._multiproc import shared_mem
from nvidia.dali._multiproc.messages import Structure, ShmMessageDesc
from nvidia.dali._multiproc.shared_batch import _align_up as align_up
class QueueMeta(Structure):
_fields = ("capacity", "i"), ("size", ... | dali/python/nvidia/dali/_multiproc/shared_queue.py |
from typing import List, Optional
import os
import threading
from nvidia.dali._multiproc import shared_mem
from nvidia.dali._multiproc.messages import Structure, ShmMessageDesc
from nvidia.dali._multiproc.shared_batch import _align_up as align_up
class QueueMeta(Structure):
_fields = ("capacity", "i"), ("size", ... | 0.802749 | 0.160891 |
from keras.models import Sequential
from keras.layers import Conv1D,Dense,TimeDistributed,GlobalMaxPooling1D,BatchNormalization,CuDNNLSTM,CuDNNGRU,Bidirectional,MaxPooling1D
from keras.constraints import maxnorm
from keras.optimizers import Adam
from keras.layers import Flatten
def BGRU_Model2 (self) :
mode... | models.py | from keras.models import Sequential
from keras.layers import Conv1D,Dense,TimeDistributed,GlobalMaxPooling1D,BatchNormalization,CuDNNLSTM,CuDNNGRU,Bidirectional,MaxPooling1D
from keras.constraints import maxnorm
from keras.optimizers import Adam
from keras.layers import Flatten
def BGRU_Model2 (self) :
mode... | 0.881475 | 0.2587 |
import json
from typing import Union
import click
import matplotlib.pyplot as plt
from musicbrainzapi.cli.cli import pass_environment
import musicbrainzapi.wordcloud
from musicbrainzapi.api.lyrics.builder import LyricsBuilder
from musicbrainzapi.api.lyrics.director import LyricsClickDirector
@click.option('--dev'... | src/musicbrainzapi/cli/commands/cmd_lyrics.py | import json
from typing import Union
import click
import matplotlib.pyplot as plt
from musicbrainzapi.cli.cli import pass_environment
import musicbrainzapi.wordcloud
from musicbrainzapi.api.lyrics.builder import LyricsBuilder
from musicbrainzapi.api.lyrics.director import LyricsClickDirector
@click.option('--dev'... | 0.71113 | 0.187895 |
from database_connection import database_connection
import random
# Attivita(id_attivita,nome,descrizione,dipartimento)
def creazioni_attivita():
attivita_unipa = list()
attivita_unito = list()
attivita_unimi = list()
attivita_unina = list()
facolta_scientifiche_unito = ["Dipartimento di Economia... | script/popolamento_database/fill_attivita.py | from database_connection import database_connection
import random
# Attivita(id_attivita,nome,descrizione,dipartimento)
def creazioni_attivita():
attivita_unipa = list()
attivita_unito = list()
attivita_unimi = list()
attivita_unina = list()
facolta_scientifiche_unito = ["Dipartimento di Economia... | 0.280321 | 0.366533 |
import os
from xml.etree import ElementTree as et
from packageship.application.initialize.base import ESJson
DEFAULT_NSMAP = "http://linux.duke.edu/metadata/common"
RPM_NSMAP = "http://linux.duke.edu/metadata/rpm"
MAP = {
"pkgKey": None,
"pkgId": ".//{%s}checksum:text" % DEFAULT_NSMAP,
"name": ".//{%s}nam... | packageship/application/initialize/xtp.py | import os
from xml.etree import ElementTree as et
from packageship.application.initialize.base import ESJson
DEFAULT_NSMAP = "http://linux.duke.edu/metadata/common"
RPM_NSMAP = "http://linux.duke.edu/metadata/rpm"
MAP = {
"pkgKey": None,
"pkgId": ".//{%s}checksum:text" % DEFAULT_NSMAP,
"name": ".//{%s}nam... | 0.490724 | 0.095645 |
from eggshell.ocg.utils import temp_groups
from flyingpigeon import config
from eggshell.general.utils import archive, archiveextract, check_creationtime, download, FreeMemory, download_file, \
searchfile, local_path, make_dirs, rename_complexinputs, prepare_static_folder
from eggshell.ocg.utils import calc_groupi... | flyingpigeon/utils.py |
from eggshell.ocg.utils import temp_groups
from flyingpigeon import config
from eggshell.general.utils import archive, archiveextract, check_creationtime, download, FreeMemory, download_file, \
searchfile, local_path, make_dirs, rename_complexinputs, prepare_static_folder
from eggshell.ocg.utils import calc_groupi... | 0.587825 | 0.216467 |
from trimap_network.models import build_model, DataWrapper
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.sampler import WeightedRandomSampler
import cv2
import numpy as np
import logging
import math
import time
pipe_logger = logging.getLo... | pipeline/trimap_stage.py | from trimap_network.models import build_model, DataWrapper
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.sampler import WeightedRandomSampler
import cv2
import numpy as np
import logging
import math
import time
pipe_logger = logging.getLo... | 0.82425 | 0.32603 |
import unittest
from unittest.mock import patch
from flask import request
from main import app
class TestPlaceLandingPage(unittest.TestCase):
@patch('routes.api.place.get_display_name')
def test_place_landing(self, mock_get_display_name):
mock_get_display_name.return_value = {
'geoId/17... | server/tests/place_test.py |
import unittest
from unittest.mock import patch
from flask import request
from main import app
class TestPlaceLandingPage(unittest.TestCase):
@patch('routes.api.place.get_display_name')
def test_place_landing(self, mock_get_display_name):
mock_get_display_name.return_value = {
'geoId/17... | 0.400749 | 0.442998 |
from __future__ import absolute_import, division, print_function
__author__ = "<NAME> <<EMAIL>>"
__contributors__ = [
"<NAME> <<EMAIL>>",
"<NAME> <<EMAIL>>"
]
__copyright__ = "Copyright (c) 2021 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"
from flask import Flask, jsoni... | sasebot/app.py | from __future__ import absolute_import, division, print_function
__author__ = "<NAME> <<EMAIL>>"
__contributors__ = [
"<NAME> <<EMAIL>>",
"<NAME> <<EMAIL>>"
]
__copyright__ = "Copyright (c) 2021 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"
from flask import Flask, jsoni... | 0.413714 | 0.092565 |
import requests
import structlog
from django.utils import timezone
from utils.date import dateManager
from main.model.models import Forecast
from main.controller.logic import CustomizeLogic
logger = structlog.getLogger(__name__)
def get_forecast_json():
logger.debug("get things for weather forecast")
customi... | app/main/controller/forecast/forecastApi.py | import requests
import structlog
from django.utils import timezone
from utils.date import dateManager
from main.model.models import Forecast
from main.controller.logic import CustomizeLogic
logger = structlog.getLogger(__name__)
def get_forecast_json():
logger.debug("get things for weather forecast")
customi... | 0.291384 | 0.054424 |
from flask_wtf import FlaskForm
from markupsafe import escape, Markup
from wtforms import Field, SubmitField
from wtforms.fields import FieldList, SelectField, StringField
from wtforms.utils import unset_value
from wtforms.widgets import html_params, TextInput
class BaseForm(FlaskForm):
"""Add an invisible field ... | noggin/form/base.py | from flask_wtf import FlaskForm
from markupsafe import escape, Markup
from wtforms import Field, SubmitField
from wtforms.fields import FieldList, SelectField, StringField
from wtforms.utils import unset_value
from wtforms.widgets import html_params, TextInput
class BaseForm(FlaskForm):
"""Add an invisible field ... | 0.84124 | 0.190762 |
import json
from unittest import TestCase
import numpy as np
from odm_report_shot_coverage.models.camera import json_parse_camera
from odm_report_shot_coverage.models.test_fixtures import TestFixtures as Fixtures
class Test(TestCase):
def test_json_load_camera(self):
json_str = """
{
... | src/odm_report_shot_coverage/models/test_camera.py | import json
from unittest import TestCase
import numpy as np
from odm_report_shot_coverage.models.camera import json_parse_camera
from odm_report_shot_coverage.models.test_fixtures import TestFixtures as Fixtures
class Test(TestCase):
def test_json_load_camera(self):
json_str = """
{
... | 0.682574 | 0.397354 |
from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
import re
from webfriend.scripting.environment import Environment
from webfriend.scripting.scope import Scope
from webfriend.scripting.execute import execute_script
from prompt_toolkit import prompt
from prompt_too... | webfriend/repl.py | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
import re
from webfriend.scripting.environment import Environment
from webfriend.scripting.scope import Scope
from webfriend.scripting.execute import execute_script
from prompt_toolkit import prompt
from prompt_too... | 0.494141 | 0.072374 |
class Node:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
class DLL:
def __init__(self):
self.cnt = 0
self.head = None
self.tail = self.head
def insert(self, value):
new_node = Node(value)
... | double_linked_list.py | class Node:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
class DLL:
def __init__(self):
self.cnt = 0
self.head = None
self.tail = self.head
def insert(self, value):
new_node = Node(value)
... | 0.349089 | 0.157493 |
import os
import argparse
# Imports: third party
import numpy as np
import pandas as pd
import pytest
# Imports: first party
from ml4c3.recipes import train_model, infer_multimodal_multitask
from ml4c3.explorations import (
explore,
continuous_explore_header,
categorical_explore_header,
_tmap_requires... | tests/test_recipes.py | import os
import argparse
# Imports: third party
import numpy as np
import pandas as pd
import pytest
# Imports: first party
from ml4c3.recipes import train_model, infer_multimodal_multitask
from ml4c3.explorations import (
explore,
continuous_explore_header,
categorical_explore_header,
_tmap_requires... | 0.456652 | 0.32826 |
# updated 30-01-2015: writeDOT also writes color information for edges.
# updated 2-2-2015: writeDOT can also write directed graphs.
# updated 5-2-2015: no black fill color used, when more than numcolors**2 vertices.
# updated 29-1-2017: pep8 reformat, general improvements
import sys
from typing import IO, Tuple, Lis... | graph/graph_io.py |
# updated 30-01-2015: writeDOT also writes color information for edges.
# updated 2-2-2015: writeDOT can also write directed graphs.
# updated 5-2-2015: no black fill color used, when more than numcolors**2 vertices.
# updated 29-1-2017: pep8 reformat, general improvements
import sys
from typing import IO, Tuple, Lis... | 0.576184 | 0.478346 |
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
'''
import datetime
import re
from typing import Optional
import discord
import asyncpg
from discord.ext import commands, tas... | bot/extensions/starboard.py | This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
'''
import datetime
import re
from typing import Optional
import discord
import asyncpg
from discord.ext import commands, tas... | 0.7586 | 0.202226 |
import os
from mdutils.mdutils import MdUtils
originalPath = r"/home/luke/Documents/logbook"
saveLocation = r"/home/luke/Documents"
outputFileLocation = "/home/luke/Documents" + "/output.txt"
def main():
createFile()
#I feel like I could put this in the makeFolderList function somehow
yearFolders = os.l... | pythonlogbook/combineLogs.py | import os
from mdutils.mdutils import MdUtils
originalPath = r"/home/luke/Documents/logbook"
saveLocation = r"/home/luke/Documents"
outputFileLocation = "/home/luke/Documents" + "/output.txt"
def main():
createFile()
#I feel like I could put this in the makeFolderList function somehow
yearFolders = os.l... | 0.163479 | 0.164718 |
from unittest import TestCase
from datetime import datetime, timedelta, timezone
from uw_hrp.models import (
EmploymentStatus, JobProfile, SupervisoryOrganization,
Worker, WorkerPosition, parse_date, WorkerRef)
from uw_hrp.util import fdao_hrp_override
@fdao_hrp_override
class WorkerTest(TestCase):
def ... | uw_hrp/tests/test_models.py |
from unittest import TestCase
from datetime import datetime, timedelta, timezone
from uw_hrp.models import (
EmploymentStatus, JobProfile, SupervisoryOrganization,
Worker, WorkerPosition, parse_date, WorkerRef)
from uw_hrp.util import fdao_hrp_override
@fdao_hrp_override
class WorkerTest(TestCase):
def ... | 0.632616 | 0.512266 |
import re
import click
from datetime import datetime
class Datetime(click.ParamType):
"""
A datetime object parsed via datetime.strptime.
Format specifiers can be found here :
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
Stolen from
https://github.c... | fire/cli/utils.py | import re
import click
from datetime import datetime
class Datetime(click.ParamType):
"""
A datetime object parsed via datetime.strptime.
Format specifiers can be found here :
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
Stolen from
https://github.c... | 0.431704 | 0.170612 |
import amber
from amber import AmberObject
import datetime as dt
class ContentType(enumerate):
Text = 'text'
Image = 'image'
Video = 'video'
class Reactions(enumerate):
Like = 'like'
Dislike = 'dislike'
Love = 'love'
Angry = 'angry'
Haha = 'haha'
class ShipPrivac... | src/ships.py | import amber
from amber import AmberObject
import datetime as dt
class ContentType(enumerate):
Text = 'text'
Image = 'image'
Video = 'video'
class Reactions(enumerate):
Like = 'like'
Dislike = 'dislike'
Love = 'love'
Angry = 'angry'
Haha = 'haha'
class ShipPrivac... | 0.210482 | 0.068475 |
import data_structure as ds
import configparser
import datetime
from keras.models import Sequential
from keras.layers import Dense, LSTM
from keras.callbacks import TensorBoard
from model_manipulation import Model
from matplotlib import pyplot as plt
print("All libraries are loaded from training")
# fit a customized... | modeling/training.py |
import data_structure as ds
import configparser
import datetime
from keras.models import Sequential
from keras.layers import Dense, LSTM
from keras.callbacks import TensorBoard
from model_manipulation import Model
from matplotlib import pyplot as plt
print("All libraries are loaded from training")
# fit a customized... | 0.591487 | 0.585457 |
from zipfile import ZipFile
from urllib.request import urlretrieve
from urllib import error
import pandas as pd
import urllib
import os
import seaborn as sns
import matplotlib.pyplot as plt
def download_zip():
"""download openpowerlifting data (~77mb) and store in this .py file's directory (default path)"""
t... | stats.py | from zipfile import ZipFile
from urllib.request import urlretrieve
from urllib import error
import pandas as pd
import urllib
import os
import seaborn as sns
import matplotlib.pyplot as plt
def download_zip():
"""download openpowerlifting data (~77mb) and store in this .py file's directory (default path)"""
t... | 0.498291 | 0.322073 |
class GameBoard:
"""
A GameBoard object is a representation of the game in an array form
It hold's the current board, player's letters, and win conditions
Attributes:
__board (String[]): array representation of the board
__player_one (String): Letter of player one
__player_two (S... | GameBoard.py | class GameBoard:
"""
A GameBoard object is a representation of the game in an array form
It hold's the current board, player's letters, and win conditions
Attributes:
__board (String[]): array representation of the board
__player_one (String): Letter of player one
__player_two (S... | 0.851968 | 0.689889 |
import logging
import os
import threading
from galaxy.util import asbool
from galaxy.web.framework.helpers import time_ago
from tool_shed.util import readme_util
import tool_shed.util.shed_util_common as suc
log = logging.getLogger( __name__ )
# String separator
STRSEP = '__ESEP__'
class Folder( object ):
"""Co... | lib/galaxy/webapps/tool_shed/util/container_util.py | import logging
import os
import threading
from galaxy.util import asbool
from galaxy.web.framework.helpers import time_ago
from tool_shed.util import readme_util
import tool_shed.util.shed_util_common as suc
log = logging.getLogger( __name__ )
# String separator
STRSEP = '__ESEP__'
class Folder( object ):
"""Co... | 0.517815 | 0.069164 |
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _GeomTools.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
i... | Lib/site-packages/OCC/GeomTools.py |
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _GeomTools.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
i... | 0.350866 | 0.08389 |
import tkinter as tk
from tkinter import ttk
import threading
import time
from rmslogin import RakutenRms
class SearchWindow:
def __init__(self, parent, top, rms):
self.items = []
self.rms = rms
self.parent = parent
self.search_type_dict = {"商品名": "itemName",
... | app.py |
import tkinter as tk
from tkinter import ttk
import threading
import time
from rmslogin import RakutenRms
class SearchWindow:
def __init__(self, parent, top, rms):
self.items = []
self.rms = rms
self.parent = parent
self.search_type_dict = {"商品名": "itemName",
... | 0.386532 | 0.101589 |