code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from sklearn.model_selection import train_test_split
# Code starts here
data = pd.read_csv(path)
X = data.drop(columns=['customer.id','paid.back.loan'])
y = data['paid.back.loan']
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0... | Decision-Tree-Loan-Defaulters/code.py |
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from sklearn.model_selection import train_test_split
# Code starts here
data = pd.read_csv(path)
X = data.drop(columns=['customer.id','paid.back.loan'])
y = data['paid.back.loan']
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0... | 0.289472 | 0.325494 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=Tru... | blog/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=Tru... | 0.598195 | 0.165694 |
from spy_state import *
import sys, re
# All these calls are based on the print statements in legion_logging.h
prefix = "\[[0-9]+ - [0-9a-f]+\] \{\w+\}\{legion_spy\}: "
# Calls for the shape of region trees
top_index_pat = re.compile(prefix+"Index Space (?P<uid>[0-9]+)")
index_part_pat = re.compil... | tools/spy_parser.py |
from spy_state import *
import sys, re
# All these calls are based on the print statements in legion_logging.h
prefix = "\[[0-9]+ - [0-9a-f]+\] \{\w+\}\{legion_spy\}: "
# Calls for the shape of region trees
top_index_pat = re.compile(prefix+"Index Space (?P<uid>[0-9]+)")
index_part_pat = re.compil... | 0.149811 | 0.344526 |
from logging.config import dictConfig
from reports.core import BaseBidsUtility, NEW_ALG_DATE, CHANGE_2019_DATE
from reports.helpers import (
thresholds_headers,
get_arguments_parser,
read_config
)
from reports.helpers import DEFAULT_TIMEZONE, DEFAULT_MODE
class InvoicesUtility(BaseBidsUtility):
numbe... | reports/utilities/invoices.py | from logging.config import dictConfig
from reports.core import BaseBidsUtility, NEW_ALG_DATE, CHANGE_2019_DATE
from reports.helpers import (
thresholds_headers,
get_arguments_parser,
read_config
)
from reports.helpers import DEFAULT_TIMEZONE, DEFAULT_MODE
class InvoicesUtility(BaseBidsUtility):
numbe... | 0.645567 | 0.168549 |
import os
import pandas as pd
import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.spatial import distance
from IPython.display import clear_output
from itertools import combinations
import multiprocessing as mp
import logging
import argparse
import time
'''
This script will compare action se... | analysis/ool2020/get_transformed_action_distance.py | import os
import pandas as pd
import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.spatial import distance
from IPython.display import clear_output
from itertools import combinations
import multiprocessing as mp
import logging
import argparse
import time
'''
This script will compare action se... | 0.612657 | 0.400632 |
from typing import Optional
import starstruct
from starstruct.element import register, Element
from starstruct.modes import Mode
class Escapor:
def __init__(self, start=None, separator=None, end=None, opts=None):
self._start = start
self._separator = separator
self._end = end
se... | starstruct/elementescaped.py |
from typing import Optional
import starstruct
from starstruct.element import register, Element
from starstruct.modes import Mode
class Escapor:
def __init__(self, start=None, separator=None, end=None, opts=None):
self._start = start
self._separator = separator
self._end = end
se... | 0.84317 | 0.384103 |
import asyncio
import time as ttime
from bluesky_queueserver.manager.task_results import TaskResults
def test_TaskResults_update_uid():
"""
TaskResults: Test that task result UID is updated.
"""
async def testing():
tr = TaskResults()
uid = tr.task_results_uid
assert isinsta... | bluesky_queueserver/manager/tests/test_task_results.py | import asyncio
import time as ttime
from bluesky_queueserver.manager.task_results import TaskResults
def test_TaskResults_update_uid():
"""
TaskResults: Test that task result UID is updated.
"""
async def testing():
tr = TaskResults()
uid = tr.task_results_uid
assert isinsta... | 0.655446 | 0.581095 |
from datetime import datetime
import boto3
from botocore.client import ClientError
import requests
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from saleor.product.models import ProductImage
class Command(BaseCommand):
version = "1.0"
def add_arguments(... | saleor/core/management/commands/remove_background.py | from datetime import datetime
import boto3
from botocore.client import ClientError
import requests
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from saleor.product.models import ProductImage
class Command(BaseCommand):
version = "1.0"
def add_arguments(... | 0.494385 | 0.082254 |
import sqlalchemy
from flask_taxonomies.constants import INCLUDE_DELETED, INCLUDE_DESCENDANTS, \
INCLUDE_DESCENDANTS_COUNT, INCLUDE_STATUS, INCLUDE_SELF
from flask_taxonomies.models import TaxonomyTerm, TermStatusEnum, Representation
from flask_taxonomies.proxies import current_flask_taxonomies
from flask_taxonomie... | oarepo_taxonomies/utils.py | import sqlalchemy
from flask_taxonomies.constants import INCLUDE_DELETED, INCLUDE_DESCENDANTS, \
INCLUDE_DESCENDANTS_COUNT, INCLUDE_STATUS, INCLUDE_SELF
from flask_taxonomies.models import TaxonomyTerm, TermStatusEnum, Representation
from flask_taxonomies.proxies import current_flask_taxonomies
from flask_taxonomie... | 0.558327 | 0.133754 |
import numpy as np
from datetime import datetime, timedelta
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import sys
from tools_TC202010 import read_score
def main( top='', stime=datetime(2020, 9, 1, 0 ), etime=datetime(2020, 9, 1, 0) ):
time = stime
while time < etime:
data_ = ... | src/nobs_tseris.py | import numpy as np
from datetime import datetime, timedelta
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import sys
from tools_TC202010 import read_score
def main( top='', stime=datetime(2020, 9, 1, 0 ), etime=datetime(2020, 9, 1, 0) ):
time = stime
while time < etime:
data_ = ... | 0.161155 | 0.399519 |
import numpy as np
import pytest
import opexebo
from opexebo.general import accumulate_spatial as func
print("=== tests_general_accumulate_spatial ===")
def test_invalid_inputs():
# No `arena_size` keyword
with pytest.raises(TypeError):
pos = np.random.rand(100)
func(pos)
# Misdefined bi... | opexebo/tests/test_general/test_accumulateSpatial.py | import numpy as np
import pytest
import opexebo
from opexebo.general import accumulate_spatial as func
print("=== tests_general_accumulate_spatial ===")
def test_invalid_inputs():
# No `arena_size` keyword
with pytest.raises(TypeError):
pos = np.random.rand(100)
func(pos)
# Misdefined bi... | 0.402862 | 0.746809 |
import os
import platform
import subprocess
def _pv_linux_machine(machine):
if machine == 'x86_64':
return machine
cpu_info = subprocess.check_output(['cat', '/proc/cpuinfo']).decode()
hardware_info = [x for x in cpu_info.split('\n') if 'Hardware' in x][0]
model_info = [x for x in cpu_info.s... | resources/util/python/util.py | import os
import platform
import subprocess
def _pv_linux_machine(machine):
if machine == 'x86_64':
return machine
cpu_info = subprocess.check_output(['cat', '/proc/cpuinfo']).decode()
hardware_info = [x for x in cpu_info.split('\n') if 'Hardware' in x][0]
model_info = [x for x in cpu_info.s... | 0.312475 | 0.088072 |
class Day4:
def part1(self):
min = 356261
max = 846303
password = <PASSWORD>
possibleCount = 0
while password <= max:
passwordText = str(password)
isPossible = False
stringIndex = 0
while stringIndex < len(str(max)) - 1:
... | AOC2019/Day4.py | class Day4:
def part1(self):
min = 356261
max = 846303
password = <PASSWORD>
possibleCount = 0
while password <= max:
passwordText = str(password)
isPossible = False
stringIndex = 0
while stringIndex < len(str(max)) - 1:
... | 0.132739 | 0.395893 |
import numpy as np
from models.model import BaseModel
from tqdm.autonotebook import tqdm
from xgboost import XGBRegressor
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
class Boosting(BaseModel):
def __init__ (self, generator, cfg, **kwargs):
super().__ini... | models/boosting.py | import numpy as np
from models.model import BaseModel
from tqdm.autonotebook import tqdm
from xgboost import XGBRegressor
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
class Boosting(BaseModel):
def __init__ (self, generator, cfg, **kwargs):
super().__ini... | 0.463687 | 0.220091 |
import numpy as np
import matplotlib.pyplot as plt
def df_to_matrix(df, quantity, replicate_identifier):
""" Construct a matrix from a Dataframe for a given vector-valued
quantity in which each vector replicate is labeled by a unique
replicate identifier.
Parameters
----------
df : DataFrame
... | dlsmicro/backend/plot_tools.py | import numpy as np
import matplotlib.pyplot as plt
def df_to_matrix(df, quantity, replicate_identifier):
""" Construct a matrix from a Dataframe for a given vector-valued
quantity in which each vector replicate is labeled by a unique
replicate identifier.
Parameters
----------
df : DataFrame
... | 0.895065 | 0.699408 |
import time
import grove_rgb_lcd
sleep = time.sleep
setText = grove_rgb_lcd.setText
setText_norefresh = grove_rgb_lcd.setText_norefresh
setRGB = grove_rgb_lcd.setRGB
class LCDControl(object):
def __init__(self, red = 100, green = 100, blue = 100):
#Set default background colour
self.red = red
... | LCD_Screen_Control.py |
import time
import grove_rgb_lcd
sleep = time.sleep
setText = grove_rgb_lcd.setText
setText_norefresh = grove_rgb_lcd.setText_norefresh
setRGB = grove_rgb_lcd.setRGB
class LCDControl(object):
def __init__(self, red = 100, green = 100, blue = 100):
#Set default background colour
self.red = red
... | 0.344443 | 0.11737 |
import os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
try:
import keyring
except:
keyring = None
class GUI(object):
UI_DATA_PATH = os.path.join(os.path.dirname(__file__), "..", "ui")
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_fi... | mountn/gui.py | import os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
try:
import keyring
except:
keyring = None
class GUI(object):
UI_DATA_PATH = os.path.join(os.path.dirname(__file__), "..", "ui")
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_fi... | 0.291787 | 0.071494 |
import asyncio
from typing import Union
import discord
from redbot.core import commands
from redbot.core.utils.chat_formatting import box
class SupportCommands(commands.Cog):
@commands.group(name="supportset", aliases=["sset"])
@commands.guild_only()
@commands.admin()
async def support(self, ctx: com... | support/commands.py | import asyncio
from typing import Union
import discord
from redbot.core import commands
from redbot.core.utils.chat_formatting import box
class SupportCommands(commands.Cog):
@commands.group(name="supportset", aliases=["sset"])
@commands.guild_only()
@commands.admin()
async def support(self, ctx: com... | 0.680772 | 0.073863 |
import os
import sys
import argparse
try:
assert (sys.version_info[0] == 3)
except:
sys.stderr.write("Please use Python-3.4 to run this program. Exiting now ...\n");
sys.exit(1)
def create_directory(directory):
if not os.path.isdir(directory):
os.system('mkdir %s' % directory)
else:
... | runFeatureTests.py | import os
import sys
import argparse
try:
assert (sys.version_info[0] == 3)
except:
sys.stderr.write("Please use Python-3.4 to run this program. Exiting now ...\n");
sys.exit(1)
def create_directory(directory):
if not os.path.isdir(directory):
os.system('mkdir %s' % directory)
else:
... | 0.16043 | 0.148386 |
"""Benchmark for the dataflow GGNN pipeline."""
import contextlib
import os
import pathlib
import sys
import tempfile
import warnings
from sklearn.exceptions import UndefinedMetricWarning
from tqdm import tqdm
from labm8.py import app
from labm8.py import ppar
from labm8.py import prof
from programl.models.ggnn.ggnn ... | programl/test/benchmarks/benchmark_dataflow_ggnn.py | """Benchmark for the dataflow GGNN pipeline."""
import contextlib
import os
import pathlib
import sys
import tempfile
import warnings
from sklearn.exceptions import UndefinedMetricWarning
from tqdm import tqdm
from labm8.py import app
from labm8.py import ppar
from labm8.py import prof
from programl.models.ggnn.ggnn ... | 0.59561 | 0.280244 |
import torch
from torch import nn, transpose
from torch.autograd import Variable
from torch.nn import functional as F
class FCNet(nn.Module):
def __init__(self, shape, task_num):
super(FCNet, self).__init__()
print('Intializing FCNet...')
self.inp_len = shape[1]
self.inp_size = sha... | DIGDriver/region_model/nets/cnn_predictors.py | import torch
from torch import nn, transpose
from torch.autograd import Variable
from torch.nn import functional as F
class FCNet(nn.Module):
def __init__(self, shape, task_num):
super(FCNet, self).__init__()
print('Intializing FCNet...')
self.inp_len = shape[1]
self.inp_size = sha... | 0.934043 | 0.383641 |
import os
import json
import logging
logger = logging.getLogger('amr_postprocessing')
def get_default_amr():
default = '(w / want-01 :ARG0 (b / boy) :ARG1 (g / go-01 :ARG0 b))'
return default
def write_to_file(lst, file_new):
with open(file_new, 'w', encoding='utf-8') as out_f:
for line in lst... | amr_seq2seq/utils/amr_utils.py | import os
import json
import logging
logger = logging.getLogger('amr_postprocessing')
def get_default_amr():
default = '(w / want-01 :ARG0 (b / boy) :ARG1 (g / go-01 :ARG0 b))'
return default
def write_to_file(lst, file_new):
with open(file_new, 'w', encoding='utf-8') as out_f:
for line in lst... | 0.40251 | 0.152158 |
from model import *
from utils import *
from evaluate import *
from dataloader import *
def load_data(args):
data = dataloader()
batch = []
cti = load_tkn_to_idx(args[1]) # char_to_idx
wti = load_tkn_to_idx(args[2]) # word_to_idx
itt = load_idx_to_tkn(args[3]) # idx_to_tkn
print("loading %s..."... | lstm/train.py | from model import *
from utils import *
from evaluate import *
from dataloader import *
def load_data(args):
data = dataloader()
batch = []
cti = load_tkn_to_idx(args[1]) # char_to_idx
wti = load_tkn_to_idx(args[2]) # word_to_idx
itt = load_idx_to_tkn(args[3]) # idx_to_tkn
print("loading %s..."... | 0.435661 | 0.351311 |
__author__ = 'wangqiang'
'''
基于多线程实现1对多的websocket
一个server,多个client
'''
import websockets
import threading
import asyncio
import time
import uuid
import random
def start_server(host, port):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(websockets.serve(server, host... | open_modules/about_websocket_threading.py | __author__ = 'wangqiang'
'''
基于多线程实现1对多的websocket
一个server,多个client
'''
import websockets
import threading
import asyncio
import time
import uuid
import random
def start_server(host, port):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(websockets.serve(server, host... | 0.21158 | 0.105579 |
ACTIVE_DETECTORS=('H2','H1','AX','L1','L2', 'CDD')
#FITS=('Ar41:linear','Ar40:linear', 'Ar39:parabolic','Ar38:parabolic','Ar37:parabolic','Ar36:parabolic')
def main():
#simulate CO2 analysis
#open('T')
#sleep(5)
#close('L')
#display information with info(msg)
info('unknown measurement scri... | docs/user_guide/operation/scripts/examples/argus/measurement/jan_cocktail_whiff.py | ACTIVE_DETECTORS=('H2','H1','AX','L1','L2', 'CDD')
#FITS=('Ar41:linear','Ar40:linear', 'Ar39:parabolic','Ar38:parabolic','Ar37:parabolic','Ar36:parabolic')
def main():
#simulate CO2 analysis
#open('T')
#sleep(5)
#close('L')
#display information with info(msg)
info('unknown measurement scri... | 0.284874 | 0.282858 |
import json
from argparse import ArgumentParser
from pathlib import Path
from typing import Set
import numpy as np
import pandas as pd
from loguru import logger
from utils.constants import (CATEGORICAL, FLOAT, INTEGER, NUMERICAL, ORDINAL)
from utils.utils import json_numpy_serialzer
# Please define the set of the or... | executables/generate_metadata_file.py | import json
from argparse import ArgumentParser
from pathlib import Path
from typing import Set
import numpy as np
import pandas as pd
from loguru import logger
from utils.constants import (CATEGORICAL, FLOAT, INTEGER, NUMERICAL, ORDINAL)
from utils.utils import json_numpy_serialzer
# Please define the set of the or... | 0.844794 | 0.239199 |
import numpy as np
import matplotlib.pyplot as plt
from pandas.io.parsers import read_csv
import scipy.optimize as opt
from sklearn.preprocessing import PolynomialFeatures
def load_csv(file_name):
values = read_csv(file_name, header=None).values
return values.astype(float)
def gradient(thetas, XX,... | src/regression/regresion_logistic_regularized.py | import numpy as np
import matplotlib.pyplot as plt
from pandas.io.parsers import read_csv
import scipy.optimize as opt
from sklearn.preprocessing import PolynomialFeatures
def load_csv(file_name):
values = read_csv(file_name, header=None).values
return values.astype(float)
def gradient(thetas, XX,... | 0.577138 | 0.588889 |
import cv2
import base64
import numpy as np
import pandas as pd
from unittest import TestCase, main
from ..core.constants import IMAGE_ID_COL, RLE_MASK_COL, DEFAULT_IMAGE_SIZE
from ..core.utils import (decode_rle, rescale, check_square_size,
get_image_rle_masks, decode_image_b64,
... | asdc/tests/test_utils.py |
import cv2
import base64
import numpy as np
import pandas as pd
from unittest import TestCase, main
from ..core.constants import IMAGE_ID_COL, RLE_MASK_COL, DEFAULT_IMAGE_SIZE
from ..core.utils import (decode_rle, rescale, check_square_size,
get_image_rle_masks, decode_image_b64,
... | 0.76145 | 0.713874 |
"""Augmentation ops."""
import functools
import random
from third_party import augment_ops
from third_party import data_util as simclr_ops
from third_party import rand_augment as randaug
import tensorflow as tf
def base_augment(is_training=True, **kwargs):
"""Base (resize and crop) augmentation."""
size, pad_si... | data/augment_ops.py | """Augmentation ops."""
import functools
import random
from third_party import augment_ops
from third_party import data_util as simclr_ops
from third_party import rand_augment as randaug
import tensorflow as tf
def base_augment(is_training=True, **kwargs):
"""Base (resize and crop) augmentation."""
size, pad_si... | 0.912869 | 0.240067 |
from math import radians
import arcade
import pymunk
from pymunk import Space
from ev3dev2simulator.obstacle.Board import Board
from ev3dev2simulator.state.RobotState import RobotState
from ev3dev2simulator.obstacle.Border import Border
from ev3dev2simulator.obstacle.Bottle import Bottle
from ev3dev2simulator.obstac... | ev3dev2simulator/state/WorldState.py | from math import radians
import arcade
import pymunk
from pymunk import Space
from ev3dev2simulator.obstacle.Board import Board
from ev3dev2simulator.state.RobotState import RobotState
from ev3dev2simulator.obstacle.Border import Border
from ev3dev2simulator.obstacle.Bottle import Bottle
from ev3dev2simulator.obstac... | 0.536556 | 0.360067 |
import pytz
import pytest
from itertools import product
from unittest.mock import Mock
from datetime import datetime, timezone, date
from originexample.common import Unit
from originexample.auth import User
from originexample.agreements.queries import AgreementQuery
from originexample.agreements.models import TradeAgr... | src/tests/agreements/AgreementQuery_test.py | import pytz
import pytest
from itertools import product
from unittest.mock import Mock
from datetime import datetime, timezone, date
from originexample.common import Unit
from originexample.auth import User
from originexample.agreements.queries import AgreementQuery
from originexample.agreements.models import TradeAgr... | 0.478285 | 0.259122 |
import numpy as np
import tensorflow as tf
import lucid.optvis.render as render
import itertools
from lucid.misc.gradient_override import gradient_override_map
def maxpool_override():
def MaxPoolGrad(op, grad):
inp = op.inputs[0]
op_args = [
op.get_attr("ksize"),
op.get_att... | lucid/scratch/rl_util/attribution.py | import numpy as np
import tensorflow as tf
import lucid.optvis.render as render
import itertools
from lucid.misc.gradient_override import gradient_override_map
def maxpool_override():
def MaxPoolGrad(op, grad):
inp = op.inputs[0]
op_args = [
op.get_attr("ksize"),
op.get_att... | 0.669205 | 0.413892 |
import model
def izpis_igre(igra):
tekst = (
'========================================'
'Število preostalih poskusov: {stevilo_preostalih_poskusov} \n\n'
' {pravilni_del_gesla}\n\n'
'Neuspeli poskusi: {neuspeli_poskusi}\n\n'
'================================... | tekstovni_vmesnik.py | import model
def izpis_igre(igra):
tekst = (
'========================================'
'Število preostalih poskusov: {stevilo_preostalih_poskusov} \n\n'
' {pravilni_del_gesla}\n\n'
'Neuspeli poskusi: {neuspeli_poskusi}\n\n'
'================================... | 0.08947 | 0.283707 |
from __future__ import print_function
import numpy as np
def generate_mult_function_batch_compile(k_list, l_list, m_list, mult_table_vals, n_dims,
product_name, product_mask=None, cuda=False):
"""
Takes a given product and generates the code for a function that evaluate... | clifford/code_gen.py | from __future__ import print_function
import numpy as np
def generate_mult_function_batch_compile(k_list, l_list, m_list, mult_table_vals, n_dims,
product_name, product_mask=None, cuda=False):
"""
Takes a given product and generates the code for a function that evaluate... | 0.45181 | 0.179495 |
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=... | blog/migrations/0001_initial.py | from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=... | 0.592313 | 0.143548 |
import os
import sys
import json
import types
import shutil
import pickle
import joblib
import xxhash
import inspect
import logging
from glob import glob
from time import time
from pathlib import Path
from functools import partial, wraps
CACHE_DIR = Path.home()/'.niq'
def load_cache(cache_path):
try:
retu... | niq/_niq.py | import os
import sys
import json
import types
import shutil
import pickle
import joblib
import xxhash
import inspect
import logging
from glob import glob
from time import time
from pathlib import Path
from functools import partial, wraps
CACHE_DIR = Path.home()/'.niq'
def load_cache(cache_path):
try:
retu... | 0.302082 | 0.054024 |
from momiji.modules import permissions
import discord
from discord.ext import commands
from momiji.reusables import get_member_helpers
class Utilities(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="ban_member", brief="Ban a member")
@commands.check(permissions.is_a... | momiji/cogs/Utilities.py | from momiji.modules import permissions
import discord
from discord.ext import commands
from momiji.reusables import get_member_helpers
class Utilities(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="ban_member", brief="Ban a member")
@commands.check(permissions.is_a... | 0.378229 | 0.080394 |
import turtle
import random
import time
# 画樱花的躯干
def tree(branch, t):
time.sleep(0.0008)
if branch > 3:
if 8 <= branch <= 12:
if random.randint(0, 2) == 0:
t.color('snow')
else:
t.color('lightcoral')
t.pensize(branch / 3)
elif... | cherry/cherry.py | import turtle
import random
import time
# 画樱花的躯干
def tree(branch, t):
time.sleep(0.0008)
if branch > 3:
if 8 <= branch <= 12:
if random.randint(0, 2) == 0:
t.color('snow')
else:
t.color('lightcoral')
t.pensize(branch / 3)
elif... | 0.165965 | 0.349366 |
from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import cross_validate
import numpy as np
import matplotlib.pyplot as plt
def plot_svc(model):
"""Plot the decision function for a 2D SVC"""
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# create grid to ... | SVM/1- First_Part/main.py | from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import cross_validate
import numpy as np
import matplotlib.pyplot as plt
def plot_svc(model):
"""Plot the decision function for a 2D SVC"""
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# create grid to ... | 0.698535 | 0.553747 |
import matplotlib.pyplot as plt
import numpy as np
def get_energy(J, spins):
return -J*np.sum(spins * np.roll(spins, 1, axis=0) +
spins * np.roll(spins, -1, axis=0) +
spins * np.roll(spins, 1, axis=1) +
spins * np.roll(spins, -1, axis=1))/2
... | Code/Ising_energy_Gibbs_sampling.py | import matplotlib.pyplot as plt
import numpy as np
def get_energy(J, spins):
return -J*np.sum(spins * np.roll(spins, 1, axis=0) +
spins * np.roll(spins, -1, axis=0) +
spins * np.roll(spins, 1, axis=1) +
spins * np.roll(spins, -1, axis=1))/2
... | 0.566498 | 0.500183 |
from colorama import Fore, Style, init
from json import load, load
init(autoreset=True)
file = "data\data.json"
with open(file, "r") as f:
data = load(f)
version_ = data["version"]
with open("data\\api_key.json", "r") as a:
ak = load(a)
apikey = ak["api_key"]
apikey_2 = ak["api_key_moviedb"]
with ... | src/submain.py | from colorama import Fore, Style, init
from json import load, load
init(autoreset=True)
file = "data\data.json"
with open(file, "r") as f:
data = load(f)
version_ = data["version"]
with open("data\\api_key.json", "r") as a:
ak = load(a)
apikey = ak["api_key"]
apikey_2 = ak["api_key_moviedb"]
with ... | 0.260107 | 0.172886 |
import os
import math
import random
import numpy as np
import tensorflow as tf
import cv2
slim = tf.contrib.slim
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import sys
sys.path.append('../')
from nets import ssd_vgg_300, ssd_common
from preprocessing import ssd_vgg_preprocessing
import visualiza... | ssd_visualize.py | import os
import math
import random
import numpy as np
import tensorflow as tf
import cv2
slim = tf.contrib.slim
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import sys
sys.path.append('../')
from nets import ssd_vgg_300, ssd_common
from preprocessing import ssd_vgg_preprocessing
import visualiza... | 0.412885 | 0.202148 |
from federatedml.evaluation import Evaluation
from sklearn.metrics import roc_auc_score
import numpy as np
import unittest
class TestClassificationEvaluaction(unittest.TestCase):
def assertFloatEqual(self,op1, op2):
diff = np.abs(op1 - op2)
self.assertLess(diff, 1e-6)
def test_auc(self):
... | federatedml/evaluation/test/evaluation_test.py |
from federatedml.evaluation import Evaluation
from sklearn.metrics import roc_auc_score
import numpy as np
import unittest
class TestClassificationEvaluaction(unittest.TestCase):
def assertFloatEqual(self,op1, op2):
diff = np.abs(op1 - op2)
self.assertLess(diff, 1e-6)
def test_auc(self):
... | 0.475605 | 0.543166 |
from props import getNode
import comms.events
from mission.task.task import Task
import mission.task.state
class Preflight(Task):
def __init__(self, config_node):
Task.__init__(self)
self.task_node = getNode("/task", True)
self.preflight_node = getNode("/task/preflight", True)
self... | src/mission/task/preflight.py | from props import getNode
import comms.events
from mission.task.task import Task
import mission.task.state
class Preflight(Task):
def __init__(self, config_node):
Task.__init__(self)
self.task_node = getNode("/task", True)
self.preflight_node = getNode("/task/preflight", True)
self... | 0.294621 | 0.121921 |
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render, redirect
from duolingo import Duolingo, DuolingoException
from .forms import Ne... | DuoVocabFE/views.py | from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render, redirect
from duolingo import Duolingo, DuolingoException
from .forms import Ne... | 0.34632 | 0.089614 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
from torch.autograd import Variable
import numpy as np
import time
import os
import copy
import argparse
from PIL im... | utils_incremental/compute_confusion_matrix.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
from torch.autograd import Variable
import numpy as np
import time
import os
import copy
import argparse
from PIL im... | 0.550124 | 0.513607 |
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.C... | amos/migrations/0001_initial.py |
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.C... | 0.486088 | 0.173533 |
from collections import OrderedDict
from MDRSREID.Loss_Meter.ID_loss import IDLoss
from MDRSREID.Loss_Meter.ID_smooth_loss import IDSmoothLoss
from MDRSREID.Loss_Meter.triplet_loss import TripletLoss
from MDRSREID.Loss_Meter.triplet_loss import TripletHardLoss
from MDRSREID.Loss_Meter.permutation_loss import Permutatio... | MDRSREID/Trainer/loss_function_creation/__init__.py | from collections import OrderedDict
from MDRSREID.Loss_Meter.ID_loss import IDLoss
from MDRSREID.Loss_Meter.ID_smooth_loss import IDSmoothLoss
from MDRSREID.Loss_Meter.triplet_loss import TripletLoss
from MDRSREID.Loss_Meter.triplet_loss import TripletHardLoss
from MDRSREID.Loss_Meter.permutation_loss import Permutatio... | 0.729905 | 0.108803 |
import math
def distanceOfPosition(pos1, pos2):
"""To get the distance between 2 given 3D points."""
return math.sqrt(pow(pos1[0]-pos2[0],2) + pow(pos1[1]-pos2[1],2) + pow(pos1[2]-pos2[2],2))
class Matrix:
def __init__(self, n):
self._rowlist = list()
self._size = n
i = 0
... | recoUtils.py | import math
def distanceOfPosition(pos1, pos2):
"""To get the distance between 2 given 3D points."""
return math.sqrt(pow(pos1[0]-pos2[0],2) + pow(pos1[1]-pos2[1],2) + pow(pos1[2]-pos2[2],2))
class Matrix:
def __init__(self, n):
self._rowlist = list()
self._size = n
i = 0
... | 0.533884 | 0.653251 |
import functools
import httplib
import Queue
import os
import re
import string
import socket
import sys
import threading
import telnetlib
import time
import urllib
if __name__ == '__main__':
try:
soapTemplate = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.... | Documentation/test scripts/test_bravia_tv.py | import functools
import httplib
import Queue
import os
import re
import string
import socket
import sys
import threading
import telnetlib
import time
import urllib
if __name__ == '__main__':
try:
soapTemplate = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.... | 0.048824 | 0.05498 |
import csv
import pandas as pd
import json
import spacy
import re
from spacy.lang.en import English
from spacy.pipeline import EntityRuler
from spacy import displacy
from collections import Counter
# Import data yg akan dilakukan ekstraksi informasi
data = pd.read_csv("data/desa.csv", encoding='utf-8', index_col=0)
ek... | script/news-analysis/Ekstraksi.py | import csv
import pandas as pd
import json
import spacy
import re
from spacy.lang.en import English
from spacy.pipeline import EntityRuler
from spacy import displacy
from collections import Counter
# Import data yg akan dilakukan ekstraksi informasi
data = pd.read_csv("data/desa.csv", encoding='utf-8', index_col=0)
ek... | 0.221603 | 0.207897 |
"""Azure Service helpers."""
import logging
from tempfile import NamedTemporaryFile
from adal.adal_error import AdalError
from azure.common import AzureException
from azure.core.exceptions import HttpResponseError
from msrest.exceptions import ClientException
from providers.azure.client import AzureClientFactory
LOG... | koku/masu/external/downloader/azure/azure_service.py | """Azure Service helpers."""
import logging
from tempfile import NamedTemporaryFile
from adal.adal_error import AdalError
from azure.common import AzureException
from azure.core.exceptions import HttpResponseError
from msrest.exceptions import ClientException
from providers.azure.client import AzureClientFactory
LOG... | 0.848235 | 0.092606 |
import shapes
import pygame
class Brush:
"""
Brush class
"""
def __init__(self, colour, width):
"""
Constructor, assigns values
Args:
colour (tuple): RGB values for the brush colour
width (int): width of brush
"""
self._colour = colour
... | src/brushes.py | import shapes
import pygame
class Brush:
"""
Brush class
"""
def __init__(self, colour, width):
"""
Constructor, assigns values
Args:
colour (tuple): RGB values for the brush colour
width (int): width of brush
"""
self._colour = colour
... | 0.897415 | 0.547404 |
from .. import Tag
from ..render import HRenderer
import threading
import os,json
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.routing import Route,WebSocketRoute
from starlette.endpoints import WebSocketEndpoint
import socket
def isFree(ip, port):
s =... | htag/runners/devapp.py |
from .. import Tag
from ..render import HRenderer
import threading
import os,json
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.routing import Route,WebSocketRoute
from starlette.endpoints import WebSocketEndpoint
import socket
def isFree(ip, port):
s =... | 0.309963 | 0.06951 |
from datetime import timedelta
from logging import getLogger
from typing import Callable, Union, List, Tuple, Optional
from zstandard import ZstdDecompressor # type: ignore
from penguin_judge.check_result import equal_binary
from penguin_judge.models import (
JudgeStatus, Submission, JudgeResult, transaction, sc... | backend/penguin_judge/judge/main.py | from datetime import timedelta
from logging import getLogger
from typing import Callable, Union, List, Tuple, Optional
from zstandard import ZstdDecompressor # type: ignore
from penguin_judge.check_result import equal_binary
from penguin_judge.models import (
JudgeStatus, Submission, JudgeResult, transaction, sc... | 0.745028 | 0.23014 |
import re
from markdown.blockprocessors import ParagraphProcessor
from markdown.extensions import Extension
from markdown.util import etree
from .utils import markdown_ordered_dict_prepend
class EmbeddingProcessor(ParagraphProcessor):
RE = re.compile(r'!\[embed(\?(?P<params>.*))?\]\((?P<url>[^\)]+)\)')
YOU... | iwg_blog/markdown_extensions/embedding.py | import re
from markdown.blockprocessors import ParagraphProcessor
from markdown.extensions import Extension
from markdown.util import etree
from .utils import markdown_ordered_dict_prepend
class EmbeddingProcessor(ParagraphProcessor):
RE = re.compile(r'!\[embed(\?(?P<params>.*))?\]\((?P<url>[^\)]+)\)')
YOU... | 0.390708 | 0.127598 |
import re
import unittest
import pytest
from cognite.client.data_classes import ContextualizationJob
from cognite.client.exceptions import ModelFailedException
from cognite.experimental import CogniteClient
from cognite.experimental.data_classes import PNIDDetectionList, PNIDDetectResults
from tests.utils import jsgz... | tests/tests_unit/test_contextualization/test_pnid_parsing.py | import re
import unittest
import pytest
from cognite.client.data_classes import ContextualizationJob
from cognite.client.exceptions import ModelFailedException
from cognite.experimental import CogniteClient
from cognite.experimental.data_classes import PNIDDetectionList, PNIDDetectResults
from tests.utils import jsgz... | 0.382372 | 0.204521 |
from s3iamcli.cli_response import CLIResponse
class UserLoginProfile:
def __init__(self, iam_client, cli_args):
self.iam_client = iam_client
self.cli_args = cli_args
def create(self):
if(self.cli_args.name is None):
message = "User name is required for user login-profile c... | auth-utils/s3iamcli/s3iamcli/userloginprofile.py |
from s3iamcli.cli_response import CLIResponse
class UserLoginProfile:
def __init__(self, iam_client, cli_args):
self.iam_client = iam_client
self.cli_args = cli_args
def create(self):
if(self.cli_args.name is None):
message = "User name is required for user login-profile c... | 0.223547 | 0.039379 |
import os
import sys
import time
import click
import signal
import requests
from requests.compat import urljoin
from prometheus_client import start_http_server
from prometheus_client.core import REGISTRY
from ecs_container_exporter.utils import create_metric, task_metric_tags, TASK_CONTAINER_NAME_TAG
from ecs_contain... | ecs_container_exporter/main.py | import os
import sys
import time
import click
import signal
import requests
from requests.compat import urljoin
from prometheus_client import start_http_server
from prometheus_client.core import REGISTRY
from ecs_container_exporter.utils import create_metric, task_metric_tags, TASK_CONTAINER_NAME_TAG
from ecs_contain... | 0.335024 | 0.062875 |
import math, os, sys, unittest
sys.path.append(os.path.join('..'))
from twyg.geom import Vector2
deg = math.degrees
rad = math.radians
class TestEvalExpr(unittest.TestCase):
def assert_equals(self, a, b):
self.assertTrue(abs(a - b) < 1e-12)
def test_constructor_cartesian1(self)... | twyg/tests/geom_test.py | import math, os, sys, unittest
sys.path.append(os.path.join('..'))
from twyg.geom import Vector2
deg = math.degrees
rad = math.radians
class TestEvalExpr(unittest.TestCase):
def assert_equals(self, a, b):
self.assertTrue(abs(a - b) < 1e-12)
def test_constructor_cartesian1(self)... | 0.581778 | 0.708824 |
import sys
import os
import time
from signal import SIGTERM
class Daemon:
def __init__(self, stdout='/dev/null', stderr=None, stdin='/dev/null'):
self.stdout = stdout
self.stderr = stderr
self.stdin = stdin
self.startmsg = 'started with pid {}'
def deamonize(self, pidfile=None... | Bagpipe/Coordinator/daemon.py | import sys
import os
import time
from signal import SIGTERM
class Daemon:
def __init__(self, stdout='/dev/null', stderr=None, stdin='/dev/null'):
self.stdout = stdout
self.stderr = stderr
self.stdin = stdin
self.startmsg = 'started with pid {}'
def deamonize(self, pidfile=None... | 0.111652 | 0.078184 |
import requests
import json
def ocr_space_file(filename, overlay=False, api_key='<KEY>', language='eng'):
""" OCR.space API request with local file.
Python3.5 - not tested on 2.7
:param filename: Your file path & name.
:param overlay: Is OCR.space overlay required in your response.
... | OCR _TEST.py | import requests
import json
def ocr_space_file(filename, overlay=False, api_key='<KEY>', language='eng'):
""" OCR.space API request with local file.
Python3.5 - not tested on 2.7
:param filename: Your file path & name.
:param overlay: Is OCR.space overlay required in your response.
... | 0.47171 | 0.247726 |
from data_cleaner import DataCleaner
import pandas as pd
import sys
# input_path = "contratos_vigentes_2015.csv"
# DEFAULT_OUTPUT_PATH = "clear_contratos_vigentes_2015.csv"
DEFAULT_INPUT_PATH = "contratos-raw.csv"
DEFAULT_OUTPUT_PATH_VIGENTE = "contratos-2015-clean.csv"
DEFAULT_OUTPUT_PATH1_HISTORICO = "contratos-hist... | contratos/cleaner-contratos.py | from data_cleaner import DataCleaner
import pandas as pd
import sys
# input_path = "contratos_vigentes_2015.csv"
# DEFAULT_OUTPUT_PATH = "clear_contratos_vigentes_2015.csv"
DEFAULT_INPUT_PATH = "contratos-raw.csv"
DEFAULT_OUTPUT_PATH_VIGENTE = "contratos-2015-clean.csv"
DEFAULT_OUTPUT_PATH1_HISTORICO = "contratos-hist... | 0.233881 | 0.317955 |
import os
import shutil
import eos.log
import eos.tools
import eos.util
def _check_return_code(code):
if code != 0:
raise RuntimeError("repository operation failed")
def _remove_directory(directory):
if os.path.exists(directory):
shutil.rmtree(directory)
def _execute(command):
print_co... | eos/repo.py | import os
import shutil
import eos.log
import eos.tools
import eos.util
def _check_return_code(code):
if code != 0:
raise RuntimeError("repository operation failed")
def _remove_directory(directory):
if os.path.exists(directory):
shutil.rmtree(directory)
def _execute(command):
print_co... | 0.343562 | 0.127761 |
import jinja2
import cherrypy
import platform
from pymongo import MongoClient
from pymongo import ReadPreference
from engine.tools import IgnoreRequestFilter
from engine.tools import secureheaders
cherrypy.tools.secureheaders = cherrypy.Tool(
"before_finalize", secureheaders, priority=60)
from engine.tools impor... | containers/shiva/S.H.I.V.A..py | import jinja2
import cherrypy
import platform
from pymongo import MongoClient
from pymongo import ReadPreference
from engine.tools import IgnoreRequestFilter
from engine.tools import secureheaders
cherrypy.tools.secureheaders = cherrypy.Tool(
"before_finalize", secureheaders, priority=60)
from engine.tools impor... | 0.367838 | 0.112918 |
import os
from collections import OrderedDict
def create_param(is_reverse, data):
line_id = data[0]
try:
if is_reverse:
param = data[1]
src_line = [data[0], data[1]]
else:
param = data[1] + ',' + data[2]
src_line = [data[0], data[1], data[2]]
... | geocoder/util.py | import os
from collections import OrderedDict
def create_param(is_reverse, data):
line_id = data[0]
try:
if is_reverse:
param = data[1]
src_line = [data[0], data[1]]
else:
param = data[1] + ',' + data[2]
src_line = [data[0], data[1], data[2]]
... | 0.203708 | 0.387864 |
import config as config # configurables file
import os, sys
import datetime as dt
import asyncio
import smtplib
import RH.Reports.RH_functions as rh # robinhood processes
import RH.Reports.APP_functions as app # application processes
import RH.Process_routes as routes # routes
import RH.Log.log... | APP.py | import config as config # configurables file
import os, sys
import datetime as dt
import asyncio
import smtplib
import RH.Reports.RH_functions as rh # robinhood processes
import RH.Reports.APP_functions as app # application processes
import RH.Process_routes as routes # routes
import RH.Log.log... | 0.151843 | 0.052912 |
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
class People(models.Model):
entity = models.ForeignKey(
'register.Entity',
related_name='%(class)s' + 's',
on_delete=models.C... | people/models.py | from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
class People(models.Model):
entity = models.ForeignKey(
'register.Entity',
related_name='%(class)s' + 's',
on_delete=models.C... | 0.560734 | 0.108095 |
from marshmallow import EXCLUDE
from marshmallow_jsonapi import Schema as __Schema, SchemaOpts as __SchemaOpts
from starlette.applications import Starlette
class BaseSchemaOpts(__SchemaOpts):
""" An adaptation of marshmallow-jsonapi Flask SchemaOpts for use with Starlette. """
def __init__(self, meta, *args, ... | starlette_jsonapi/schema.py | from marshmallow import EXCLUDE
from marshmallow_jsonapi import Schema as __Schema, SchemaOpts as __SchemaOpts
from starlette.applications import Starlette
class BaseSchemaOpts(__SchemaOpts):
""" An adaptation of marshmallow-jsonapi Flask SchemaOpts for use with Starlette. """
def __init__(self, meta, *args, ... | 0.797281 | 0.086903 |
from __future__ import annotations
import typing as t
from dataclasses import dataclass, field
from arg_services.graph.v1 import graph_pb2
from arguebuf.models import Userdata
from arguebuf.models.metadata import Metadata
from arguebuf.schema import ova
from arguebuf.services import dt, utils
from pendulum.datetime i... | arguebuf/models/resource.py | from __future__ import annotations
import typing as t
from dataclasses import dataclass, field
from arg_services.graph.v1 import graph_pb2
from arguebuf.models import Userdata
from arguebuf.models.metadata import Metadata
from arguebuf.schema import ova
from arguebuf.services import dt, utils
from pendulum.datetime i... | 0.898461 | 0.16872 |
import certifi
import os
import socket
import ssl
from functools import lru_cache
from os.path import dirname, abspath
from pydantic import BaseSettings
host_name = socket.gethostname()
class Settings(BaseSettings):
"""
application settings
"""
# uvicorn settings
uvicorn_app: str = "bluebutton.a... | blue-button.py/bluebutton/config.py | import certifi
import os
import socket
import ssl
from functools import lru_cache
from os.path import dirname, abspath
from pydantic import BaseSettings
host_name = socket.gethostname()
class Settings(BaseSettings):
"""
application settings
"""
# uvicorn settings
uvicorn_app: str = "bluebutton.a... | 0.394084 | 0.080864 |
from __future__ import unicode_literals
import frappe
from frappe.utils import cint
import pandas
from operator import itemgetter
def execute(filters=None):
return get_data(filters)
def get_conditions(filters):
where_clause = []
if filters.get("from_date"):
where_clause += ["date(comm.creation)... | npro/npro/report/customer_contactwise_communication_analysis/customer_contactwise_communication_analysis.py |
from __future__ import unicode_literals
import frappe
from frappe.utils import cint
import pandas
from operator import itemgetter
def execute(filters=None):
return get_data(filters)
def get_conditions(filters):
where_clause = []
if filters.get("from_date"):
where_clause += ["date(comm.creation)... | 0.66769 | 0.177526 |
import json
import datetime
import subprocess as sp
import boto3
import time
import sys
from gpiozero import LED
from gpiozero import Button
# Red led = gpio 24
# Green led = gpio 18
# Button = gpio 3
class RpiHandler:
def __init__(self, table_name, username):
self.state = False
self.start_time = ... | rpi/gpiocontroller.py |
import json
import datetime
import subprocess as sp
import boto3
import time
import sys
from gpiozero import LED
from gpiozero import Button
# Red led = gpio 24
# Green led = gpio 18
# Button = gpio 3
class RpiHandler:
def __init__(self, table_name, username):
self.state = False
self.start_time = ... | 0.275325 | 0.111121 |
class TstNode(object):
key = None
value = None
mid = None
left = None
right = None
def __init__(self, key=None, value=None, left=None, right=None, mid=None):
if key is not None:
self.key = key
if value is not None:
self.value = value
if mid is not... | pysie/dsl/set.py | class TstNode(object):
key = None
value = None
mid = None
left = None
right = None
def __init__(self, key=None, value=None, left=None, right=None, mid=None):
if key is not None:
self.key = key
if value is not None:
self.value = value
if mid is not... | 0.619932 | 0.264982 |
import os
import json
from datetime import datetime
from collections import Counter, defaultdict
FAIL_TAGS = ('UNDEFINED', 'PRECALC', 'BUILDING', 'NOT_SOLID', 'VOLUME',
'BBOX_Z', 'BBOX_XY', 'TIMEOUT')
class Report:
'''Summarizes test result data.
Also organizes parameters which failed to produc... | tests/report.py | import os
import json
from datetime import datetime
from collections import Counter, defaultdict
FAIL_TAGS = ('UNDEFINED', 'PRECALC', 'BUILDING', 'NOT_SOLID', 'VOLUME',
'BBOX_Z', 'BBOX_XY', 'TIMEOUT')
class Report:
'''Summarizes test result data.
Also organizes parameters which failed to produc... | 0.269133 | 0.135518 |
import csv, json, pandas as pd
import os, sys, requests, datetime, time
import zipfile, io
import lxml.html as lhtml
import lxml.html.clean as lhtmlclean
import warnings
from pandas.core.common import SettingWithCopyWarning
warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
class QualClient:
... | qualclient/qualclient.py | import csv, json, pandas as pd
import os, sys, requests, datetime, time
import zipfile, io
import lxml.html as lhtml
import lxml.html.clean as lhtmlclean
import warnings
from pandas.core.common import SettingWithCopyWarning
warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
class QualClient:
... | 0.36376 | 0.256966 |
def spaceRect(rect,y):
for i in range(len(rect)):
for b in [0,1]:
if rect[i][b]>=y:
rect[i][b]+=1
def spaceColumn(col,y):
for i in range(len(col)):
if col[i]>=y:
col[i]+=1
def findMax(rect):
mx=-1
for i in range(len(rect)):
... | src/KnotTheory/HFK-Zurich/braid2rect.py | def spaceRect(rect,y):
for i in range(len(rect)):
for b in [0,1]:
if rect[i][b]>=y:
rect[i][b]+=1
def spaceColumn(col,y):
for i in range(len(col)):
if col[i]>=y:
col[i]+=1
def findMax(rect):
mx=-1
for i in range(len(rect)):
... | 0.049359 | 0.267197 |
from typing import Any, Dict, List, Tuple, Union
from ..logger import get_logger
log = get_logger("DB-Util")
def convert_to_db_list(orig_list: Union[Tuple[Any, ...], List[Any]]) -> Dict[str, Any]:
"""Convert a list to the DynamoDB list type.
Note: There is no tuple type in DynamoDB so we will also convert t... | lorien/database/util.py | from typing import Any, Dict, List, Tuple, Union
from ..logger import get_logger
log = get_logger("DB-Util")
def convert_to_db_list(orig_list: Union[Tuple[Any, ...], List[Any]]) -> Dict[str, Any]:
"""Convert a list to the DynamoDB list type.
Note: There is no tuple type in DynamoDB so we will also convert t... | 0.873032 | 0.364071 |
from pygame import mixer # Playing sound
from gtts import gTTS, gTTSError
from mutagen.mp3 import MP3
from multiprocessing import Process, Queue, Manager
from audioplayer import AudioPlayer
import time
import uuid
import os
import gtts.tokenizer.symbols as sym
# Add custom abbreviations for pt-br
new_abbreviations =... | bg.py | from pygame import mixer # Playing sound
from gtts import gTTS, gTTSError
from mutagen.mp3 import MP3
from multiprocessing import Process, Queue, Manager
from audioplayer import AudioPlayer
import time
import uuid
import os
import gtts.tokenizer.symbols as sym
# Add custom abbreviations for pt-br
new_abbreviations =... | 0.285671 | 0.074467 |
__all__ = ["tripleFromMetadataXML",
"decodeTriple",
"ChemistryLookupError" ]
import xml.etree.ElementTree as ET, os.path
from pkg_resources import Requirement, resource_filename
from collections import OrderedDict
class ChemistryLookupError(Exception): pass
def _loadBarcodeMappingsFromFile(ma... | pbcore/chemistry/chemistry.py |
__all__ = ["tripleFromMetadataXML",
"decodeTriple",
"ChemistryLookupError" ]
import xml.etree.ElementTree as ET, os.path
from pkg_resources import Requirement, resource_filename
from collections import OrderedDict
class ChemistryLookupError(Exception): pass
def _loadBarcodeMappingsFromFile(ma... | 0.578448 | 0.113949 |
from twitter import Twitter, OAuth, TwitterHTTPError
import os
from twitter_info import *
# put the full path and file name of the file you want to store your "already followed"
# list in
ALREADY_FOLLOWED_FILE = "already-followed.csv"
t = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET,
CONSUMER_KEY, CONSUME... | twitter/twitter_follow_bot.py | from twitter import Twitter, OAuth, TwitterHTTPError
import os
from twitter_info import *
# put the full path and file name of the file you want to store your "already followed"
# list in
ALREADY_FOLLOWED_FILE = "already-followed.csv"
t = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET,
CONSUMER_KEY, CONSUME... | 0.319758 | 0.085939 |
from bs4 import BeautifulSoup
from Crypto.PublicKey import RSA
from argparse import ArgumentParser
import requests
import os
from . import __version__
FACTOR_DB_URL = 'http://factordb.com/index.php'
def get_int_href(href) -> int:
nid = href.get('href').split('=')[1].strip('/')
response = requests.get(FACTOR_D... | rsapwn/rsapwn.py | from bs4 import BeautifulSoup
from Crypto.PublicKey import RSA
from argparse import ArgumentParser
import requests
import os
from . import __version__
FACTOR_DB_URL = 'http://factordb.com/index.php'
def get_int_href(href) -> int:
nid = href.get('href').split('=')[1].strip('/')
response = requests.get(FACTOR_D... | 0.463201 | 0.081374 |
from collections import defaultdict
from dataclasses import dataclass
from functools import total_ordering
from itertools import groupby
from json import loads
from optparse import OptionParser
from sys import getdefaultencoding
from jsonpath_ng import parse
from tabulate import tabulate
@dataclass(order=True, froze... | pythonProject1/venv/Lib/site-packages/json_analyze.py | from collections import defaultdict
from dataclasses import dataclass
from functools import total_ordering
from itertools import groupby
from json import loads
from optparse import OptionParser
from sys import getdefaultencoding
from jsonpath_ng import parse
from tabulate import tabulate
@dataclass(order=True, froze... | 0.386995 | 0.211091 |
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = """\
Copyright (c) 2005-2013 <NAME>
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 ... | thor/tcp.py | __author__ = "<NAME> <<EMAIL>>"
__copyright__ = """\
Copyright (c) 2005-2013 <NAME>
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 ... | 0.359926 | 0.15084 |
from datetime import datetime
import logging
from prpy.planning.base import Tags
from prpy.util import GetTrajectoryTags
def get_logger():
"""
Return the metrics logger.
@return metrics logger
"""
metrics_logger = logging.getLogger('planning_metrics')
return metrics_logger
def setup_logger... | src/magi/logging_utils.py |
from datetime import datetime
import logging
from prpy.planning.base import Tags
from prpy.util import GetTrajectoryTags
def get_logger():
"""
Return the metrics logger.
@return metrics logger
"""
metrics_logger = logging.getLogger('planning_metrics')
return metrics_logger
def setup_logger... | 0.83762 | 0.174621 |
from pythonjsonlogger import jsonlogger
import logging
# Distributed tracing
# OpenTelemetry python imports
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.exporter.otlp.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from o... | demo-app/service1/app.py | from pythonjsonlogger import jsonlogger
import logging
# Distributed tracing
# OpenTelemetry python imports
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.exporter.otlp.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from o... | 0.536556 | 0.077622 |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn.manifold as manifold
from sklearn.decomposition import PCA, TruncatedSVD, RandomizedPCA
from pandas.tools.plotting import parallel_coordinates
from bokeh_plots import scatter_with_hover
... | examples/plot.py | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn.manifold as manifold
from sklearn.decomposition import PCA, TruncatedSVD, RandomizedPCA
from pandas.tools.plotting import parallel_coordinates
from bokeh_plots import scatter_with_hover
... | 0.498291 | 0.564519 |
import argparse
import os
import shutil
import stat
import sys
import tempfile
import pytest
from statick_tool.config import Config
from statick_tool.plugin_context import PluginContext
from statick_tool.resources import Resources
from statick_tool.tool_plugin import ToolPlugin
def test_tool_plugin_load_mapping_val... | tests/tool_plugin/test_tool_plugin.py | import argparse
import os
import shutil
import stat
import sys
import tempfile
import pytest
from statick_tool.config import Config
from statick_tool.plugin_context import PluginContext
from statick_tool.resources import Resources
from statick_tool.tool_plugin import ToolPlugin
def test_tool_plugin_load_mapping_val... | 0.47926 | 0.234407 |
import os
from wa import ApkUiautoWorkload, Parameter
from wa.framework.exception import ValidationError, WorkloadError
class Gmail(ApkUiautoWorkload):
name = 'gmail'
package_names = ['com.google.android.gm']
description = '''
A workload to perform standard productivity tasks within Gmail. The wor... | wa/workloads/gmail/__init__.py |
import os
from wa import ApkUiautoWorkload, Parameter
from wa.framework.exception import ValidationError, WorkloadError
class Gmail(ApkUiautoWorkload):
name = 'gmail'
package_names = ['com.google.android.gm']
description = '''
A workload to perform standard productivity tasks within Gmail. The wor... | 0.544075 | 0.317638 |
from collections import defaultdict
import json
from os import environ, getcwd, path
import shutil
import subprocess
import ssh_utils
import utils
WORKSPACE = getcwd()
HOSTS_PATH = path.join(WORKSPACE, 'hosts')
HOSTS_TEMPLATE_PATH = path.join(WORKSPACE, '.hosts-template')
def host_path(host_dir):
return path.jo... | .python-packages/base_host.py | from collections import defaultdict
import json
from os import environ, getcwd, path
import shutil
import subprocess
import ssh_utils
import utils
WORKSPACE = getcwd()
HOSTS_PATH = path.join(WORKSPACE, 'hosts')
HOSTS_TEMPLATE_PATH = path.join(WORKSPACE, '.hosts-template')
def host_path(host_dir):
return path.jo... | 0.422147 | 0.058534 |
import datetime
import pytest
import boto3
from mock import patch, Mock
import reports.import_config_rule_status.import_config_rule_status as import_config_rule_status
@pytest.fixture(scope="function")
def _citizen_items_valid():
return {
"Items": [
{
"AccountId": {"S": "1"},
... | unit_tests/reports/test_import_config_rule_status.py | import datetime
import pytest
import boto3
from mock import patch, Mock
import reports.import_config_rule_status.import_config_rule_status as import_config_rule_status
@pytest.fixture(scope="function")
def _citizen_items_valid():
return {
"Items": [
{
"AccountId": {"S": "1"},
... | 0.373419 | 0.218482 |
__title__ = 'Create Lintel'
__author__ = 'htl'
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import rpw
from rpw.ui.forms import Label, TextBox, Button, ComboBox, FlexForm
from htl import selection
uiapp = __revit__
uidoc = uiapp.ActiveUIDocument
app = uiapp.Application
doc = uidoc.Document
... | HTL.tab/Architecture.panel/Lintel.pushbutton/script.py | __title__ = 'Create Lintel'
__author__ = 'htl'
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import rpw
from rpw.ui.forms import Label, TextBox, Button, ComboBox, FlexForm
from htl import selection
uiapp = __revit__
uidoc = uiapp.ActiveUIDocument
app = uiapp.Application
doc = uidoc.Document
... | 0.45641 | 0.136062 |
import codecs
import json
import random
def shuffle_list(paper_list,number):
random.shuffle(paper_list)
return paper_list[:number]
def expand_by_coop(flag):
with codecs.open("./raw_data/author_press.json","r","utf-8") as fid:
author_press = json.load(fid)
with codecs.open("./raw_data/author_co... | code/expand_author_press.py | import codecs
import json
import random
def shuffle_list(paper_list,number):
random.shuffle(paper_list)
return paper_list[:number]
def expand_by_coop(flag):
with codecs.open("./raw_data/author_press.json","r","utf-8") as fid:
author_press = json.load(fid)
with codecs.open("./raw_data/author_co... | 0.071118 | 0.17637 |
import abc
import os
from plaso.lib import errors
from plaso.parsers import manager
class BaseFileEntryFilter(object):
"""Class that defines the file entry filter interface."""
@abc.abstractmethod
def Match(self, file_entry):
"""Determines if a file entry matches the filter.
Args:
file_entry: a... | plaso/parsers/interface.py | import abc
import os
from plaso.lib import errors
from plaso.parsers import manager
class BaseFileEntryFilter(object):
"""Class that defines the file entry filter interface."""
@abc.abstractmethod
def Match(self, file_entry):
"""Determines if a file entry matches the filter.
Args:
file_entry: a... | 0.85744 | 0.305141 |
"""Import of required packages/libraries."""
import datetime
import os
from flask import flash
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import Response
from flask import send_file
from flask import url_for
from flask_basicauth import Basi... | creative/app/main.py | """Import of required packages/libraries."""
import datetime
import os
from flask import flash
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import Response
from flask import send_file
from flask import url_for
from flask_basicauth import Basi... | 0.510496 | 0.08374 |
"""Module with classes to format results from the Google Cloud Translation API"""
import logging
import pandas as pd
from typing import AnyStr, Dict
from plugin_io_utils import (
API_COLUMN_NAMES_DESCRIPTION_DICT,
ErrorHandlingEnum,
build_unique_column_names,
generate_unique,
safe_json_loads,
... | python-lib/google_translate_api_formatting.py | """Module with classes to format results from the Google Cloud Translation API"""
import logging
import pandas as pd
from typing import AnyStr, Dict
from plugin_io_utils import (
API_COLUMN_NAMES_DESCRIPTION_DICT,
ErrorHandlingEnum,
build_unique_column_names,
generate_unique,
safe_json_loads,
... | 0.868548 | 0.455441 |
"""
CloudFront Plugin
"""
import logging
import urlparse
import uglwcdriver.lib.abstractlwc as abstractlwc
logger = logging.getLogger('syndicate_cloudfront_cdn')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('syndicate_cloudfront_cdn.log')
fh.setLevel(logg... | src/uglwcdriver/plugins/cloudfront/cloudfront_plugin.py | """
CloudFront Plugin
"""
import logging
import urlparse
import uglwcdriver.lib.abstractlwc as abstractlwc
logger = logging.getLogger('syndicate_cloudfront_cdn')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('syndicate_cloudfront_cdn.log')
fh.setLevel(logg... | 0.570331 | 0.065755 |
from typing import Optional
from fastapi import FastAPI, Request, Depends, BackgroundTasks
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session
from pydantic import BaseModel
import yfinance
import models
from database import SessionLocal, engine... | main.py | from typing import Optional
from fastapi import FastAPI, Request, Depends, BackgroundTasks
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session
from pydantic import BaseModel
import yfinance
import models
from database import SessionLocal, engine... | 0.719384 | 0.166134 |
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')
FONT = pygame.font.Font(None, 32)
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.... | input_box.py | import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')
FONT = pygame.font.Font(None, 32)
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.... | 0.370225 | 0.181608 |
from django.core.exceptions import ValidationError
from nails_project.schedule.models import Schedule
from tests.base.tests import NailsProjectTestCase
class ScheduleModelTests(NailsProjectTestCase):
def test_saveModel_whenValid_shouldBeValid(self):
data = {
'date': "2021-08-10",
... | tests/schedule/models/test_schedule_model.py | from django.core.exceptions import ValidationError
from nails_project.schedule.models import Schedule
from tests.base.tests import NailsProjectTestCase
class ScheduleModelTests(NailsProjectTestCase):
def test_saveModel_whenValid_shouldBeValid(self):
data = {
'date': "2021-08-10",
... | 0.550849 | 0.341308 |