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 |
|---|---|---|---|---|
# Various Flask framework items.
import os
import sys
import codecs
import psycopg2
from flask import url_for, redirect, render_template, flash, g
from bluecat import route, util
from bluecat.wtform_extensions import GatewayForm
from bluecat.wtform_fields import TableField
import config.default_config as config
fro... | Community/view_db_statistics/view_db_statistics_page.py |
# Various Flask framework items.
import os
import sys
import codecs
import psycopg2
from flask import url_for, redirect, render_template, flash, g
from bluecat import route, util
from bluecat.wtform_extensions import GatewayForm
from bluecat.wtform_fields import TableField
import config.default_config as config
fro... | 0.361954 | 0.142232 |
### BEGIN INIT INFO
# Provides: k9pidaemon
# Required-Start: $syslog
# Required-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Starts up serial communication to the k9 robot
# Description: Reponsible for auto starting the k9 robot. A script which will s... | pi/daemon/k9pidaemon.py |
### BEGIN INIT INFO
# Provides: k9pidaemon
# Required-Start: $syslog
# Required-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Starts up serial communication to the k9 robot
# Description: Reponsible for auto starting the k9 robot. A script which will s... | 0.307462 | 0.141667 |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.metrics import precision_score, recall_score, accuracy_score, f1_score, auc, average_precision_score, confusion_matrix, roc_auc_score, classification_report, plot_precision_recall_curve
from collections import Counter
from sklearn.dat... | utils.py | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.metrics import precision_score, recall_score, accuracy_score, f1_score, auc, average_precision_score, confusion_matrix, roc_auc_score, classification_report, plot_precision_recall_curve
from collections import Counter
from sklearn.dat... | 0.810966 | 0.597784 |
import os
import argparse
import logging
import logging.config
import embeddix.core.converter as converter
import embeddix.core.extractor as extractor
import embeddix.core.evaluator as evaluator
import embeddix.core.reducer as reducer
import embeddix.utils.config as cutils
logging.config.dictConfig(
cutils.load... | embeddix/main.py | import os
import argparse
import logging
import logging.config
import embeddix.core.converter as converter
import embeddix.core.extractor as extractor
import embeddix.core.evaluator as evaluator
import embeddix.core.reducer as reducer
import embeddix.utils.config as cutils
logging.config.dictConfig(
cutils.load... | 0.475362 | 0.093264 |
import sys
import csv
import pandas as pd
current_path = sys.path[0]
sys.path.append(''.join([current_path,'\\..']))
sys.path.append(''.join([current_path,'\\..\\netCDF_Utils']))
from netCDF4 import Dataset
import numpy as np
import netCDF_Utils.nc as nc
from pytz import timezone
from csv_readers import Leveltroll, Mea... | STNServices2/dist/Assets/Scripts/stn_script_air.py | import sys
import csv
import pandas as pd
current_path = sys.path[0]
sys.path.append(''.join([current_path,'\\..']))
sys.path.append(''.join([current_path,'\\..\\netCDF_Utils']))
from netCDF4 import Dataset
import numpy as np
import netCDF_Utils.nc as nc
from pytz import timezone
from csv_readers import Leveltroll, Mea... | 0.166404 | 0.144994 |
from django.db import migrations, models
import phone_field.models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20200120_1850'),
]
operations = [
migrations.AddField(
model_name='application',
name='birth_certificate',
fi... | src/api/migrations/0004_auto_20200121_1216.py |
from django.db import migrations, models
import phone_field.models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20200120_1850'),
]
operations = [
migrations.AddField(
model_name='application',
name='birth_certificate',
fi... | 0.620277 | 0.167593 |
from django.contrib.auth import get_user_model
from django.utils.decorators import method_decorator
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from qfieldcloud.core import permissions_utils, utils
from qfieldcloud.core.models import Project, ProjectQueryset
from qfieldcloud.core.seriali... | docker-app/qfieldcloud/core/views/projects_views.py | from django.contrib.auth import get_user_model
from django.utils.decorators import method_decorator
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from qfieldcloud.core import permissions_utils, utils
from qfieldcloud.core.models import Project, ProjectQueryset
from qfieldcloud.core.seriali... | 0.623033 | 0.141994 |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
import torch.nn.functional as F
import torchvision
# Tools lib
import numpy as np
import cv2
import random
import time
import os
# Set iteration time
ITERATION = 4
# Model
class Att_GAN_Generator(... | models/att_gan.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
import torch.nn.functional as F
import torchvision
# Tools lib
import numpy as np
import cv2
import random
import time
import os
# Set iteration time
ITERATION = 4
# Model
class Att_GAN_Generator(... | 0.846594 | 0.450601 |
#INVESTIGATING FREEFALL USING THE EULER METHOD
#-----------------------------------------------------------
#PART A
#-----------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
y0 = 1000
m = 70
k = 0.207
g = 9.8
NumPoints = 200
t0 = 0.0
t = 30
time = np.linspace(... | Simulating Freefall with Drag.py | #INVESTIGATING FREEFALL USING THE EULER METHOD
#-----------------------------------------------------------
#PART A
#-----------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
y0 = 1000
m = 70
k = 0.207
g = 9.8
NumPoints = 200
t0 = 0.0
t = 30
time = np.linspace(... | 0.488283 | 0.526951 |
import tensorflow as tf
def _make_3layer_name(base):
return f"{base}a", f"{base}b", f"{base}c"
def _normalized_conv2d(inputs, filters, kernel_size, strides, padding='valid', name=""):
conv = tf.layers.conv2d(inputs, filters, kernel_size, strides, padding, name=name)
norm = tf.layers.batch_normalization(... | ResNet101.py | import tensorflow as tf
def _make_3layer_name(base):
return f"{base}a", f"{base}b", f"{base}c"
def _normalized_conv2d(inputs, filters, kernel_size, strides, padding='valid', name=""):
conv = tf.layers.conv2d(inputs, filters, kernel_size, strides, padding, name=name)
norm = tf.layers.batch_normalization(... | 0.92345 | 0.374705 |
import sys
import re
import os
import pandas as pd
import numpy as np
import gzip
import time
import json
from optparse import OptionParser
from datetime import date, timedelta
from exio.authClient import AuthenticatedClient
from exio.websocketClient import WebsocketClient
class Client(object):
def __init__(self, ke... | examples/exio_cli.py | import sys
import re
import os
import pandas as pd
import numpy as np
import gzip
import time
import json
from optparse import OptionParser
from datetime import date, timedelta
from exio.authClient import AuthenticatedClient
from exio.websocketClient import WebsocketClient
class Client(object):
def __init__(self, ke... | 0.315947 | 0.092852 |
import ctypes
import gc
import unittest
from clang.cindex import AvailabilityKind
from clang.cindex import CursorKind
from clang.cindex import TemplateArgumentKind
from clang.cindex import TranslationUnit
from clang.cindex import TypeKind
from .util import get_cursor
from .util import get_cursors
from .util import get... | roxe.cdt/roxe_llvm/tools/clang/bindings/python/tests/cindex/test_cursor.py | import ctypes
import gc
import unittest
from clang.cindex import AvailabilityKind
from clang.cindex import CursorKind
from clang.cindex import TemplateArgumentKind
from clang.cindex import TranslationUnit
from clang.cindex import TypeKind
from .util import get_cursor
from .util import get_cursors
from .util import get... | 0.574395 | 0.337572 |
import socket
import argparse
import sys
parser = argparse.ArgumentParser(description="Resolve required AMP Addresses to IPs.")
parser.add_argument('--NAM', action="store_true", help="Display IPs for AMP North America.")
parser.add_argument('--EU', action="store_true", help="Display IPs for AMP Europe.")
parser.add_ar... | Resolve_IPs/resolve_IPs.py | import socket
import argparse
import sys
parser = argparse.ArgumentParser(description="Resolve required AMP Addresses to IPs.")
parser.add_argument('--NAM', action="store_true", help="Display IPs for AMP North America.")
parser.add_argument('--EU', action="store_true", help="Display IPs for AMP Europe.")
parser.add_ar... | 0.223886 | 0.128197 |
import logging
import xml.etree.ElementTree as ET
import chc.util.fileutil as UF
import chc.util.xmlutil as UX
fidvidmax_initial_value = 1000000
"""
TODO:
- save gxrefs file if new vid's were added to a file
"""
class IndexManager(object):
def __init__(self, issinglefile):
self.issinglefile = issing... | chc/app/IndexManager.py |
import logging
import xml.etree.ElementTree as ET
import chc.util.fileutil as UF
import chc.util.xmlutil as UX
fidvidmax_initial_value = 1000000
"""
TODO:
- save gxrefs file if new vid's were added to a file
"""
class IndexManager(object):
def __init__(self, issinglefile):
self.issinglefile = issing... | 0.383064 | 0.116991 |
import sys
import os
import time
import atexit
import logging
from signal import SIGTERM
class Daemon(object):
"""Class to demonize the application
Args:
pidfile (str): path for the pidfile
stdin (Optional[str]): path to stdin. Default to /dev/null
stdout (Optional[str]): path to std... | mymongolib/daemon.py | import sys
import os
import time
import atexit
import logging
from signal import SIGTERM
class Daemon(object):
"""Class to demonize the application
Args:
pidfile (str): path for the pidfile
stdin (Optional[str]): path to stdin. Default to /dev/null
stdout (Optional[str]): path to std... | 0.274351 | 0.114715 |
import os
from pprint import pformat, pprint
from typing import Dict, Iterator, Tuple, Union
import numpy as np
from tensorboardX import SummaryWriter
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from torch.optim import Adam
from torch.optim.optimizer import Op... | module/trainer.py | import os
from pprint import pformat, pprint
from typing import Dict, Iterator, Tuple, Union
import numpy as np
from tensorboardX import SummaryWriter
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from torch.optim import Adam
from torch.optim.optimizer import Op... | 0.862641 | 0.487856 |
import re
import os
from collections import defaultdict
import pickle as pk
from typing import Dict
import pandas as pd
import pylab as pl
from curves.t_rate_list_format import TimeSeriesSingle
_dir, _ = os.path.split(__file__)
def init_pickles(per_str, resolution_str):
chunks = []
currency_2_curve = defau... | datasets/yahoo/unified_format.py | import re
import os
from collections import defaultdict
import pickle as pk
from typing import Dict
import pandas as pd
import pylab as pl
from curves.t_rate_list_format import TimeSeriesSingle
_dir, _ = os.path.split(__file__)
def init_pickles(per_str, resolution_str):
chunks = []
currency_2_curve = defau... | 0.729712 | 0.169131 |
from torchvision import transforms
from utils import *
from PIL import Image, ImageDraw, ImageFont
from datasets import GTSDBDataset
from tqdm import tqdm
from pprint import PrettyPrinter
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Good formatting when printing the APs for each class and m... | SRC/my_eval.py | from torchvision import transforms
from utils import *
from PIL import Image, ImageDraw, ImageFont
from datasets import GTSDBDataset
from tqdm import tqdm
from pprint import PrettyPrinter
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Good formatting when printing the APs for each class and m... | 0.891817 | 0.408513 |
class WinUtil:
# wmi_conn = wmi.WMI() for local.
@staticmethod
def get_all_installed_win10_store():
import wmi
results = {}
try:
wmi_conn = wmi.WMI()
for info in wmi_conn.Win32_InstalledStoreProgram():
if '-' in info.Name: continue
... | falconcv/util/win_util.py | class WinUtil:
# wmi_conn = wmi.WMI() for local.
@staticmethod
def get_all_installed_win10_store():
import wmi
results = {}
try:
wmi_conn = wmi.WMI()
for info in wmi_conn.Win32_InstalledStoreProgram():
if '-' in info.Name: continue
... | 0.244724 | 0.082512 |
import json
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
boto_config = Config(
retries = {
'mode': 'standard',
'max_attempts': 10
}
)
def connect_to_ec2(boto_config):
return boto3.client('ec2', config=boto_config)
def get_pub... | source/remediation_runbooks/scripts/GetPublicEBSSnapshots.py |
import json
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
boto_config = Config(
retries = {
'mode': 'standard',
'max_attempts': 10
}
)
def connect_to_ec2(boto_config):
return boto3.client('ec2', config=boto_config)
def get_pub... | 0.417628 | 0.282394 |
import markdown
from django import template
from library import tag_utils
from library.tag_utils import get_passed_objects
register = template.Library()
@register.tag
def render_node_text(_parser, token):
return NodeTextDescriptionTag(tag_utils.get_passed_object(token))
@register.tag
def render_dataframe(_par... | snpdb/templatetags/text_tags.py | import markdown
from django import template
from library import tag_utils
from library.tag_utils import get_passed_objects
register = template.Library()
@register.tag
def render_node_text(_parser, token):
return NodeTextDescriptionTag(tag_utils.get_passed_object(token))
@register.tag
def render_dataframe(_par... | 0.352313 | 0.136637 |
import numpy as np
from src.data import Problem, Case, Matter
def is_monotone(color_dict):
a = -1000
b = -1000
v = -1000
for k in sorted(color_dict.keys()):
if color_dict[k] != v:
v = color_dict[k]
if a == -1000:
a = k
elif b == -1000:
... | src/operator/solver/dynamic/color/auto_paste_a.py | import numpy as np
from src.data import Problem, Case, Matter
def is_monotone(color_dict):
a = -1000
b = -1000
v = -1000
for k in sorted(color_dict.keys()):
if color_dict[k] != v:
v = color_dict[k]
if a == -1000:
a = k
elif b == -1000:
... | 0.334481 | 0.486454 |
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@p... | modelci/types/proto/service_pb2.py |
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@p... | 0.224991 | 0.114171 |
import numpy as np
import os
import pickle
import random
import sys
import tensorflow as tf
import time
#Import functions and classes
from tensorflow.keras import backend as K
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.preprocessing.sequence imp... | backend/chatbot/model_2/training/training.py | import numpy as np
import os
import pickle
import random
import sys
import tensorflow as tf
import time
#Import functions and classes
from tensorflow.keras import backend as K
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.preprocessing.sequence imp... | 0.470007 | 0.296062 |
import argparse
import ast
import sys
from datetime import datetime
import logging
from .. import set_handler, __version__
from ..sync.client import read_write_read
from .._log import _set_handler_with_logger
from .._utils import ShowVersionAction
def main():
parser = argparse.ArgumentParser(description='Write a ... | caproto/commandline/put.py | import argparse
import ast
import sys
from datetime import datetime
import logging
from .. import set_handler, __version__
from ..sync.client import read_write_read
from .._log import _set_handler_with_logger
from .._utils import ShowVersionAction
def main():
parser = argparse.ArgumentParser(description='Write a ... | 0.230054 | 0.069164 |
from io import StringIO
import numpy as np
import rxcclib.file.Gaussian as rxfile
class DihdFunction(object):
def __init__(self, periodicity, phase, forceconst, npaths, dihd):
self.periodicity = periodicity
self.forceconst = forceconst
self.phase = phase
self.npaths = npaths
... | file/GauAmberCOM.py | from io import StringIO
import numpy as np
import rxcclib.file.Gaussian as rxfile
class DihdFunction(object):
def __init__(self, periodicity, phase, forceconst, npaths, dihd):
self.periodicity = periodicity
self.forceconst = forceconst
self.phase = phase
self.npaths = npaths
... | 0.466481 | 0.220941 |
# note: the string translate() method would be the high-performance solution
# the string module has some handy constants.
import string
# a few handy constants:
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
def rot13a(text):
"""
A brute force solution
"""
# loop through the letters in the inp... | Solutions/rot_13/rot13.py | # note: the string translate() method would be the high-performance solution
# the string module has some handy constants.
import string
# a few handy constants:
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
def rot13a(text):
"""
A brute force solution
"""
# loop through the letters in the inp... | 0.536799 | 0.536495 |
import os
import json
import cloudstorage as gcs
import datetime
from flask import Blueprint, request, session
from flask_principal import Permission, RoleNeed
from werkzeug.exceptions import HTTPException, Forbidden
from google.appengine.api import app_identity
from google.appengine.api import mail
from credit.mode... | python/credit/controller.py | import os
import json
import cloudstorage as gcs
import datetime
from flask import Blueprint, request, session
from flask_principal import Permission, RoleNeed
from werkzeug.exceptions import HTTPException, Forbidden
from google.appengine.api import app_identity
from google.appengine.api import mail
from credit.mode... | 0.260013 | 0.048451 |
import random
import copy
boardsize = 4
def display():
largest = board[0][0]
for row in board:
for element in row:
if element > largest:
largest = element
numSpace = len(str(largest))
for row in board:
currentRow = "|"
for element in ro... | 2048 game final.py | import random
import copy
boardsize = 4
def display():
largest = board[0][0]
for row in board:
for element in row:
if element > largest:
largest = element
numSpace = len(str(largest))
for row in board:
currentRow = "|"
for element in ro... | 0.056236 | 0.225204 |
from unittest.mock import patch
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase, Client
import server.utils
from sal.plugin import Widget, ReportPlugin, DetailPlugin
from server.models import Plugin, Report, MachineDetailPlugin
class WidgetSettingsTest(T... | server/tests/test_settings_views.py | from unittest.mock import patch
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase, Client
import server.utils
from sal.plugin import Widget, ReportPlugin, DetailPlugin
from server.models import Plugin, Report, MachineDetailPlugin
class WidgetSettingsTest(T... | 0.710829 | 0.167627 |
from slackclient import SlackClient
from chatterbot.output import OutputAdapter
from client.services import EventManager
class Slack(OutputAdapter):
"""
An input adapter that allows a ChatterBot instance to send responses via a
Slack Bot User using *Slack API*. The adapter sends to the channel the last
... | client/client/output/slack.py | from slackclient import SlackClient
from chatterbot.output import OutputAdapter
from client.services import EventManager
class Slack(OutputAdapter):
"""
An input adapter that allows a ChatterBot instance to send responses via a
Slack Bot User using *Slack API*. The adapter sends to the channel the last
... | 0.78016 | 0.209793 |
import os
# os.environ['TL_BACKEND'] = 'paddle'
# os.environ['CUDA_VISIBLE_DEVICES'] = ' '
# set your backend here, default `tensorflow`, you can choose 'paddle'、'tensorflow'、'torch'
from gammagl.datasets import TUDataset
from tqdm import tqdm
import tensorlayerx as tlx
import argparse
from tensorlayerx.model import T... | examples/infograph/infograph_trainer.py | import os
# os.environ['TL_BACKEND'] = 'paddle'
# os.environ['CUDA_VISIBLE_DEVICES'] = ' '
# set your backend here, default `tensorflow`, you can choose 'paddle'、'tensorflow'、'torch'
from gammagl.datasets import TUDataset
from tqdm import tqdm
import tensorlayerx as tlx
import argparse
from tensorlayerx.model import T... | 0.41561 | 0.175361 |
import pytest
from freezegun import freeze_time
from scorekeeper import Scorekeeper
from scorekeeper import score
tmp_path = None
current_test = None
@pytest.fixture(autouse=True)
def mock_shelve_path(request, tmpdir, monkeypatch):
global tmp_path
global current_test
if not current_test or current_tes... | tests/test_scorekeeper.py | import pytest
from freezegun import freeze_time
from scorekeeper import Scorekeeper
from scorekeeper import score
tmp_path = None
current_test = None
@pytest.fixture(autouse=True)
def mock_shelve_path(request, tmpdir, monkeypatch):
global tmp_path
global current_test
if not current_test or current_tes... | 0.389082 | 0.423398 |
from __future__ import absolute_import, print_function
import click
import base64
import tempfile
import uuid
from tomaat.core.service import TOMAATService
import time
import tensorflow as tf
from util.data_loader import *
from util.train_test_func import *
from util.parse_config import parse_config
from train import... | serve.py | from __future__ import absolute_import, print_function
import click
import base64
import tempfile
import uuid
from tomaat.core.service import TOMAATService
import time
import tensorflow as tf
from util.data_loader import *
from util.train_test_func import *
from util.parse_config import parse_config
from train import... | 0.68616 | 0.106924 |
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('amcm', '0035_auto_20220105_2106'),
]
operations = [
migrations.AlterField(
model_name='credito',
... | apps/amcm/migrations/0036_auto_20220105_2131.py |
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('amcm', '0035_auto_20220105_2106'),
]
operations = [
migrations.AlterField(
model_name='credito',
... | 0.478529 | 0.172172 |
from sstcam_sandbox.d181106_tf_investigations import all_files
from sstcam_sandbox import HDF5Writer, HDF5Reader
import pandas as pd
from tqdm import tqdm
from CHECLabPy.utils.files import open_runlist_dl1
import numpy as np
def rmse(measured, true):
return np.sqrt(np.sum(np.power(measured - true, 2)) / measured.... | sstcam_sandbox/d181106_tf_investigations/extract_stats.py | from sstcam_sandbox.d181106_tf_investigations import all_files
from sstcam_sandbox import HDF5Writer, HDF5Reader
import pandas as pd
from tqdm import tqdm
from CHECLabPy.utils.files import open_runlist_dl1
import numpy as np
def rmse(measured, true):
return np.sqrt(np.sum(np.power(measured - true, 2)) / measured.... | 0.439988 | 0.318936 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import unittest
import os
import functools
import numpy as np
import pims
from numpy.testing import assert_array_equal
from pims import plot_to_frame, plots_to_frame
from pims.display import export_m... | pims/tests/test_display.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import unittest
import os
import functools
import numpy as np
import pims
from numpy.testing import assert_array_equal
from pims import plot_to_frame, plots_to_frame
from pims.display import export_m... | 0.661814 | 0.51812 |
left_motor = 47246689260697394641558
right_motor = 47251723202529841910772
intake = 47254408925743638880954
shooter = 47252346776555950902602
door = 47251015244498422263341
def autonomous_setup():
#Robot.set_value(right_motor, "duty_cycle", 1)
#Robot.set_value(left_motor, "duty_cycle", 1)
#Robot... | staff-bots/mech_sweep.py | left_motor = 47246689260697394641558
right_motor = 47251723202529841910772
intake = 47254408925743638880954
shooter = 47252346776555950902602
door = 47251015244498422263341
def autonomous_setup():
#Robot.set_value(right_motor, "duty_cycle", 1)
#Robot.set_value(left_motor, "duty_cycle", 1)
#Robot... | 0.195786 | 0.258803 |
import time
import pytest
from webdriver import error
from webdriver.transport import Response
from tests.support import platform_name
from tests.support.asserts import assert_error, assert_success
def navigate_to(session, url):
return session.transport.send(
"POST", "session/{session_id}/url".format(**... | webdriver/tests/navigate_to/navigate.py | import time
import pytest
from webdriver import error
from webdriver.transport import Response
from tests.support import platform_name
from tests.support.asserts import assert_error, assert_success
def navigate_to(session, url):
return session.transport.send(
"POST", "session/{session_id}/url".format(**... | 0.611034 | 0.369116 |
import os
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import gui
from gui.constants import DARK_THEMES
def path_to_dark_path(path):
parts = path.split(".")
parts[-2] += "-dark"
return ".".join(parts)
class DynamicIcon(QIcon):
def __init__(self, path):
... | gui/dynamic_widgets.py | import os
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import gui
from gui.constants import DARK_THEMES
def path_to_dark_path(path):
parts = path.split(".")
parts[-2] += "-dark"
return ".".join(parts)
class DynamicIcon(QIcon):
def __init__(self, path):
... | 0.561215 | 0.074635 |
from __future__ import absolute_import, unicode_literals
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse_lazy
from django.views.generic import DetailView, ListView, RedirectView, UpdateView, CreateView, DeleteView
from braces.views import LoginRequiredMixin
from rest_framew... | urlshortener_project/urlshortener/views.py | from __future__ import absolute_import, unicode_literals
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse_lazy
from django.views.generic import DetailView, ListView, RedirectView, UpdateView, CreateView, DeleteView
from braces.views import LoginRequiredMixin
from rest_framew... | 0.487063 | 0.067824 |
import unittest
from unittest.mock import patch, call
import sys
from Launcher import Launcher
class Test_environment(unittest.TestCase):
"""Test the environment to ensure it will match production."""
def test_python_version(self):
"""Make sure the python version is 3.x."""
self.assertGreater... | test_Launcher.py | import unittest
from unittest.mock import patch, call
import sys
from Launcher import Launcher
class Test_environment(unittest.TestCase):
"""Test the environment to ensure it will match production."""
def test_python_version(self):
"""Make sure the python version is 3.x."""
self.assertGreater... | 0.632503 | 0.591959 |
import datetime
import pytest
from housekeeper.date import get_date, match_date
def test_match_date_dash():
"""Test to match common string formated date"""
# GIVEN a datestring separated by '-'
date_str = "2015-05-10"
# WHEN checking if it is a valid datestring
res = match_date(date_str)
# T... | tests/test_date.py | import datetime
import pytest
from housekeeper.date import get_date, match_date
def test_match_date_dash():
"""Test to match common string formated date"""
# GIVEN a datestring separated by '-'
date_str = "2015-05-10"
# WHEN checking if it is a valid datestring
res = match_date(date_str)
# T... | 0.561696 | 0.528351 |
import json
from django.http import HttpResponseBadRequest, JsonResponse
import ethik
import pandas as pd
from sklearn import metrics
from .utils import fig_to_json, interp_color, read_ds
# TODO: let the user choose
METRIC = metrics.accuracy_score
N_SAMPLES = 30
def check_dataset(request):
try:
body = ... | api/views.py | import json
from django.http import HttpResponseBadRequest, JsonResponse
import ethik
import pandas as pd
from sklearn import metrics
from .utils import fig_to_json, interp_color, read_ds
# TODO: let the user choose
METRIC = metrics.accuracy_score
N_SAMPLES = 30
def check_dataset(request):
try:
body = ... | 0.285671 | 0.288134 |
import MySQLdb as Sql
import logging
import datetime
from threading import Lock
__author__ = '<NAME>'
__description__ = 'Database access management / API'
__copyright__ = "Copyright 2016"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "in development"
TABLE_PLAYTIME = 'playtime'
TAB... | database.py |
import MySQLdb as Sql
import logging
import datetime
from threading import Lock
__author__ = '<NAME>'
__description__ = 'Database access management / API'
__copyright__ = "Copyright 2016"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "in development"
TABLE_PLAYTIME = 'playtime'
TAB... | 0.276495 | 0.046725 |
import os
import json
import argparse
from sklearn import metrics
def align(*args):
keys = None
for a in args:
if keys is not None:
keys &= set(a.keys())
else:
keys = set(a.keys())
return [[a[k] for k in keys] for a in args]
if __name__ == "__main__":
parse... | evaluation/scripts/performance/compare.py | import os
import json
import argparse
from sklearn import metrics
def align(*args):
keys = None
for a in args:
if keys is not None:
keys &= set(a.keys())
else:
keys = set(a.keys())
return [[a[k] for k in keys] for a in args]
if __name__ == "__main__":
parse... | 0.672654 | 0.265648 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.BigAutoField(auto_create... | app/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='Customer',
fields=[
('id', models.BigAutoField(auto_create... | 0.522446 | 0.199211 |
import datetime
import locale
import re
from . import log
# MIN/MAX year for which we generate events
MINYEAR = 1980
MAXYEAR = 2100
def yearText(n):
loc = locale.getlocale()
if isinstance(loc, tuple):
loc = loc[0]
if loc and loc.startswith('da'):
yt = '%d år', '%d år'
elif loc and lo... | dpc/events.py | import datetime
import locale
import re
from . import log
# MIN/MAX year for which we generate events
MINYEAR = 1980
MAXYEAR = 2100
def yearText(n):
loc = locale.getlocale()
if isinstance(loc, tuple):
loc = loc[0]
if loc and loc.startswith('da'):
yt = '%d år', '%d år'
elif loc and lo... | 0.373304 | 0.196903 |
COMPLETE_A = """\
[build-system]
requires = [ "whey",]
build-backend = "whey"
[project]
name = "whey"
version = "2021.0.0"
description = "A simple Python wheel builder for simple projects."
keywords = [ "pep517", "pep621", "build", "sdist", "wheel", "packaging", "distribution",]
dynamic = [ "classifiers", "requires-py... | tests/example_configs.py | COMPLETE_A = """\
[build-system]
requires = [ "whey",]
build-backend = "whey"
[project]
name = "whey"
version = "2021.0.0"
description = "A simple Python wheel builder for simple projects."
keywords = [ "pep517", "pep621", "build", "sdist", "wheel", "packaging", "distribution",]
dynamic = [ "classifiers", "requires-py... | 0.519278 | 0.232354 |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from uuid import uuid4
# Create your models here.
@python_2_unicode_compatible
class Banner(models.Model):
''' Banner '''
... | djwechat/portfolio/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from uuid import uuid4
# Create your models here.
@python_2_unicode_compatible
class Banner(models.Model):
''' Banner '''
... | 0.488283 | 0.066176 |
from abc import ABCMeta, abstractmethod
import logging
from time import sleep
import requests
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
class AbstractExecutor(object):
"""Base class for executor that runs jobs remotely."""
__metaclass__ = ABCMeta
@abstractmethod
def __init_... | nest_py/knoweng/jobs/abstract_executor.py | from abc import ABCMeta, abstractmethod
import logging
from time import sleep
import requests
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
class AbstractExecutor(object):
"""Base class for executor that runs jobs remotely."""
__metaclass__ = ABCMeta
@abstractmethod
def __init_... | 0.708112 | 0.171096 |
from config.api2_0_config import *
from on_http_api2_0 import ApiApi as WorkflowApi
from on_http_api2_0 import rest
from modules.logger import Log
from datetime import datetime
from proboscis.asserts import *
from proboscis import SkipTest
from proboscis import test
from json import dumps, loads
import json
LOG = Log... | test/tests/api/v2_0/workflowTasks_tests.py | from config.api2_0_config import *
from on_http_api2_0 import ApiApi as WorkflowApi
from on_http_api2_0 import rest
from modules.logger import Log
from datetime import datetime
from proboscis.asserts import *
from proboscis import SkipTest
from proboscis import test
from json import dumps, loads
import json
LOG = Log... | 0.378344 | 0.208904 |
import os
import sys
import unittest
from conans.client import tools
from conans.client.output import ConanOutput
from conans.test.utils.test_files import temp_folder
from conans.test.utils.tools import TestClient
from conans.test.utils.mocks import TestBufferConanOutput
from conans.util.files import load, save
from ... | conans/test/unittests/util/conanfile_tools_test.py | import os
import sys
import unittest
from conans.client import tools
from conans.client.output import ConanOutput
from conans.test.utils.test_files import temp_folder
from conans.test.utils.tools import TestClient
from conans.test.utils.mocks import TestBufferConanOutput
from conans.util.files import load, save
from ... | 0.180431 | 0.155687 |
import argparse
import os
import subprocess
def _cli():
parser = generate_parser()
args = parser.parse_args()
kwargs = _args2spec(args)
return interface(**kwargs)
def _args2spec(args):
return vars(args)
def generate_parser(parser=None):
if not parser:
parser = argparse.ArgumentP... | PreFreeSurfer/scripts/atropos_refine_mask.py | import argparse
import os
import subprocess
def _cli():
parser = generate_parser()
args = parser.parse_args()
kwargs = _args2spec(args)
return interface(**kwargs)
def _args2spec(args):
return vars(args)
def generate_parser(parser=None):
if not parser:
parser = argparse.ArgumentP... | 0.455925 | 0.162546 |
import time
import uuid
import base64
import urllib.parse
import hashlib
import requests
from gl import Global
def get_file_content(file_path):
with open(file_path, "rb") as fp:
return fp.read()
def get_exp_account():
url = Global.config.get_value("experience_account_url")
t = int(time.time())
... | ocrapi.py |
import time
import uuid
import base64
import urllib.parse
import hashlib
import requests
from gl import Global
def get_file_content(file_path):
with open(file_path, "rb") as fp:
return fp.read()
def get_exp_account():
url = Global.config.get_value("experience_account_url")
t = int(time.time())
... | 0.492676 | 0.155271 |
from collections import namedtuple
from datetime import datetime
from typing import List
import requests
Success = namedtuple("Success", ["RowAffected"])
class GorseException(BaseException):
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message... | backend/gorse.py | from collections import namedtuple
from datetime import datetime
from typing import List
import requests
Success = namedtuple("Success", ["RowAffected"])
class GorseException(BaseException):
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message... | 0.734024 | 0.165897 |
import pytest
import ast
import textwrap
import inspect
import os
import HartreeParticleDSL.HartreeParticleDSL as HartreeParticleDSL
from HartreeParticleDSL.HartreeParticleDSLExceptions import SingletonInstanceError, \
RepeatedNameError, \
... | src/HartreeParticleDSL/test/test_HartreeParticleDSL.py | import pytest
import ast
import textwrap
import inspect
import os
import HartreeParticleDSL.HartreeParticleDSL as HartreeParticleDSL
from HartreeParticleDSL.HartreeParticleDSLExceptions import SingletonInstanceError, \
RepeatedNameError, \
... | 0.474388 | 0.452657 |
class Protocol:
"""A Pharmokinetic (PK) dosing protocol
Allows for continuous or instantaneous (at one or more time points) dosing.
Also allows to set up the dose X in ng.
Parameters
----------
dose_amount: numeric, optional, default=1
This parameter takes in the amount of dose given -... | pkmodel/protocol.py |
class Protocol:
"""A Pharmokinetic (PK) dosing protocol
Allows for continuous or instantaneous (at one or more time points) dosing.
Also allows to set up the dose X in ng.
Parameters
----------
dose_amount: numeric, optional, default=1
This parameter takes in the amount of dose given -... | 0.944498 | 0.816553 |
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Device, Command, Measured, DeviceTracking, UserPreference, Notification
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
mo... | monitor/monitor_engine/serializers.py | from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Device, Command, Measured, DeviceTracking, UserPreference, Notification
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
mo... | 0.311008 | 0.058373 |
from utils import nft_utils
from utils.nft_errors import NFTError, Error
from parsers import table_parser
from wrappers import chain_wrapper, set_wrapper, dictionary_wrapper
def list_all_tables():
tables = table_parser.parse_tables(nft_utils.nft_get_json_command())
chains = chain_wrapper.list_all_chains()
... | nftserver/app/wrappers/table_wrapper.py | from utils import nft_utils
from utils.nft_errors import NFTError, Error
from parsers import table_parser
from wrappers import chain_wrapper, set_wrapper, dictionary_wrapper
def list_all_tables():
tables = table_parser.parse_tables(nft_utils.nft_get_json_command())
chains = chain_wrapper.list_all_chains()
... | 0.338405 | 0.102979 |
import fmodpy
import os
import numpy as np
_this_dir = os.path.dirname(os.path.abspath(__file__))
# Build a class that contains pointers to the model internals, allowing
# python attribute access to all of the different components of the models.
class AposModel:
def __init__(self, config, model):
self.conf... | tlux/approximate/apos/test/compare_versions.py | import fmodpy
import os
import numpy as np
_this_dir = os.path.dirname(os.path.abspath(__file__))
# Build a class that contains pointers to the model internals, allowing
# python attribute access to all of the different components of the models.
class AposModel:
def __init__(self, config, model):
self.conf... | 0.270191 | 0.122078 |
import binascii
import socket
import struct
ETH_BROADCAST = 'ff:ff:ff:ff:ff:ff'
ETH_TYPE_ARP = 0x0806
eth_length = 14
arp_length = 28
def parse_packet(packet):
eth_frame = parse_eth_frame(packet[0:eth_length])
arp_packet = parse_arp_packet(packet[eth_length:(eth_length+arp_length)])
return eth_frame, ar... | arproxy/utils.py | import binascii
import socket
import struct
ETH_BROADCAST = 'ff:ff:ff:ff:ff:ff'
ETH_TYPE_ARP = 0x0806
eth_length = 14
arp_length = 28
def parse_packet(packet):
eth_frame = parse_eth_frame(packet[0:eth_length])
arp_packet = parse_arp_packet(packet[eth_length:(eth_length+arp_length)])
return eth_frame, ar... | 0.248079 | 0.283512 |
import feedparser
import sys
import operator
import re
import urllib2
from lxml import etree
from os import path, mkdir, remove
from glob import glob
from random import shuffle
from subprocess import *
from datetime import date, datetime, timedelta
from AINewsTools import savefile
from AINewsConfig import config, path... | AINewsPublisher.py |
import feedparser
import sys
import operator
import re
import urllib2
from lxml import etree
from os import path, mkdir, remove
from glob import glob
from random import shuffle
from subprocess import *
from datetime import date, datetime, timedelta
from AINewsTools import savefile
from AINewsConfig import config, path... | 0.284477 | 0.044953 |
import setpath
import functions
import json
import re
import itertools
registered=True
class residualscomputation(functions.vtable.vtbase.VT):
def VTiter(self, *parsedArgs,**envars):
largs, dictargs = self.full_parse(parsedArgs)
if 'query' not in dictargs:
raise functions.OperatorErro... | Exareme-Docker/src/exareme/exareme-tools/madis/src/functionslocal/vtable/residualscomputation.py | import setpath
import functions
import json
import re
import itertools
registered=True
class residualscomputation(functions.vtable.vtbase.VT):
def VTiter(self, *parsedArgs,**envars):
largs, dictargs = self.full_parse(parsedArgs)
if 'query' not in dictargs:
raise functions.OperatorErro... | 0.121895 | 0.238683 |
import json
import os.path
import sys
import common
from utils import download_archive, ensure_dir_exists, export_csv
# Latest dump of the OpenChargeMap database
DATASET_URL = 'https://github.com/openchargemap/ocm-data/blob/master/poi.json.gz?raw=true'
DATASET_ARCHIVE = 'poi.json.gz'
DATASET_NAME = 'poi.json'
# Ref... | src/openchargemap.py | import json
import os.path
import sys
import common
from utils import download_archive, ensure_dir_exists, export_csv
# Latest dump of the OpenChargeMap database
DATASET_URL = 'https://github.com/openchargemap/ocm-data/blob/master/poi.json.gz?raw=true'
DATASET_ARCHIVE = 'poi.json.gz'
DATASET_NAME = 'poi.json'
# Ref... | 0.425367 | 0.190366 |
import numpy as np
from tqdm.autonotebook import trange
import torch
import torch.nn as nn
from matgps.segments import WeightedAttention, SimpleNetwork, ResidualNetwork
from matgps.utils import AverageMeter
class ReactionNet(nn.Module):
"""
Create a neural network for predicting elements in product from pr... | matgps/reaction_graph/model.py | import numpy as np
from tqdm.autonotebook import trange
import torch
import torch.nn as nn
from matgps.segments import WeightedAttention, SimpleNetwork, ResidualNetwork
from matgps.utils import AverageMeter
class ReactionNet(nn.Module):
"""
Create a neural network for predicting elements in product from pr... | 0.93485 | 0.574275 |
from __future__ import division
import numpy as np
from numbapro import cuda
import numbapro.cudalib.cublas as cublas
from numba import *
import math
@cuda.jit('void(f4[:,:],i8[:,:],i8)')
def removeWinners(curCoef,winners,jj):
i = cuda.grid(1)
for k in xrange(jj-1):
curCoef[i,winners[k,i]] = 0.
@cuda.... | MPnumbaprog.py | from __future__ import division
import numpy as np
from numbapro import cuda
import numbapro.cudalib.cublas as cublas
from numba import *
import math
@cuda.jit('void(f4[:,:],i8[:,:],i8)')
def removeWinners(curCoef,winners,jj):
i = cuda.grid(1)
for k in xrange(jj-1):
curCoef[i,winners[k,i]] = 0.
@cuda.... | 0.442396 | 0.47993 |
import os
import collections
import queue
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union, cast
import numpy as np
from loguru import logger
from typing_extensions import Literal
import carla
from .. import physics, process
from ..utils.carla_image import carla_image_to_np
fro... | intervention/carla_utils/manager.py | import os
import collections
import queue
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union, cast
import numpy as np
from loguru import logger
from typing_extensions import Literal
import carla
from .. import physics, process
from ..utils.carla_image import carla_image_to_np
fro... | 0.908779 | 0.349866 |
"""Global fixtures for integration."""
from unittest.mock import MagicMock, Mock, patch
import pytest
from midea_beautiful.exceptions import CloudAuthenticationError, MideaError
from midea_beautiful.midea import APPLIANCE_TYPE_DEHUMIDIFIER, APPLIANCE_TYPE_AIRCON
from custom_components.midea_dehumidifier_lan.util im... | tests/conftest.py | """Global fixtures for integration."""
from unittest.mock import MagicMock, Mock, patch
import pytest
from midea_beautiful.exceptions import CloudAuthenticationError, MideaError
from midea_beautiful.midea import APPLIANCE_TYPE_DEHUMIDIFIER, APPLIANCE_TYPE_AIRCON
from custom_components.midea_dehumidifier_lan.util im... | 0.849784 | 0.302468 |
from pywikibot import Site
from pywikibot.data.sparql import SparqlQuery
from properties import wikidata_properties as wp
def episodes(season_id):
"""Find episodes for a given season (specified by QID)
Returns an iterable of (season ordinal, episode QID, episode title)
"""
query = f"""
SELEC... | sparql/queries.py | from pywikibot import Site
from pywikibot.data.sparql import SparqlQuery
from properties import wikidata_properties as wp
def episodes(season_id):
"""Find episodes for a given season (specified by QID)
Returns an iterable of (season ordinal, episode QID, episode title)
"""
query = f"""
SELEC... | 0.746878 | 0.357792 |
class GraphRenderer:
'''
Only a "renderer" knows how big each node will end up based on metadata
in the graph which is specific to the renderer.
All renderers should be able to set the (x,y) "size" tuple
'''
def __init__(self, graph):
self._vg_graph = graph
self._vg_layout = Non... | visgraph/renderers/__init__.py | class GraphRenderer:
'''
Only a "renderer" knows how big each node will end up based on metadata
in the graph which is specific to the renderer.
All renderers should be able to set the (x,y) "size" tuple
'''
def __init__(self, graph):
self._vg_graph = graph
self._vg_layout = Non... | 0.753648 | 0.552962 |
import argparse
import os
import pickle
import time
from importlib import import_module
from multiprocessing import Pool
from mindspore.mindrecord import FileWriter
def _exec_task(task_id, parallel_writer=True):
"""
Execute task with specified task id
"""
print("exec task {}, parallel: {} ...".format... | example/cv_to_mindrecord/ImageNet_Similar_Perf/writer.py | import argparse
import os
import pickle
import time
from importlib import import_module
from multiprocessing import Pool
from mindspore.mindrecord import FileWriter
def _exec_task(task_id, parallel_writer=True):
"""
Execute task with specified task id
"""
print("exec task {}, parallel: {} ...".format... | 0.260107 | 0.090454 |
from functools import partial
from jax import numpy as jnp
import numpyro
from numpyro.distributions.discrete import PRNGIdentity
def flax_module(name, nn, input_shape=None):
"""
Declare a :mod:`~flax` style neural network inside a
model so that its parameters are registered for optimization via
:f... | numpyro/contrib/module.py |
from functools import partial
from jax import numpy as jnp
import numpyro
from numpyro.distributions.discrete import PRNGIdentity
def flax_module(name, nn, input_shape=None):
"""
Declare a :mod:`~flax` style neural network inside a
model so that its parameters are registered for optimization via
:f... | 0.940551 | 0.436262 |
import pandas.util.testing as tm
import pytest
from pandas import DataFrame
from pandas.compat.numpy import np_datetime64_compat
import pandas_gbq.exceptions
from pandas_gbq import gbq
try:
import mock
except ImportError: # pragma: NO COVER
from unittest import mock
@pytest.fixture
def min_bq_version():
... | tests/unit/test_gbq.py |
import pandas.util.testing as tm
import pytest
from pandas import DataFrame
from pandas.compat.numpy import np_datetime64_compat
import pandas_gbq.exceptions
from pandas_gbq import gbq
try:
import mock
except ImportError: # pragma: NO COVER
from unittest import mock
@pytest.fixture
def min_bq_version():
... | 0.327991 | 0.343452 |
import logging
logger = logging.getLogger(__name__)
from nymms.schemas import types
def always_true(result, previous_state):
""" Not really necessary since no filters results in an always true result,
but this is useful to show an example of what a filter is without actually
doing anything.
"""
... | nymms/reactor/filters/__init__.py | import logging
logger = logging.getLogger(__name__)
from nymms.schemas import types
def always_true(result, previous_state):
""" Not really necessary since no filters results in an always true result,
but this is useful to show an example of what a filter is without actually
doing anything.
"""
... | 0.540196 | 0.265953 |
import re
import json
import datetime
from logging import getLogger
from restclients_core.exceptions import (
InvalidNetID, InvalidRegID, DataFailureException)
from uw_sws.models import Person
from uw_sws.enrollment import enrollment_search_url_prefix
from uw_pws import PERSON_PREFIX
from sis_provisioner.exception... | sis_provisioner/views/user.py |
import re
import json
import datetime
from logging import getLogger
from restclients_core.exceptions import (
InvalidNetID, InvalidRegID, DataFailureException)
from uw_sws.models import Person
from uw_sws.enrollment import enrollment_search_url_prefix
from uw_pws import PERSON_PREFIX
from sis_provisioner.exception... | 0.367724 | 0.064036 |
import string
import artifacts
from graph import DirectedGraph
from tasks import Task
class TemplateKeyError(Exception):
def __init__(self, template_string, key, parameters):
self.template_string = template_string
self.key = key
self.parameters = parameters
def __str__(self):
return ("Missing key ... | datamake/templates.py | import string
import artifacts
from graph import DirectedGraph
from tasks import Task
class TemplateKeyError(Exception):
def __init__(self, template_string, key, parameters):
self.template_string = template_string
self.key = key
self.parameters = parameters
def __str__(self):
return ("Missing key ... | 0.495606 | 0.158239 |
import itertools as it
def arith_combos(digits:list):
targets = []
funcs = ["+", "-", "*", "/"]
for func_set in it.product(funcs, repeat=3):
for new_digs in it.permutations(digits[1:], 3):
for parentheses in [(0, 5), (0, 9), (3, 9), (3, 12), (7,12), (0,12)]:
equation = ... | 076-100/p093/inle.py | import itertools as it
def arith_combos(digits:list):
targets = []
funcs = ["+", "-", "*", "/"]
for func_set in it.product(funcs, repeat=3):
for new_digs in it.permutations(digits[1:], 3):
for parentheses in [(0, 5), (0, 9), (3, 9), (3, 12), (7,12), (0,12)]:
equation = ... | 0.260672 | 0.448064 |
from datetime import datetime, timedelta
from utils import next_weekday
def dev_of_the_week_confirmed(data, lunch_tip=False):
dotwList = data["dotwList"]
backupList = data["backupList"]
next_monday = next_weekday(datetime.now(),0).strftime("%b %d %Y")
next_friday = next_weekday(datetime.now(),4).strfti... | messages.py | from datetime import datetime, timedelta
from utils import next_weekday
def dev_of_the_week_confirmed(data, lunch_tip=False):
dotwList = data["dotwList"]
backupList = data["backupList"]
next_monday = next_weekday(datetime.now(),0).strftime("%b %d %Y")
next_friday = next_weekday(datetime.now(),4).strfti... | 0.350755 | 0.31254 |
try:
from pip.req import parse_requirements
except ImportError:
# For pip version >= 10
from pip._internal.req import parse_requirements
import logging
import os
import zipfile
from .file import get_model_bundles_base_dir, extract_zip_to_dir, \
clean_directory
from ..exceptions import InvalidDemoBundl... | origamid/utils/validation.py | try:
from pip.req import parse_requirements
except ImportError:
# For pip version >= 10
from pip._internal.req import parse_requirements
import logging
import os
import zipfile
from .file import get_model_bundles_base_dir, extract_zip_to_dir, \
clean_directory
from ..exceptions import InvalidDemoBundl... | 0.61555 | 0.214095 |
import numpy as np
from data_generation import *
def pwc_nev(t, w, t_binning):
"""
Piecewise constant approximation of the normalized Explained Variance measure.
Let this measure be denoted by D(t,w,q). 1 - D(t,w,q)*var(w) is basically
the r2 score of regressing w to t by a piecewise constant fun... | nev.py | import numpy as np
from data_generation import *
def pwc_nev(t, w, t_binning):
"""
Piecewise constant approximation of the normalized Explained Variance measure.
Let this measure be denoted by D(t,w,q). 1 - D(t,w,q)*var(w) is basically
the r2 score of regressing w to t by a piecewise constant fun... | 0.815747 | 0.808332 |
from unittest.mock import patch, Mock
import pytest
import numpy as np
import tensorflow as tf
from pathlib import Path
import ramjet.photometric_database.light_curve_database
import ramjet.photometric_database.standard_and_injected_light_curve_database as database_module
from ramjet.photometric_database.derived.toy_... | tests/photometric_database/test_standard_and_injected_lightcurve_database.py | from unittest.mock import patch, Mock
import pytest
import numpy as np
import tensorflow as tf
from pathlib import Path
import ramjet.photometric_database.light_curve_database
import ramjet.photometric_database.standard_and_injected_light_curve_database as database_module
from ramjet.photometric_database.derived.toy_... | 0.90605 | 0.429938 |
import grpc
from python_pachyderm.proto.admin.v1_9.auth import auth_pb2 as client_dot_admin_dot_v1__9_dot_auth_dot_auth__pb2
class APIStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
... | src/python_pachyderm/proto/admin/v1_9/auth/auth_pb2_grpc.py | import grpc
from python_pachyderm.proto.admin.v1_9.auth import auth_pb2 as client_dot_admin_dot_v1__9_dot_auth_dot_auth__pb2
class APIStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
... | 0.55435 | 0.033211 |
import datetime
import sys
import flask_babel
from flask_babel import _
try:
from app import db
from app.models import Rezident, Ban, SubState
from app.payments import email
from app.tools import utils
except ImportError:
sys.stderr.write(
"ERREUR - Ce script peut uniquement être appelé de... | scripts/update_sub_states.py | import datetime
import sys
import flask_babel
from flask_babel import _
try:
from app import db
from app.models import Rezident, Ban, SubState
from app.payments import email
from app.tools import utils
except ImportError:
sys.stderr.write(
"ERREUR - Ce script peut uniquement être appelé de... | 0.097428 | 0.110711 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import _utilities, _tables
__all__ = [
'GetAccountIdTokenResult',
'AwaitableGetAccountIdTokenResult',
'get_account_id_token',
]
@pulumi.output_type
class GetAccountIdTokenResult... | sdk/python/pulumi_gcp/serviceaccount/get_account_id_token.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import _utilities, _tables
__all__ = [
'GetAccountIdTokenResult',
'AwaitableGetAccountIdTokenResult',
'get_account_id_token',
]
@pulumi.output_type
class GetAccountIdTokenResult... | 0.81841 | 0.096025 |
"""Factory functions for all ngraph ops."""
from functools import partial
from typing import Callable, Iterable, List, Optional, Set, Union
import numpy as np
from ngraph.impl import Node, Shape
from ngraph.impl.op import Constant, Parameter
from ngraph.opset_utils import _get_node_factory
from ngraph.utils.decorator... | ngraph/python/src/ngraph/opset8/ops.py |
"""Factory functions for all ngraph ops."""
from functools import partial
from typing import Callable, Iterable, List, Optional, Set, Union
import numpy as np
from ngraph.impl import Node, Shape
from ngraph.impl.op import Constant, Parameter
from ngraph.opset_utils import _get_node_factory
from ngraph.utils.decorator... | 0.971129 | 0.552419 |
import sys
import json
import optparse
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from twkit.utils import *
import config
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def __init__(self, db, api... | twkit/crawler/stream.py | import sys
import json
import optparse
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from twkit.utils import *
import config
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def __init__(self, db, api... | 0.206014 | 0.058239 |
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import linear_kernel
from sklearn.preprocessing import StandardScaler
from scipy.sparse import csr_matrix
import networkx as nx
class graph():
def __init__(
self, df, team_name, mat... | pystatsbomb/passgraph.py | import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import linear_kernel
from sklearn.preprocessing import StandardScaler
from scipy.sparse import csr_matrix
import networkx as nx
class graph():
def __init__(
self, df, team_name, mat... | 0.6508 | 0.263149 |
from os import system , name
def limpaTela():
if name == 'nt':
system('cls')
else:
system('clear')
limpaTela()
def maquina(a, b, c, d, e):
'''
Máquina responsável por vender Celulares, com capacidade para cinco unidades de cada produto, sem limite de notas, onde o troco é devolvido ao
usuário... | EP1_Basico (1).py | from os import system , name
def limpaTela():
if name == 'nt':
system('cls')
else:
system('clear')
limpaTela()
def maquina(a, b, c, d, e):
'''
Máquina responsável por vender Celulares, com capacidade para cinco unidades de cada produto, sem limite de notas, onde o troco é devolvido ao
usuário... | 0.043722 | 0.283357 |
from .backend import ParserBackend
from ..parser import Parser
__all__ = ['StanfordnlpParser']
import logging
logger = logging.getLogger(__name__)
@Parser.register_backend
class StanfordnlpParser(ParserBackend):
"""
Scene graph parser based on spaCy.
"""
__identifier__ = 'stanfordnlp'
def __i... | clevr_parser/backends/stanfordnlp_parser.py |
from .backend import ParserBackend
from ..parser import Parser
__all__ = ['StanfordnlpParser']
import logging
logger = logging.getLogger(__name__)
@Parser.register_backend
class StanfordnlpParser(ParserBackend):
"""
Scene graph parser based on spaCy.
"""
__identifier__ = 'stanfordnlp'
def __i... | 0.442034 | 0.318538 |
import nose
import mock
from pylons import config
from ckan.plugins import toolkit
try:
from ckan.tests import helpers
except ImportError:
from ckan.new_tests import helpers
from ckanext.dcat.logic import _pagination_info
eq_ = nose.tools.eq_
assert_raises = nose.tools.assert_raises
class TestPagination(... | ckan/ckanext-dcat/ckanext/dcat/tests/test_logic.py | import nose
import mock
from pylons import config
from ckan.plugins import toolkit
try:
from ckan.tests import helpers
except ImportError:
from ckan.new_tests import helpers
from ckanext.dcat.logic import _pagination_info
eq_ = nose.tools.eq_
assert_raises = nose.tools.assert_raises
class TestPagination(... | 0.553747 | 0.367355 |
import numpy as np
from numpy import cos, sin, arccos, pi,tan
import scipy.integrate as integrate
import pandas as pd
import os
import matplotlib.pyplot as plt
class airfoil:
def __init__(self,NACA = None,delta_a = None,ca = None,DNI= None,number_coefs = 100,rudder= None):
self.theta = np.linspace(0,pi,1... | aerodynamics/aero.py | import numpy as np
from numpy import cos, sin, arccos, pi,tan
import scipy.integrate as integrate
import pandas as pd
import os
import matplotlib.pyplot as plt
class airfoil:
def __init__(self,NACA = None,delta_a = None,ca = None,DNI= None,number_coefs = 100,rudder= None):
self.theta = np.linspace(0,pi,1... | 0.303216 | 0.287083 |
from pystruct.models import ChainCRF
from pystruct.learners import OneSlackSSVM
import numpy as np
from reviewModules import *
from functions import *
import pickle
import pdb
# training the crf:
listOfReviewFeatures=[]
listOfReviewTags=[]
listOfReviews=[]
with open("data/scoredReviewsAllFeaturesTrainingWithCosine")... | ldaSegmentation/crfForSegmentation.py |
from pystruct.models import ChainCRF
from pystruct.learners import OneSlackSSVM
import numpy as np
from reviewModules import *
from functions import *
import pickle
import pdb
# training the crf:
listOfReviewFeatures=[]
listOfReviewTags=[]
listOfReviews=[]
with open("data/scoredReviewsAllFeaturesTrainingWithCosine")... | 0.1585 | 0.323353 |
import time
from openerp.report import report_sxw
class pos_payment_report_user(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(pos_payment_report_user, self).__init__(cr, uid, name, context=context)
self.total = 0.0
self.localcontext.update({
'time': ... | openerp/addons/point_of_sale/report/pos_payment_report_user.py |
import time
from openerp.report import report_sxw
class pos_payment_report_user(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(pos_payment_report_user, self).__init__(cr, uid, name, context=context)
self.total = 0.0
self.localcontext.update({
'time': ... | 0.394784 | 0.122104 |
import requests
import keys
def collect_data(station):
keyconvert = station.lower()
if keyconvert == 'kenmore':
station = 'place-kencl'
lines = 1
elif keyconvert == 'hynes' or keyconvert == 'hynesconventioncenter':
station = 'place-hymnl'
lines = 1
elif keyconvert == 'c... | mbta.py | import requests
import keys
def collect_data(station):
keyconvert = station.lower()
if keyconvert == 'kenmore':
station = 'place-kencl'
lines = 1
elif keyconvert == 'hynes' or keyconvert == 'hynesconventioncenter':
station = 'place-hymnl'
lines = 1
elif keyconvert == 'c... | 0.200949 | 0.264685 |
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
import scipy as sp
def normalize(X):
t = X.shape
Y = X
mean = np.mean(X,axis=0)
std = np.std(X,axis=0)
for i in range(t[0]):
for j in range(t[1]):
if std[j]!... | code/tenfold-CV.py | import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
import scipy as sp
def normalize(X):
t = X.shape
Y = X
mean = np.mean(X,axis=0)
std = np.std(X,axis=0)
for i in range(t[0]):
for j in range(t[1]):
if std[j]!... | 0.112302 | 0.342077 |
__all__ = [
"create_influxdb_database",
"write_influxdb_line",
"job_to_influxdb",
]
import importlib
import logging
import os
import requests
from requests.exceptions import ConnectionError, HTTPError
from .celery import celery
from .utils.transformation import Transformer
profile = os.environ.get("SQU... | src/squash/tasks/influxdb.py |
__all__ = [
"create_influxdb_database",
"write_influxdb_line",
"job_to_influxdb",
]
import importlib
import logging
import os
import requests
from requests.exceptions import ConnectionError, HTTPError
from .celery import celery
from .utils.transformation import Transformer
profile = os.environ.get("SQU... | 0.742048 | 0.09314 |
import re
import requests
import time
from threading import *
from multiprocessing import Process
from bs4 import BeautifulSoup as bs
import matplotlib.pyplot as plt
url0 = "https://src.sjtu.edu.cn/list/?page="
submitter_index_dic, edu_index_dic = {}, {}
datas = [] #承载爬虫获取的数据(列表形式)
bug_name = ["SQL", "CSRF... | eduSRC.py | import re
import requests
import time
from threading import *
from multiprocessing import Process
from bs4 import BeautifulSoup as bs
import matplotlib.pyplot as plt
url0 = "https://src.sjtu.edu.cn/list/?page="
submitter_index_dic, edu_index_dic = {}, {}
datas = [] #承载爬虫获取的数据(列表形式)
bug_name = ["SQL", "CSRF... | 0.088465 | 0.18188 |
from setuptools import Extension, setup
from Cython.Distutils import build_ext
from sys import platform
def get_long_description():
with open('README.md') as f:
return f.read()
if platform == "win32":
# This is for Windows
ext_modules = [Extension("zgy2sgz",
sources=... | setup.py | from setuptools import Extension, setup
from Cython.Distutils import build_ext
from sys import platform
def get_long_description():
with open('README.md') as f:
return f.read()
if platform == "win32":
# This is for Windows
ext_modules = [Extension("zgy2sgz",
sources=... | 0.266071 | 0.059183 |
import threading
import shfemdapi
import time
from utils import log
class MdHandler(shfemdapi.CShfeFtdcMduserSpi):
def __init__(self, md_api, user_id, password):
self.logger = log.get_logger(category="MdSpi")
shfemdapi.CShfeFtdcMduserSpi.__init__(self)
self.md_api = md_api
sel... | extrader/md_handler.py |
import threading
import shfemdapi
import time
from utils import log
class MdHandler(shfemdapi.CShfeFtdcMduserSpi):
def __init__(self, md_api, user_id, password):
self.logger = log.get_logger(category="MdSpi")
shfemdapi.CShfeFtdcMduserSpi.__init__(self)
self.md_api = md_api
sel... | 0.283583 | 0.137185 |