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 |
|---|---|---|---|---|
MENUS = {
'MAIN':
[['[&File]', 'FILE', None],
['[&Edit]', 'EDIT', None],
['[&Code]', 'CODE', None],
['[&Macro]', 'MACRO', None],
['[&Tools]', 'TOOLS', None],
['[&Git]', 'GIT', None],
['[&Window]', 'WINDOW', None]],
'FILE':
[['&New', None, 'file.new'],
['&Open', None, ... | kaa/filetype/default/menu.py | MENUS = {
'MAIN':
[['[&File]', 'FILE', None],
['[&Edit]', 'EDIT', None],
['[&Code]', 'CODE', None],
['[&Macro]', 'MACRO', None],
['[&Tools]', 'TOOLS', None],
['[&Git]', 'GIT', None],
['[&Window]', 'WINDOW', None]],
'FILE':
[['&New', None, 'file.new'],
['&Open', None, ... | 0.213787 | 0.204759 |
from keras.engine.topology import Layer
class SpatialPyramidPoling(Layer):
"""Spatial pyramid pooling layer for 2D inputs.
See Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition,
<NAME>, <NAME>, <NAME>, <NAME>
# Arguments
pool_list: list of int
# Input shape
... | spp_layer.py | from keras.engine.topology import Layer
class SpatialPyramidPoling(Layer):
"""Spatial pyramid pooling layer for 2D inputs.
See Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition,
<NAME>, <NAME>, <NAME>, <NAME>
# Arguments
pool_list: list of int
# Input shape
... | 0.920039 | 0.485844 |
import pandas as pd
from datetime import datetime
import math
import pathlib
import sys
import os
# Read data downloaded from the crawler
def read_data(path):
try:
data = pd.read_excel(path, engine="odf")
return data
except Exception as excep:
sys.stderr.write(
"'Não foi p... | mpdft/src/parser.py | import pandas as pd
from datetime import datetime
import math
import pathlib
import sys
import os
# Read data downloaded from the crawler
def read_data(path):
try:
data = pd.read_excel(path, engine="odf")
return data
except Exception as excep:
sys.stderr.write(
"'Não foi p... | 0.338186 | 0.371878 |
import torch
import torchmetrics
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from . import backbone
from siamese.trainer.loss import ContrastiveLoss
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torchmetrics
import torch.optim as optim
class SiameseTa... | siamese/modules/model.py | import torch
import torchmetrics
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from . import backbone
from siamese.trainer.loss import ContrastiveLoss
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torchmetrics
import torch.optim as optim
class SiameseTa... | 0.880328 | 0.386242 |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... | exercises/perform_model_selection.py | from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... | 0.939429 | 0.482734 |
import math
def multiply(quaternion1, quaternion0):
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return [ x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0]
def conjugate(quaternio... | osgar/lib/quaternion.py | import math
def multiply(quaternion1, quaternion0):
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return [ x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0]
def conjugate(quaternio... | 0.785391 | 0.66939 |
from abc import abstractmethod, ABC
from typing import Optional, Sequence, Hashable, Any, Union, Iterable, overload, Dict
from coba.utilities import HashableDict
from coba.pipes import Source
Action = Union[Hashable, HashableDict]
Context = Union[None, Hashable, HashableDict]
class SimulatedInteraction:
"""A cl... | coba/environments/core.py | from abc import abstractmethod, ABC
from typing import Optional, Sequence, Hashable, Any, Union, Iterable, overload, Dict
from coba.utilities import HashableDict
from coba.pipes import Source
Action = Union[Hashable, HashableDict]
Context = Union[None, Hashable, HashableDict]
class SimulatedInteraction:
"""A cl... | 0.943217 | 0.721694 |
import pygame
import math
class Planet:
def __init__(self, surface, color, position, radius, center):
self.radius = radius
self.surface = surface
self.color = color
self.setPosition(position)
self.center = center
self.setOrbitOffset(0)
self.setOrbitPeriod(1)
... | space/planet.py | import pygame
import math
class Planet:
def __init__(self, surface, color, position, radius, center):
self.radius = radius
self.surface = surface
self.color = color
self.setPosition(position)
self.center = center
self.setOrbitOffset(0)
self.setOrbitPeriod(1)
... | 0.714827 | 0.409132 |
import glob
import logging
import os.path
import shutil
import signal
import sys
def patch_crypto():
# This is needed to help pyinstaller find the right backend
from cryptography.hazmat import backends
from cryptography.hazmat.backends.openssl.backend import backend as be_cc
backends._available_backen... | __main__.py | import glob
import logging
import os.path
import shutil
import signal
import sys
def patch_crypto():
# This is needed to help pyinstaller find the right backend
from cryptography.hazmat import backends
from cryptography.hazmat.backends.openssl.backend import backend as be_cc
backends._available_backen... | 0.259263 | 0.055311 |
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from users.tests import token_auth
from .models import BeverageType, Purchase
class PurchasesTest(APITestCase):
api_uri = '/api/purchases'
... | purchases/tests.py | from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from users.tests import token_auth
from .models import BeverageType, Purchase
class PurchasesTest(APITestCase):
api_uri = '/api/purchases'
... | 0.637821 | 0.166032 |
import pytest
import pyomo.environ as pyo
from idaes.apps.caprese.categorize import (
categorize_dae_variables_and_constraints,
)
from idaes.apps.caprese.tests.test_simple_model import (
make_model,
initialize_t0,
)
from idaes.apps.caprese.estimator import (
_Estimator... | idaes/apps/caprese/tests/test_estimator.py | import pytest
import pyomo.environ as pyo
from idaes.apps.caprese.categorize import (
categorize_dae_variables_and_constraints,
)
from idaes.apps.caprese.tests.test_simple_model import (
make_model,
initialize_t0,
)
from idaes.apps.caprese.estimator import (
_Estimator... | 0.531939 | 0.541288 |
from datetime import timedelta
import re
from typing import Any, Dict, Optional, Union
multiple_map = {
"K": 1024 ** 0,
"M": 1024 ** 1,
"G": 1024 ** 2,
"T": 1024 ** 3,
"E": 1024 ** 4,
}
state_colors = {
"FAILED": "red",
"TIMEOUT": "red",
"OUT_OF_MEMORY": "red",
"RUNNING": "cyan",
... | src/reportseff/job.py | from datetime import timedelta
import re
from typing import Any, Dict, Optional, Union
multiple_map = {
"K": 1024 ** 0,
"M": 1024 ** 1,
"G": 1024 ** 2,
"T": 1024 ** 3,
"E": 1024 ** 4,
}
state_colors = {
"FAILED": "red",
"TIMEOUT": "red",
"OUT_OF_MEMORY": "red",
"RUNNING": "cyan",
... | 0.919439 | 0.343342 |
import torch
from torch import nn
import torch.nn.functional as F
from typing import Sequence, Tuple, Dict
class DistogramHead(nn.Module):
"""
https://github.com/lupoglaz/alphafold/blob/2d53ad87efedcbbda8e67ab3be96af769dbeae7d/alphafold/model/modules.py#L1348
"""
def __init__(self, config, global_config, num_feat... | alphafold/Model/Heads/distogram.py | import torch
from torch import nn
import torch.nn.functional as F
from typing import Sequence, Tuple, Dict
class DistogramHead(nn.Module):
"""
https://github.com/lupoglaz/alphafold/blob/2d53ad87efedcbbda8e67ab3be96af769dbeae7d/alphafold/model/modules.py#L1348
"""
def __init__(self, config, global_config, num_feat... | 0.860398 | 0.475971 |
from typing import List
import argparse
import pandas as pd
from ulfs import stats_utils, tex_utils
def reduce(df_l: List[pd.DataFrame], out_csv: str, out_tex: str):
# drop_columns = [
# 'seed', 'b', 'terminate_reason', 'train_acc',
# 'val_same_gnd_clusters', 'val_same_pred_clusters', 'val_new_gn... | ref_task/analysis/texrel/reduce_vs_shapeworld.py | from typing import List
import argparse
import pandas as pd
from ulfs import stats_utils, tex_utils
def reduce(df_l: List[pd.DataFrame], out_csv: str, out_tex: str):
# drop_columns = [
# 'seed', 'b', 'terminate_reason', 'train_acc',
# 'val_same_gnd_clusters', 'val_same_pred_clusters', 'val_new_gn... | 0.562777 | 0.404449 |
import logging
class Result:
def __init__(self, value, pos: int):
self.value = value
self.pos = pos
class Parser:
def __call__(self, tokens: list, pos: int) -> Result:
return None
def __add__(self, other):
return Concat(self, other)
def __or__(self, other):
... | makehex/combinators.py | import logging
class Result:
def __init__(self, value, pos: int):
self.value = value
self.pos = pos
class Parser:
def __call__(self, tokens: list, pos: int) -> Result:
return None
def __add__(self, other):
return Concat(self, other)
def __or__(self, other):
... | 0.739986 | 0.457137 |
from quex.engine.state_machine.core import DFA
import quex.engine.state_machine.construction.parallelize as parallelize
def stem(Dfa):
"""RETURNS: DFA consisting only of branches until the first acceptance
state.
"""
return __clone_until_acceptance(Dfa, Dfa.init_s... | quex/engine/state_machine/cut/stem_and_branches.py | from quex.engine.state_machine.core import DFA
import quex.engine.state_machine.construction.parallelize as parallelize
def stem(Dfa):
"""RETURNS: DFA consisting only of branches until the first acceptance
state.
"""
return __clone_until_acceptance(Dfa, Dfa.init_s... | 0.639286 | 0.547948 |
import math
from utils import *
class TAG(object):
"""
Implementation of our proposed TAG optimizer
"""
def __init__(self, model, args, num_tasks, optim='rms', lr=None, b=5):
"""
Gets all the necessary arguments for initialization
:param model: Current model
:param args: All arguments for experiment confi... | tag_update.py | import math
from utils import *
class TAG(object):
"""
Implementation of our proposed TAG optimizer
"""
def __init__(self, model, args, num_tasks, optim='rms', lr=None, b=5):
"""
Gets all the necessary arguments for initialization
:param model: Current model
:param args: All arguments for experiment confi... | 0.566258 | 0.549218 |
import unittest
from flask import json
from mock import patch, Mock
from app import app
class StorageResourceTestCase(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
mock = patch('flask_login.AnonymousUserMixin.is_authenticated').start()
mock.return_value = True
def... | app/storage/tests.py | import unittest
from flask import json
from mock import patch, Mock
from app import app
class StorageResourceTestCase(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
mock = patch('flask_login.AnonymousUserMixin.is_authenticated').start()
mock.return_value = True
def... | 0.497803 | 0.306073 |
from pymodm.errors import ValidationError
def together(*funcs):
"""Run several validators successively on the same value."""
def validator(value):
for func in funcs:
func(value)
return validator
def validator_for_func(func):
"""Return a validator that re-raises any errors from t... | env/lib/python3.6/site-packages/pymodm/validators.py |
from pymodm.errors import ValidationError
def together(*funcs):
"""Run several validators successively on the same value."""
def validator(value):
for func in funcs:
func(value)
return validator
def validator_for_func(func):
"""Return a validator that re-raises any errors from t... | 0.889162 | 0.500366 |
import locale
import time
import re
from dateutil.parser import parse
from datetime import datetime, time as ltime
from time import mktime as mktime, time as ttime
'''
Магический ооочень простой объект времени
'''
class magictime:
tformat = '%d %b %Y %H:%M:%S'
mysqlformat = '%Y%m%d%H%M%S'
... | magictime.py |
import locale
import time
import re
from dateutil.parser import parse
from datetime import datetime, time as ltime
from time import mktime as mktime, time as ttime
'''
Магический ооочень простой объект времени
'''
class magictime:
tformat = '%d %b %Y %H:%M:%S'
mysqlformat = '%Y%m%d%H%M%S'
... | 0.260954 | 0.138026 |
import logging
import aiogram.utils.markdown as md
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
impor... | aibot.py | import logging
import aiogram.utils.markdown as md
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
impor... | 0.202364 | 0.180233 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^date/$', views.DateListView.as_view(),
name='date_list'),
url(
r'^date/(?P<pk>[0-9]+)$', views.DateDetailView.as_view(),
name='date_detail'),
url(
r'^date/create/$', views.DateCreate.as_view(),
... | tokens/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^date/$', views.DateListView.as_view(),
name='date_list'),
url(
r'^date/(?P<pk>[0-9]+)$', views.DateDetailView.as_view(),
name='date_detail'),
url(
r'^date/create/$', views.DateCreate.as_view(),
... | 0.259544 | 0.141015 |
import copy
from typing import Tuple, List, Optional
from aparse import Literal
from dataclasses import dataclass, fields, field, is_dataclass
from viewformer.utils.schedules import Schedule
ModelType = Literal['codebook', 'transformer']
def asdict(obj):
dict_factory = dict
def _asdict_inner(obj, dict_fact... | viewformer/models/config.py | import copy
from typing import Tuple, List, Optional
from aparse import Literal
from dataclasses import dataclass, fields, field, is_dataclass
from viewformer.utils.schedules import Schedule
ModelType = Literal['codebook', 'transformer']
def asdict(obj):
dict_factory = dict
def _asdict_inner(obj, dict_fact... | 0.850049 | 0.180829 |
import popart
import pytest
import numpy as np
import test_util as tu
import tempfile
import os
# Test that you can train a model and then use the weight in a inference run
@tu.requires_ipu_model
def test_train_then_infer_via_file():
builder = popart.Builder()
input_shape = popart.TensorInfo("FLOAT", [1, 2,... | tests/integration/train_then_infer_test.py | import popart
import pytest
import numpy as np
import test_util as tu
import tempfile
import os
# Test that you can train a model and then use the weight in a inference run
@tu.requires_ipu_model
def test_train_then_infer_via_file():
builder = popart.Builder()
input_shape = popart.TensorInfo("FLOAT", [1, 2,... | 0.678859 | 0.545891 |
from flask import Flask, render_template, url_for,jsonify
import json
# python modules created for apis
from ormQueries import getSampleNames,getOTUbySamples,getSampleMetaData,getWashingFreq
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
import p... | app.py | from flask import Flask, render_template, url_for,jsonify
import json
# python modules created for apis
from ormQueries import getSampleNames,getOTUbySamples,getSampleMetaData,getWashingFreq
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
import p... | 0.739516 | 0.182225 |
from urllib.parse import quote
import hmac
import time
import requests
import logging
from base64 import b64encode
from hashlib import sha256
from com.data.abstract_calls import AbstractApiCall
from properties import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ASSOCIATE_TAG, \
AWS_PRODUCT_API_SERVICE, AWS_PRODUCT... | com/amazon/amazon_api.py | from urllib.parse import quote
import hmac
import time
import requests
import logging
from base64 import b64encode
from hashlib import sha256
from com.data.abstract_calls import AbstractApiCall
from properties import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ASSOCIATE_TAG, \
AWS_PRODUCT_API_SERVICE, AWS_PRODUCT... | 0.509276 | 0.037117 |
import hashlib
# Third party library imports
import click
import requests
# Needed to access API
PASS_URL = "https://api.pwnedpasswords.com/range/"
# Script information
VERSION = "0.1.2"
LOGO = r"""
__ __ __
| |--.---.-.--.--.-----. |__| | |--.-----.-----.-----.
| | _ | | | -__|... | haveibeenpwnwed_password_checker/pwned.py | import hashlib
# Third party library imports
import click
import requests
# Needed to access API
PASS_URL = "https://api.pwnedpasswords.com/range/"
# Script information
VERSION = "0.1.2"
LOGO = r"""
__ __ __
| |--.---.-.--.--.-----. |__| | |--.-----.-----.-----.
| | _ | | | -__|... | 0.63023 | 0.318989 |
from textwrap import dedent
from typing import Any, Dict, List
from shared.di import service_as_factory
from shared.postgresql_backend import ConnectionHandler
from shared.util import ModelLocked, collectionfield_and_fqid_from_fqfield
# FQID LOCKING
# positions: <1> <2> <3> <4> <5>
# a/1 modified: X X
... | writer/writer/postgresql_backend/sql_occ_locker_backend_service.py | from textwrap import dedent
from typing import Any, Dict, List
from shared.di import service_as_factory
from shared.postgresql_backend import ConnectionHandler
from shared.util import ModelLocked, collectionfield_and_fqid_from_fqfield
# FQID LOCKING
# positions: <1> <2> <3> <4> <5>
# a/1 modified: X X
... | 0.714827 | 0.212681 |
import json
def json_output(response: dict) -> str:
"""
Output API response in prettified JSON format
Parameters
----------
response : dict
Returns
-------
str
"""
return json.dumps(response, indent=2, sort_keys=True)
def table_output(response: d... | beeminder_sync/output/output.py | import json
def json_output(response: dict) -> str:
"""
Output API response in prettified JSON format
Parameters
----------
response : dict
Returns
-------
str
"""
return json.dumps(response, indent=2, sort_keys=True)
def table_output(response: d... | 0.613121 | 0.386648 |
from game.nodes.actor import Actor
from game.nodes.base import Base
from game.nodes.bullet import (
BulletBoxShape,
BulletCapsuleShape,
BulletDebugNode,
BulletPlaneShape,
BulletRigidBodyNode,
BulletSphereShape,
BulletWorld,
)
from game.nodes.camera import Camera
from game.nodes.collision imp... | src/pandaEditor/game/nodes/manager.py | from game.nodes.actor import Actor
from game.nodes.base import Base
from game.nodes.bullet import (
BulletBoxShape,
BulletCapsuleShape,
BulletDebugNode,
BulletPlaneShape,
BulletRigidBodyNode,
BulletSphereShape,
BulletWorld,
)
from game.nodes.camera import Camera
from game.nodes.collision imp... | 0.679817 | 0.499146 |
import h5py
import random
import numpy as np
class DataGenerator:
"""
Class for a generator that reads in data from the HDF5 file, one batch at
a time, converts it into the jigsaw, and then returns the data
"""
def __init__(self, conf, maxHammingSet):
"""
Explain
"""
... | legacy/example/DataLoader/DataGenerator.py | import h5py
import random
import numpy as np
class DataGenerator:
"""
Class for a generator that reads in data from the HDF5 file, one batch at
a time, converts it into the jigsaw, and then returns the data
"""
def __init__(self, conf, maxHammingSet):
"""
Explain
"""
... | 0.758063 | 0.381421 |
import os
import sys
import tempfile
from glob import glob
from copy import deepcopy
from collections import defaultdict
from typing import List, NamedTuple, Union, Dict, Any, Set, Tuple
import click
import pandas as pd
import numpy as np
from tabulate import tabulate
from pycocotools.coco import COCO
from pycocotools... | cli/pawls/commands/metric.py | import os
import sys
import tempfile
from glob import glob
from copy import deepcopy
from collections import defaultdict
from typing import List, NamedTuple, Union, Dict, Any, Set, Tuple
import click
import pandas as pd
import numpy as np
from tabulate import tabulate
from pycocotools.coco import COCO
from pycocotools... | 0.564819 | 0.300271 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import time
import subprocess
import re
from pykakasi import kakasi
from arduino_timer import Yukkuri
import grove_gesture_sensor
import ap_music
import ap_music_server_conf
MENU_IDLE = 0
MENU_PLAYING = 1
MENU_ONMENU = 2
class ApMenu:
MENU_TIMEOUT_SE... | audioserver/ap_menu.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import time
import subprocess
import re
from pykakasi import kakasi
from arduino_timer import Yukkuri
import grove_gesture_sensor
import ap_music
import ap_music_server_conf
MENU_IDLE = 0
MENU_PLAYING = 1
MENU_ONMENU = 2
class ApMenu:
MENU_TIMEOUT_SE... | 0.049314 | 0.082328 |
import tempfile
import unittest
import healpy as hp
import numpy as np
import jang.conversions
import jang.gw
import jang.limits
import jang.results
import jang.significance
import jang.stacking
from jang.neutrinos import BackgroundFixed, Detector
from jang.parameters import Parameters
class TestExa... | tests/test_examples.py |
import tempfile
import unittest
import healpy as hp
import numpy as np
import jang.conversions
import jang.gw
import jang.limits
import jang.results
import jang.significance
import jang.stacking
from jang.neutrinos import BackgroundFixed, Detector
from jang.parameters import Parameters
class TestExa... | 0.361277 | 0.23456 |
from __future__ import division
import torch
from torch import nn
import torch.nn.functional as F
from inverse_warp import inverse_warp2
import math
device = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
# compute photometric loss (with ssim) and geometry consistency loss
def comput... | loss_functions.py | from __future__ import division
import torch
from torch import nn
import torch.nn.functional as F
from inverse_warp import inverse_warp2
import math
device = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
# compute photometric loss (with ssim) and geometry consistency loss
def comput... | 0.836421 | 0.572364 |
from tkinter import *
from tkinter import messagebox
from .utils import *
from .data import Tawqeetex
gui = None
def generate_callback():
'''
This function executes when the user clicks on the Generate button
The user's input are stored and passed to the Tawqeetex object in order
to produce the prayer... | tawqeetex/gui.py | from tkinter import *
from tkinter import messagebox
from .utils import *
from .data import Tawqeetex
gui = None
def generate_callback():
'''
This function executes when the user clicks on the Generate button
The user's input are stored and passed to the Tawqeetex object in order
to produce the prayer... | 0.386416 | 0.114542 |
import logging
import queue
import socket
import threading
import traceback
import numpy
import pyflac
import select
import sounddevice as sd
import config
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
level=logging.INFO,
datefmt='%H:%M:%S')
class... | client.py | import logging
import queue
import socket
import threading
import traceback
import numpy
import pyflac
import select
import sounddevice as sd
import config
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
level=logging.INFO,
datefmt='%H:%M:%S')
class... | 0.545528 | 0.057785 |
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Layer
from tensorflow.python.keras.utils import conv_utils
class ExtendRGB(Layer):
"""
Extend the RGB channels
Input:
(batch, ..., 3)
Output:
(batch, ..., k*6)
Usage:
```python
... | models/advance/extendrgb.py |
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Layer
from tensorflow.python.keras.utils import conv_utils
class ExtendRGB(Layer):
"""
Extend the RGB channels
Input:
(batch, ..., 3)
Output:
(batch, ..., k*6)
Usage:
```python
... | 0.928498 | 0.796451 |
"""Test class for the connection module."""
# Third Party Imports
import pytest
# RAMSTK Package Imports
from ramstk.analyses.milhdbk217f import connection
ATTRIBUTES = {
"category_id": 8,
"subcategory_id": 1,
"environment_active_id": 2,
"type_id": 2,
"specification_id": 1,
"n_circuit_planes"... | tests/analyses/milhdbk217f/models/test_connection.py | """Test class for the connection module."""
# Third Party Imports
import pytest
# RAMSTK Package Imports
from ramstk.analyses.milhdbk217f import connection
ATTRIBUTES = {
"category_id": 8,
"subcategory_id": 1,
"environment_active_id": 2,
"type_id": 2,
"specification_id": 1,
"n_circuit_planes"... | 0.857082 | 0.52902 |
#Psudocode: Import Values, Check that thsoe values are valid, Generate the trendlines, plot them.
#The trendline generator must be smart and be able to create different types of trendlines, and their equations.
import math
import numpy as np
import matplotlib.pyplot as plt
def cfit(x,y,filename,flag,fitType):
... | CurveFitting/Curve_Fit.py |
#Psudocode: Import Values, Check that thsoe values are valid, Generate the trendlines, plot them.
#The trendline generator must be smart and be able to create different types of trendlines, and their equations.
import math
import numpy as np
import matplotlib.pyplot as plt
def cfit(x,y,filename,flag,fitType):
... | 0.58948 | 0.687603 |
from . import deepclustering_loss, pit_loss, \
l41_loss, pit_l41_loss,\
deepclustering_L1_loss, dist2mean_rat_loss,\
dist2mean_rat_squared_loss, intravar2centervar_rat_loss,\
dist2mean_rat_fracbins_loss, crossentropy_multi_loss,\
dist2mean_closest_rat_loss,direct_loss, dist2mean_epsilon_closest_rat_loss,\
dc_pit_... | nabu/neuralnetworks/loss_computers/loss_computer_factory.py | from . import deepclustering_loss, pit_loss, \
l41_loss, pit_l41_loss,\
deepclustering_L1_loss, dist2mean_rat_loss,\
dist2mean_rat_squared_loss, intravar2centervar_rat_loss,\
dist2mean_rat_fracbins_loss, crossentropy_multi_loss,\
dist2mean_closest_rat_loss,direct_loss, dist2mean_epsilon_closest_rat_loss,\
dc_pit_... | 0.848847 | 0.411939 |
from allennlp.models import load_archive
from allennlp.predictors import Predictor, SentenceTaggerPredictor
from allennlp_models.coref import CorefPredictor
from allennlp_models.nli import DecomposableAttentionPredictor
from allennlp_models.rc.bidaf import ReadingComprehensionPredictor
from allennlp_models.syntax impo... | allennlp_models/pretrained.py | from allennlp.models import load_archive
from allennlp.predictors import Predictor, SentenceTaggerPredictor
from allennlp_models.coref import CorefPredictor
from allennlp_models.nli import DecomposableAttentionPredictor
from allennlp_models.rc.bidaf import ReadingComprehensionPredictor
from allennlp_models.syntax impo... | 0.891717 | 0.411998 |
import codecs
import csv
import json
import re
import sys
import urllib.request
import geopandas
import geopy.distance
import pandas
def getListOfSites(network=None,verified_only=False):
"""Get all site records on DEIMS-SDR and return a list of DEIMS.IDs.
'network' must be the ID of a network. If provided, ... | deims.py | import codecs
import csv
import json
import re
import sys
import urllib.request
import geopandas
import geopy.distance
import pandas
def getListOfSites(network=None,verified_only=False):
"""Get all site records on DEIMS-SDR and return a list of DEIMS.IDs.
'network' must be the ID of a network. If provided, ... | 0.496094 | 0.339965 |
import sys
def domination_count_and_set(population, element):
# gives the domination count and dominating set of the element of the population
domination_count = 0
dominated_set = []
for chromosome in population:
dominated_sum = 0 # will equal number of objectives if chromosome is domina... | evolutionary/NSGAII.py |
import sys
def domination_count_and_set(population, element):
# gives the domination count and dominating set of the element of the population
domination_count = 0
dominated_set = []
for chromosome in population:
dominated_sum = 0 # will equal number of objectives if chromosome is domina... | 0.341802 | 0.515071 |
import falcon
import git
import os
from sqlalchemy.exc import SQLAlchemyError
from lockfile import LockFile
from db import session
import model
import util
class WaveDiff(object):
def on_post(self, req, resp, id):
try:
user = req.context['user']
if (not user.is_logged_in()) or (... | endpoint/admin/waveDiff.py | import falcon
import git
import os
from sqlalchemy.exc import SQLAlchemyError
from lockfile import LockFile
from db import session
import model
import util
class WaveDiff(object):
def on_post(self, req, resp, id):
try:
user = req.context['user']
if (not user.is_logged_in()) or (... | 0.25945 | 0.074433 |
from common import *
from tables import *
from scrape import Scraper
from utils.logger import *
class Miner:
""" Data Mining class.
"""
def __init__(self, read=False):
log_path = '.'.join(['datamining', __name__])
self.logger = logging.getLogger(log_path)
self.read = read
se... | datamining/dataminer.py | from common import *
from tables import *
from scrape import Scraper
from utils.logger import *
class Miner:
""" Data Mining class.
"""
def __init__(self, read=False):
log_path = '.'.join(['datamining', __name__])
self.logger = logging.getLogger(log_path)
self.read = read
se... | 0.624752 | 0.261229 |
from typing import List
import pytest
from fwordle.game.wordle_guess import WordleGuess, WordleLetterState
@pytest.fixture
def word_guess() -> WordleGuess:
wg = WordleGuess(1)
wg.append("a", "p1")
wg.append("r", "p1")
wg.append("i", "p1")
wg.append("s", "p1")
wg.append("e", "p1")
return ... | backend/tests/unit/game/wordle_guess_test.py | from typing import List
import pytest
from fwordle.game.wordle_guess import WordleGuess, WordleLetterState
@pytest.fixture
def word_guess() -> WordleGuess:
wg = WordleGuess(1)
wg.append("a", "p1")
wg.append("r", "p1")
wg.append("i", "p1")
wg.append("s", "p1")
wg.append("e", "p1")
return ... | 0.564699 | 0.38194 |
import json
from pprint import pformat
import click
import jira_scraper.jira_worker as scraper
import jira_template_commentor.util as jira_template_commentor_util
import logger
from common_util import project_dir_path
import os
import configparser
#constant
THIS_MODULE_DIRECTORY = os.path.join(project_dir_path, 'jira_... | jira_template_commentor/commands.py | import json
from pprint import pformat
import click
import jira_scraper.jira_worker as scraper
import jira_template_commentor.util as jira_template_commentor_util
import logger
from common_util import project_dir_path
import os
import configparser
#constant
THIS_MODULE_DIRECTORY = os.path.join(project_dir_path, 'jira_... | 0.316264 | 0.211396 |
import json
import sys
from pathlib import Path
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.forms import formset_factory
from django.http import HttpResponse, HttpResponseRedirect
from django.short... | expfactory_deploy/experiments/views.py | import json
import sys
from pathlib import Path
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.forms import formset_factory
from django.http import HttpResponse, HttpResponseRedirect
from django.short... | 0.372962 | 0.076649 |
import sys
import func_timeout
from sss.read_id_list import ReadIDList
from sss.se05x import Se05x
import sss.sss_api as apis
from .cli import se05x, pass_context, session_open, session_close, \
log_traceback, TIME_OUT
@se05x.command('reset', short_help='Reset SE05X')
@pass_context
def reset(cli_ctx):
"""
... | src/cli/cli_se05x.py | import sys
import func_timeout
from sss.read_id_list import ReadIDList
from sss.se05x import Se05x
import sss.sss_api as apis
from .cli import se05x, pass_context, session_open, session_close, \
log_traceback, TIME_OUT
@se05x.command('reset', short_help='Reset SE05X')
@pass_context
def reset(cli_ctx):
"""
... | 0.293202 | 0.166574 |
import logging
from bson import ObjectId
from .db import (
get_mailbox_collection,
get_message_collection,
get_message_fs,
get_message_fs_files_collection,
get_message_fs_chunks_collection,
)
def process_message(peer, mailfrom, rcpttos, data):
mailboxes = get_mailbox_collection()
messag... | www/flask_app/messages.py | import logging
from bson import ObjectId
from .db import (
get_mailbox_collection,
get_message_collection,
get_message_fs,
get_message_fs_files_collection,
get_message_fs_chunks_collection,
)
def process_message(peer, mailfrom, rcpttos, data):
mailboxes = get_mailbox_collection()
messag... | 0.157882 | 0.09886 |
from __future__ import print_function
import bluetooth_raspi
import bluez_service_consts
import dbus
import dbus.service
import dbus.mainloop.glib
import logging
import os
import raspi_bluez_client
# Libraries needed on raspberry pi. ImportError on
# Fizz can be ignored.
try:
from bluetooth import *
except ImportEr... | chameleond/utils/raspi_bluez_service.py | from __future__ import print_function
import bluetooth_raspi
import bluez_service_consts
import dbus
import dbus.service
import dbus.mainloop.glib
import logging
import os
import raspi_bluez_client
# Libraries needed on raspberry pi. ImportError on
# Fizz can be ignored.
try:
from bluetooth import *
except ImportEr... | 0.503174 | 0.06134 |
import pandas as pd
import numpy as np
from ast import literal_eval
import time
# Create a functions that label sentences with question marks, exlamation points and quotes
def question_mark_finder(sentence):
"""
Returns 1 if sentence contains question mark, 0 otherwise
"""
if "?" in sentence:
r... | src/features/build_punctuation_feature.py | import pandas as pd
import numpy as np
from ast import literal_eval
import time
# Create a functions that label sentences with question marks, exlamation points and quotes
def question_mark_finder(sentence):
"""
Returns 1 if sentence contains question mark, 0 otherwise
"""
if "?" in sentence:
r... | 0.634656 | 0.41478 |
class DynamicArray():
def __init__(self):
self.size = 0
self.capacity = 1
self.array = self._create_array(self.capacity)
def _create_array(self,length):
return [None] * length
def len(self):
return self.size
def get_capacity(se... | array.py | class DynamicArray():
def __init__(self):
self.size = 0
self.capacity = 1
self.array = self._create_array(self.capacity)
def _create_array(self,length):
return [None] * length
def len(self):
return self.size
def get_capacity(se... | 0.530966 | 0.259194 |
import json
import os
import shutil
import h5py
import numpy as np
from ..preprocessings.h5_to_memmap import h5_to_memmaps
from ..utils.utils import standardize_signals_durations
def generate_fake_hypno(transition_kernel, hypnogram_length, s_0=0):
generated_hypno = []
s_0 = np.array(s_0)
for i in range(... | dreem_learning_open/test/utils.py | import json
import os
import shutil
import h5py
import numpy as np
from ..preprocessings.h5_to_memmap import h5_to_memmaps
from ..utils.utils import standardize_signals_durations
def generate_fake_hypno(transition_kernel, hypnogram_length, s_0=0):
generated_hypno = []
s_0 = np.array(s_0)
for i in range(... | 0.33112 | 0.220689 |
import sys
import os
import re
import shutil
import argparse
from string import Template
KEYWORDS = ["CENTER_X", "CENTER_Y", "CENTER_Z", "RADIUS", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8"]
COORD = "{:>11.3f}{:>8.3f}{:>8.3f}"
CENTER = "{:.3f}"
DIR=os.path.dirname(os.path.abspath(__file__))
BOX=os.path.join(DIR,"b... | Analysis_tools/box.py | import sys
import os
import re
import shutil
import argparse
from string import Template
KEYWORDS = ["CENTER_X", "CENTER_Y", "CENTER_Z", "RADIUS", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8"]
COORD = "{:>11.3f}{:>8.3f}{:>8.3f}"
CENTER = "{:.3f}"
DIR=os.path.dirname(os.path.abspath(__file__))
BOX=os.path.join(DIR,"b... | 0.367043 | 0.185043 |
from watchdog.observers import Observer
from optimus.watchers.templates import TemplatesWatchEventHandler
from optimus.watchers.assets import AssetsWatchEventHandler
def watcher_interface(settings, views, build_env):
"""
Initialize observer for views and possible assets according to settings and build
en... | optimus/interfaces/watch.py | from watchdog.observers import Observer
from optimus.watchers.templates import TemplatesWatchEventHandler
from optimus.watchers.assets import AssetsWatchEventHandler
def watcher_interface(settings, views, build_env):
"""
Initialize observer for views and possible assets according to settings and build
en... | 0.827967 | 0.254636 |
import errno
import glob
import os
import subprocess
import sys
CONFIGS = {}
script_dir = os.path.dirname(__file__)
for config_file in sorted(glob.glob(os.path.join(script_dir, "*build_configs.py"))):
with open(config_file) as f:
config_file_content = f.read()
exec(config_file_content, globals(), ... | build.py |
import errno
import glob
import os
import subprocess
import sys
CONFIGS = {}
script_dir = os.path.dirname(__file__)
for config_file in sorted(glob.glob(os.path.join(script_dir, "*build_configs.py"))):
with open(config_file) as f:
config_file_content = f.read()
exec(config_file_content, globals(), ... | 0.116211 | 0.050682 |
import json
import re
import traceback
from functools import wraps
from flask import request
from flask_login import current_user
from flask_socketio import disconnect
from flask_socketio import emit
from flask_socketio import join_room
import flask_together.models as models
import flask_together.youtube ... | flask_together/events.py | import json
import re
import traceback
from functools import wraps
from flask import request
from flask_login import current_user
from flask_socketio import disconnect
from flask_socketio import emit
from flask_socketio import join_room
import flask_together.models as models
import flask_together.youtube ... | 0.17989 | 0.069479 |
from django.core.exceptions import PermissionDenied
from django.utils.dateparse import parse_datetime
from django.utils.translation import gettext_lazy as _
from django.views.generic import RedirectView
from apps.ota.models import DeviceVersionAttribute
from apps.property.views import *
from apps.report.views import B... | server/apps/physicaldevice/views.py | from django.core.exceptions import PermissionDenied
from django.utils.dateparse import parse_datetime
from django.utils.translation import gettext_lazy as _
from django.views.generic import RedirectView
from apps.ota.models import DeviceVersionAttribute
from apps.property.views import *
from apps.report.views import B... | 0.540196 | 0.076822 |
Here is an abstract class for neural network models based on Tensorflow.
If you use something different, ex. Pytorch, then write similar to this class, inherit it from
Trainable and Inferable interfaces and make a pull-request to deeppavlov.
"""
from abc import abstractmethod
from warnings import warn
import tensorfl... | deeppavlov/core/models/tf_model.py | Here is an abstract class for neural network models based on Tensorflow.
If you use something different, ex. Pytorch, then write similar to this class, inherit it from
Trainable and Inferable interfaces and make a pull-request to deeppavlov.
"""
from abc import abstractmethod
from warnings import warn
import tensorfl... | 0.912048 | 0.463809 |
from functools import lru_cache
from pathlib import Path
import re
from typing import Iterable, Set, Tuple, Union
import pandas as pd
from rapidfuzz import process, fuzz
DATADIR = Path(__file__).parent / 'data'
MASTER_PLAYERS = DATADIR / 'master_players.csv'
LEGAL_CHARS = re.compile(r'\W')
SUFFIXES = {'II', 'The Se... | nflnames/players.py |
from functools import lru_cache
from pathlib import Path
import re
from typing import Iterable, Set, Tuple, Union
import pandas as pd
from rapidfuzz import process, fuzz
DATADIR = Path(__file__).parent / 'data'
MASTER_PLAYERS = DATADIR / 'master_players.csv'
LEGAL_CHARS = re.compile(r'\W')
SUFFIXES = {'II', 'The Se... | 0.89783 | 0.346375 |
import pathlib
import numpy as np
import torch
import torch.utils.data
import torchvision
import torchvision.models
import torchvision.transforms
from sampler import ImbalancedDatasetSampler
import augmentations
from PIL import Image, ImageEnhance
import transforms
import cv2
import random
import torchvision.tra... | dataloader.py | import pathlib
import numpy as np
import torch
import torch.utils.data
import torchvision
import torchvision.models
import torchvision.transforms
from sampler import ImbalancedDatasetSampler
import augmentations
from PIL import Image, ImageEnhance
import transforms
import cv2
import random
import torchvision.tra... | 0.895188 | 0.44565 |
import numpy as np
def summary_stats(df, pct_vars=None, int_vars=None, float_vars=None, count=False):
"""
Generates a transposed df.describe() table where pct_vars are formatted with two
decimal percentages, int_vars are formatted with zero decimal places, and float_
vars are formatted with two decimal... | dero/summ.py | import numpy as np
def summary_stats(df, pct_vars=None, int_vars=None, float_vars=None, count=False):
"""
Generates a transposed df.describe() table where pct_vars are formatted with two
decimal percentages, int_vars are formatted with zero decimal places, and float_
vars are formatted with two decimal... | 0.621771 | 0.321766 |
import pytest
from sayn.utils.task_query import get_query
tasks = {
"task1": {"group": "group1", "tags": list()},
"task2": {"group": "group1", "tags": ["tag1"]},
"task3": {"group": "group2", "tags": ["tag1"]},
"task4": {"group": "group2", "tags": list()},
"task5": {"group": "group3", "tags": ["ta... | tests/test_task_query.py | import pytest
from sayn.utils.task_query import get_query
tasks = {
"task1": {"group": "group1", "tags": list()},
"task2": {"group": "group1", "tags": ["tag1"]},
"task3": {"group": "group2", "tags": ["tag1"]},
"task4": {"group": "group2", "tags": list()},
"task5": {"group": "group3", "tags": ["ta... | 0.374676 | 0.567008 |
import asyncio
from collections import OrderedDict
import concurrent
from contextlib import contextmanager
from functools import wraps
import functools
import itertools
import json
import logging
import math
from os import access
import os
from os.path import realpath, basename, dirname
from pathlib import Path
from th... | helios/plato/django/server/bpEndpoint.py | import asyncio
from collections import OrderedDict
import concurrent
from contextlib import contextmanager
from functools import wraps
import functools
import itertools
import json
import logging
import math
from os import access
import os
from os.path import realpath, basename, dirname
from pathlib import Path
from th... | 0.322099 | 0.176246 |
from typing import Union, List
import requests
from nexus.core.data.program import Manifest
from nexus.core.data.store import Patch, Signal, ProgramInstance
from nexus.core.database import Instance
from nexus.core.exc import NexusError
from nexus.core.handlers.api import APIHandler
from nexus.core.handlers.container ... | nexus/core/handlers/synapser.py | from typing import Union, List
import requests
from nexus.core.data.program import Manifest
from nexus.core.data.store import Patch, Signal, ProgramInstance
from nexus.core.database import Instance
from nexus.core.exc import NexusError
from nexus.core.handlers.api import APIHandler
from nexus.core.handlers.container ... | 0.732305 | 0.143397 |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
... | shop/models.py | from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
... | 0.587233 | 0.111676 |
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
def run_varying_option_test (option) :
global command
command += testshade("-g 512 512 -center"+
" -layer src vary_... | testsuite/noise-gabor-reg/run.py |
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
def run_varying_option_test (option) :
global command
command += testshade("-g 512 512 -center"+
" -layer src vary_... | 0.512205 | 0.177312 |
import dash
import dash_core_components as dcc
import dash_html_components as html
import os
from datetime import datetime
from utilities.WordWorks import WordWorks as wordings
from sqlalchemy import create_engine
import pandas as pd
time_start = datetime.now()
print(f'Starting At: {time_start}\n\n')
engine = create... | app_sql.py | import dash
import dash_core_components as dcc
import dash_html_components as html
import os
from datetime import datetime
from utilities.WordWorks import WordWorks as wordings
from sqlalchemy import create_engine
import pandas as pd
time_start = datetime.now()
print(f'Starting At: {time_start}\n\n')
engine = create... | 0.047958 | 0.096748 |
import argparse
import os
import shutil
import sys
import urllib.request
from zipfile import ZipFile
DATASET_URLS = {
'train': 'http://images.cocodataset.org/zips/train2017.zip',
'val': 'http://images.cocodataset.org/zips/val2017.zip',
'test': 'http://images.cocodataset.org/zips/test2017.zip'
}
parser = a... | data/coco/download_coco.py | import argparse
import os
import shutil
import sys
import urllib.request
from zipfile import ZipFile
DATASET_URLS = {
'train': 'http://images.cocodataset.org/zips/train2017.zip',
'val': 'http://images.cocodataset.org/zips/val2017.zip',
'test': 'http://images.cocodataset.org/zips/test2017.zip'
}
parser = a... | 0.325735 | 0.214897 |
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell cop... | estimations_data.py |
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell cop... | 0.456894 | 0.14259 |
import pytest
from addons.osfstorage.models import Region
from admin.institutional_storage_quota_control import views
from django.test import RequestFactory
from django.urls import reverse
from nose import tools as nt
from osf.models import UserQuota
from admin_tests.utilities import setup_view
from osf_tests.factories... | admin_tests/institutional_storage_quota_control/test_views.py | import pytest
from addons.osfstorage.models import Region
from admin.institutional_storage_quota_control import views
from django.test import RequestFactory
from django.urls import reverse
from nose import tools as nt
from osf.models import UserQuota
from admin_tests.utilities import setup_view
from osf_tests.factories... | 0.477554 | 0.234472 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from cs3.storage.registry.v1beta1 import registry_api_pb2 as cs3_dot_storage_dot_registry_dot_v1beta1_dot_registry__api__pb2
class RegistryAPIStub(object):
"""Storage Registry API
The Storage Registry API is meant to as ... | cs3/storage/registry/v1beta1/registry_api_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from cs3.storage.registry.v1beta1 import registry_api_pb2 as cs3_dot_storage_dot_registry_dot_v1beta1_dot_registry__api__pb2
class RegistryAPIStub(object):
"""Storage Registry API
The Storage Registry API is meant to as ... | 0.695545 | 0.151028 |
import unittest
from selenium import webdriver
import settings
class SearchText(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
#navigate to application home page
self.driver.get("https://my... | test.py | import unittest
from selenium import webdriver
import settings
class SearchText(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
#navigate to application home page
self.driver.get("https://my... | 0.148726 | 0.12768 |
import os
PURPLE_DESCRIPTION = "A collection of various utilities called Purple Tools. Call 'purple.py <positional argument> -h' for additional help, where <positional argument> is one of the arguments from the positional argument list below."
PARSER_IDENTIFIER_NAME = "which"
TEST_COMMAND_DESCRIPTION = "test command... | scripts/utils/constants.py | import os
PURPLE_DESCRIPTION = "A collection of various utilities called Purple Tools. Call 'purple.py <positional argument> -h' for additional help, where <positional argument> is one of the arguments from the positional argument list below."
PARSER_IDENTIFIER_NAME = "which"
TEST_COMMAND_DESCRIPTION = "test command... | 0.503906 | 0.323166 |
import autodisc as ad
import ipywidgets
class ExperimentRepetitionLoaderWidget(ipywidgets.Box):
@staticmethod
def get_default_gui_config():
default_config = ad.Config()
default_config.box_layout = ad.Config()
default_config.box_layout.display = 'stretch'
default_config.box_lay... | autodisc/autodisc/gui/jupyter/experimentrepetitionloaderwidget.py | import autodisc as ad
import ipywidgets
class ExperimentRepetitionLoaderWidget(ipywidgets.Box):
@staticmethod
def get_default_gui_config():
default_config = ad.Config()
default_config.box_layout = ad.Config()
default_config.box_layout.display = 'stretch'
default_config.box_lay... | 0.580233 | 0.068694 |
from __future__ import absolute_import
import pprint
import json
import bigml.api
from bigml.constants import RENAMED_RESOURCES
from bigml.resourcehandler import get_resource_type
INDENT = 4 * " "
def sort_lists(dict_structure):
"""Sorts the lists in a dict_structure
"""
if dict_structure is not None ... | bigmler/reify/restcall.py | from __future__ import absolute_import
import pprint
import json
import bigml.api
from bigml.constants import RENAMED_RESOURCES
from bigml.resourcehandler import get_resource_type
INDENT = 4 * " "
def sort_lists(dict_structure):
"""Sorts the lists in a dict_structure
"""
if dict_structure is not None ... | 0.630344 | 0.137214 |
custom_component_base_connections_template = '''
add_connection pll_using_AD1939_MCLK.outclk0 component_name_0.clock
add_connection clock_name.clk_reset component_name_0.reset
add_connection axi_master_name component_name_0.avalon_slave
set_connection_parameter_value axi_master_name/component_name_0.avalon_slave arbit... | quartus/quartus_templates.py |
custom_component_base_connections_template = '''
add_connection pll_using_AD1939_MCLK.outclk0 component_name_0.clock
add_connection clock_name.clk_reset component_name_0.reset
add_connection axi_master_name component_name_0.avalon_slave
set_connection_parameter_value axi_master_name/component_name_0.avalon_slave arbit... | 0.695441 | 0.205575 |
from io import BytesIO
from behave import given, when, then, use_step_matcher
from PIL import Image, ImageColor
from light_character.light_character import save_characteristic_as_image
use_step_matcher('re')
@when(u'I request an image with the characteristic (?P<characteristic>.+)')
def request_image(context, char... | features/steps/__init__.py | from io import BytesIO
from behave import given, when, then, use_step_matcher
from PIL import Image, ImageColor
from light_character.light_character import save_characteristic_as_image
use_step_matcher('re')
@when(u'I request an image with the characteristic (?P<characteristic>.+)')
def request_image(context, char... | 0.734024 | 0.375678 |
import pandas as pd
import geopandas as gpd
import folium
from shapely.geometry import Point
from folium import plugins
from auth import spreadsheet_service
def create():
range_name = 'Sheet1!A1:G1000'
spreadsheet_id = '1zB9WAxgGIbhyWlLpj6g1Fhnke1Rrf5EQmduipE1pq34'
result = spreadsheet_service.spreadsheets... | map.py | import pandas as pd
import geopandas as gpd
import folium
from shapely.geometry import Point
from folium import plugins
from auth import spreadsheet_service
def create():
range_name = 'Sheet1!A1:G1000'
spreadsheet_id = '1zB9WAxgGIbhyWlLpj6g1Fhnke1Rrf5EQmduipE1pq34'
result = spreadsheet_service.spreadsheets... | 0.213131 | 0.485783 |
from conans import ConanFile, CMake, tools
import os
import shutil
class gRPCConan(ConanFile):
name = "gRPC"
version = "1.1.0-dev" # Nov 8
folder = "grpc-31606bdb34474d8728350ad45baf0e91b590b041"
url = "https://github.com/a_teammate/conan-grpc.git"
license = "BSD-3Clause"
requires = "zlib/1.2.... | conanfile.py | from conans import ConanFile, CMake, tools
import os
import shutil
class gRPCConan(ConanFile):
name = "gRPC"
version = "1.1.0-dev" # Nov 8
folder = "grpc-31606bdb34474d8728350ad45baf0e91b590b041"
url = "https://github.com/a_teammate/conan-grpc.git"
license = "BSD-3Clause"
requires = "zlib/1.2.... | 0.223377 | 0.071332 |
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from typing import Union
from botocore.paginate import Paginator
from datetime import datetime
from botocore.waiter import Waiter
from typing import List
class Client(BaseClient):
def allocate_static_ip(self, staticIpName: ... | boto3_type_annotations/boto3_type_annotations/lightsail/client.py | from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from typing import Union
from botocore.paginate import Paginator
from datetime import datetime
from botocore.waiter import Waiter
from typing import List
class Client(BaseClient):
def allocate_static_ip(self, staticIpName: ... | 0.786787 | 0.280561 |
from abc import abstractmethod
from typing import Optional
from PySDDP.dessem.script.templates.arquivo_entrada import ArquivoEntrada
class InfofcfTemplate(ArquivoEntrada):
"""
Classe que contem todos os elementos comuns a qualquer versao do arquivo Infofcf do Dessem.
Esta classe tem como intuito fornecer... | PySDDP/dessem/script/templates/infofcf.py | from abc import abstractmethod
from typing import Optional
from PySDDP.dessem.script.templates.arquivo_entrada import ArquivoEntrada
class InfofcfTemplate(ArquivoEntrada):
"""
Classe que contem todos os elementos comuns a qualquer versao do arquivo Infofcf do Dessem.
Esta classe tem como intuito fornecer... | 0.759493 | 0.326325 |
import encrypted_fields.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("profiles", "0033_auto_20201113_1515"),
]
operations = [
migrations.AlterField(
model_name="verifiedpersonalinformation",
name="email",
... | profiles/migrations/0034_add_help_texts_to_fields__noop.py |
import encrypted_fields.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("profiles", "0033_auto_20201113_1515"),
]
operations = [
migrations.AlterField(
model_name="verifiedpersonalinformation",
name="email",
... | 0.573081 | 0.199133 |
from monitors.views import MonitorDashboard, AddIndicator, DomainMonitor, DeleteIndicator
from profiles.models import Profile
from django.test import TestCase, RequestFactory
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
im... | unit_tests/test_monitor_views.py | from monitors.views import MonitorDashboard, AddIndicator, DomainMonitor, DeleteIndicator
from profiles.models import Profile
from django.test import TestCase, RequestFactory
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
im... | 0.656878 | 0.294177 |
import six
import numpy as np
from monty.json import MSONable
from ruamel.yaml import safe_dump
from propnet import logger, ureg
from sympy.parsing.sympy_parser import parse_expr
import sympy as sp
# TODO: This could be split into separate classes
# or a base class + subclasses for symbols with
# units... | propnet/core/symbols.py |
import six
import numpy as np
from monty.json import MSONable
from ruamel.yaml import safe_dump
from propnet import logger, ureg
from sympy.parsing.sympy_parser import parse_expr
import sympy as sp
# TODO: This could be split into separate classes
# or a base class + subclasses for symbols with
# units... | 0.466603 | 0.412353 |
import os
from nacl import secret, utils
from hashlib import sha256
from random import randrange
from src.EncryptCore.sources.exceptions import EncryptionKeyError, CryptoError
from src.EncryptCore.sources.Utilities import generateKey, generateCipherMod, unbundleSizeAndRest, getModFromCipher
from src.models.User impo... | src/EncryptCore/sources/FileEncryptor.py | import os
from nacl import secret, utils
from hashlib import sha256
from random import randrange
from src.EncryptCore.sources.exceptions import EncryptionKeyError, CryptoError
from src.EncryptCore.sources.Utilities import generateKey, generateCipherMod, unbundleSizeAndRest, getModFromCipher
from src.models.User impo... | 0.482673 | 0.312285 |
from pathlib import Path
import depthai as dai
import cv2
import sys
# Importing from parent folder
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # move to parent path
from utils.compute import updateSpatialCalculatorConfig
from utils.draw import drawROI, displayFPS
from utils.OakRunner import OakRunner... | V-generalization/examples/mono_neural_inference/nn_coronamask_depth_v2.py | from pathlib import Path
import depthai as dai
import cv2
import sys
# Importing from parent folder
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # move to parent path
from utils.compute import updateSpatialCalculatorConfig
from utils.draw import drawROI, displayFPS
from utils.OakRunner import OakRunner... | 0.538255 | 0.24899 |
from django.contrib.gis.db import models
class CptCadastreScdb(models.Model):
"""This is an auto-generated Django model.
"""
objectid = models.AutoField(primary_key=True)
cad_pin = models.IntegerField(blank=True, null=True)
cad_usage_codes = models.CharField(max_length=12, blank=True, null=True)
... | cddp/models.py | from django.contrib.gis.db import models
class CptCadastreScdb(models.Model):
"""This is an auto-generated Django model.
"""
objectid = models.AutoField(primary_key=True)
cad_pin = models.IntegerField(blank=True, null=True)
cad_usage_codes = models.CharField(max_length=12, blank=True, null=True)
... | 0.598664 | 0.287668 |
import random
from tkinter import *
import pandas
BACKGROUND_COLOR = "#B1DDC6"
words_to_learn = {}
current_card = {}
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
original_data = pandas.read_csv("data/french_words.csv")
words_to_learn = original_data.to_dict(orient="recor... | day 31 (Flash Cards Game)/main.py | import random
from tkinter import *
import pandas
BACKGROUND_COLOR = "#B1DDC6"
words_to_learn = {}
current_card = {}
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
original_data = pandas.read_csv("data/french_words.csv")
words_to_learn = original_data.to_dict(orient="recor... | 0.216923 | 0.109539 |
from web3 import Web3
from wrkchain import constants
from wrkchain.documentation.sections.doc_section import DocSection
class SectionSetup(DocSection):
def __init__(self, section_number, title, network, oracle_addresses,
wrkchain_id, mainchain_rpc_host, mainchain_rpc_port,
mainc... | sdk/wrkchain/documentation/sections/section_setup.py | from web3 import Web3
from wrkchain import constants
from wrkchain.documentation.sections.doc_section import DocSection
class SectionSetup(DocSection):
def __init__(self, section_number, title, network, oracle_addresses,
wrkchain_id, mainchain_rpc_host, mainchain_rpc_port,
mainc... | 0.558447 | 0.077622 |
from vpos.vpos import Vpos
import time
class TestVpos:
# Payments
## Positives
def test_should_create_a_new_payment_request_transaction(self):
merchant = Vpos()
payment = merchant.new_payment('900000000', '123.45')
request_id = payment.get('location')[17:]
response = merchan... | vpos/test/test_vpos.py | from vpos.vpos import Vpos
import time
class TestVpos:
# Payments
## Positives
def test_should_create_a_new_payment_request_transaction(self):
merchant = Vpos()
payment = merchant.new_payment('900000000', '123.45')
request_id = payment.get('location')[17:]
response = merchan... | 0.481698 | 0.435781 |
import time
from typing import Optional, Set
from prometheus_client import Counter, Gauge, Histogram # type: ignore
from starlette.middleware.base import RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp
from fast_tools.base im... | fast_tools/exporter/middleware.py | import time
from typing import Optional, Set
from prometheus_client import Counter, Gauge, Histogram # type: ignore
from starlette.middleware.base import RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp
from fast_tools.base im... | 0.799677 | 0.082033 |
import random
import requests
import datetime
from bot.utils.answers import *
from bot.utils.decorators import run_async
from bot.utils.text_converter import convert_text
class Bot:
def __init__(self, token):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
self.now = datetim... | bot/telegram_bot.py | import random
import requests
import datetime
from bot.utils.answers import *
from bot.utils.decorators import run_async
from bot.utils.text_converter import convert_text
class Bot:
def __init__(self, token):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
self.now = datetim... | 0.163612 | 0.093969 |
import sys, os, argparse
import utils
import numpy as np
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Extract images with valid range (between -99 and 99 ).')
parser.add_argument('--root', dest='root', help='Path of AFLW2000')
args = parser.parse_args()
... | code/extract_valid_files.py | import sys, os, argparse
import utils
import numpy as np
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Extract images with valid range (between -99 and 99 ).')
parser.add_argument('--root', dest='root', help='Path of AFLW2000')
args = parser.parse_args()
... | 0.271735 | 0.221709 |
import json
import numpy as np
from typing import Dict, List, Any
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def load_dataset(file_path: str = "dataset.json") -> Dict[str, Any]:
with open(file_path, "r") as f:
dataset = json.load(f)
return dataset
def ma... | text_classification/build_text_model.py | import json
import numpy as np
from typing import Dict, List, Any
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def load_dataset(file_path: str = "dataset.json") -> Dict[str, Any]:
with open(file_path, "r") as f:
dataset = json.load(f)
return dataset
def ma... | 0.896754 | 0.510252 |
import os
import sys
import argparse
sys.path.append(os.path.join(os.environ["CONTECH_HOME"], "scripts"))
import util
import subprocess
import shutil
import tempfile
def main(arg):
# TODO: usage should be based on argparse
if (len(arg)) == 1:
print "Usage: {0} input\n".format(arg[0])
exit()
... | backend/DynamicAnalysis/run.py |
import os
import sys
import argparse
sys.path.append(os.path.join(os.environ["CONTECH_HOME"], "scripts"))
import util
import subprocess
import shutil
import tempfile
def main(arg):
# TODO: usage should be based on argparse
if (len(arg)) == 1:
print "Usage: {0} input\n".format(arg[0])
exit()
... | 0.191252 | 0.109277 |
import pyautogui
from time import time, sleep
from typeguard import typechecked
from defined import Coord, RGB, Ratio, Owner, Dict
from data import uData
from adb import adb
@typechecked
class Object():
def __init__(self,
coord_name: str,
rgb_kname: str,
ratio: R... | src/object.py | import pyautogui
from time import time, sleep
from typeguard import typechecked
from defined import Coord, RGB, Ratio, Owner, Dict
from data import uData
from adb import adb
@typechecked
class Object():
def __init__(self,
coord_name: str,
rgb_kname: str,
ratio: R... | 0.577614 | 0.173673 |
import csv
import os
# Custom Imports.
class Lookup:
"""
The Lookup class is a concrete class that can ingest environmental
parameters to generate and read lookup tables for models that may take large
processing loads to compute. The expected output lookup tables are in CSV
format, and can be ind... | ArraySimulation/PVSource/PVCell/Lookup.py | import csv
import os
# Custom Imports.
class Lookup:
"""
The Lookup class is a concrete class that can ingest environmental
parameters to generate and read lookup tables for models that may take large
processing loads to compute. The expected output lookup tables are in CSV
format, and can be ind... | 0.776877 | 0.71464 |