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 copy from LspAlgorithms.GeneticAlgorithms.Chromosome import Chromosome from LspAlgorithms.GeneticAlgorithms.LocalSearch.LocalSearchNode import LocalSearchNode from LspInputDataReading.LspInputDataInstance import InputDataInstance import random class CrossOverNode: """ """ def __init__(self, parentC...
src/LspAlgorithms/GeneticAlgorithms/GAOperators/CrossOverNode.py
import copy from LspAlgorithms.GeneticAlgorithms.Chromosome import Chromosome from LspAlgorithms.GeneticAlgorithms.LocalSearch.LocalSearchNode import LocalSearchNode from LspInputDataReading.LspInputDataInstance import InputDataInstance import random class CrossOverNode: """ """ def __init__(self, parentC...
0.26971
0.461805
import logging import random from enum import Enum from typing import (Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Union) import numpy as np import torch from torch import device as t_device from torch import set_num_threads from torch.utils.data import Dataset from pos.co...
src/pos/core.py
import logging import random from enum import Enum from typing import (Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Union) import numpy as np import torch from torch import device as t_device from torch import set_num_threads from torch.utils.data import Dataset from pos.co...
0.900913
0.383699
import numpy as np class ParameterSet(object): T_POWER = (lambda x: 10.0**float(x), lambda y: np.log10(y)) T_NEGPOWER = (lambda x: 10.0**float(-x), lambda y: -1.0*np.log10(y)) T_NANO = (lambda x: x*1e9, lambda y: y*1e-9) T_MICRO = (lambda x: x*1e6, lambda y: y*1e-6) T_MILLI = (lambda x: x*1e3...
src/system/parameterset.py
import numpy as np class ParameterSet(object): T_POWER = (lambda x: 10.0**float(x), lambda y: np.log10(y)) T_NEGPOWER = (lambda x: 10.0**float(-x), lambda y: -1.0*np.log10(y)) T_NANO = (lambda x: x*1e9, lambda y: y*1e-9) T_MICRO = (lambda x: x*1e6, lambda y: y*1e-6) T_MILLI = (lambda x: x*1e3...
0.574275
0.626038
from typing import List, Dict, Any, Callable, Union, Optional from yarl import URL true = True class Block: make_block: Callable[..., Dict[str, Any]] has_state: bool = True value_from_state: Callable[..., Union[str, List[str]]] class ButtonBlock(Block): def __init__(self): self.has_state =...
slack_forms/forms/blocks.py
from typing import List, Dict, Any, Callable, Union, Optional from yarl import URL true = True class Block: make_block: Callable[..., Dict[str, Any]] has_state: bool = True value_from_state: Callable[..., Union[str, List[str]]] class ButtonBlock(Block): def __init__(self): self.has_state =...
0.882725
0.417568
import serial import re import logging import argparse logger = logging.getLogger(__name__) class BenqSerial(object): def __init__(self, device): self._ser = serial.serial_for_url(device, baudrate=115200, timeout=0.5) def __del__(self): self._ser.close() def _get_answer(self, command):...
pybenqserial.py
import serial import re import logging import argparse logger = logging.getLogger(__name__) class BenqSerial(object): def __init__(self, device): self._ser = serial.serial_for_url(device, baudrate=115200, timeout=0.5) def __del__(self): self._ser.close() def _get_answer(self, command):...
0.501221
0.062046
app_config: dict = { 'name': 'R2MD', 'log_level': 2, 'description': "R2MD is a tool that wraps version details from all PODs via\n" "Rancher API and prettify results using Markdown notation.", 'title': '\n' ' * * \...
config.py
app_config: dict = { 'name': 'R2MD', 'log_level': 2, 'description': "R2MD is a tool that wraps version details from all PODs via\n" "Rancher API and prettify results using Markdown notation.", 'title': '\n' ' * * \...
0.34798
0.059537
from model.dao.abstractdao import AbstractDAO from model.dao.daoexception import DAOException from model.player import Player R_INSERT = """ INSERT INTO Joueur VALUES (null, ?, ?, ?, ?)""" R_INSERT2 = """ INSERT INTO Composition VALUES (?, ?, ?)""" R_READ_CH_INDEX = """ SELECT id_championnat FROM vJoueur WHERE id_eq...
model/dao/sqlite/dao_player.py
from model.dao.abstractdao import AbstractDAO from model.dao.daoexception import DAOException from model.player import Player R_INSERT = """ INSERT INTO Joueur VALUES (null, ?, ?, ?, ?)""" R_INSERT2 = """ INSERT INTO Composition VALUES (?, ?, ?)""" R_READ_CH_INDEX = """ SELECT id_championnat FROM vJoueur WHERE id_eq...
0.309963
0.116061
# This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from ..foundations import hparams from ..lottery.desc import LotteryDesc from ..models import base from ..pruni...
models/fashion_cnn.py
# This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from ..foundations import hparams from ..lottery.desc import LotteryDesc from ..models import base from ..pruni...
0.925175
0.297457
from greenflow.dataframe_flow import (ConfSchema, PortsSpecSchema) from greenflow.dataframe_flow.template_node_mixin import TemplateNodeMixin from greenflow.dataframe_flow import Node from greenflow.dataframe_flow.metaSpec import MetaDataSchema class DiffNode(TemplateNodeMixin, Node): def init(self): Tem...
gQuant/plugins/hrp_plugin/greenflow_hrp_plugin/diffNode.py
from greenflow.dataframe_flow import (ConfSchema, PortsSpecSchema) from greenflow.dataframe_flow.template_node_mixin import TemplateNodeMixin from greenflow.dataframe_flow import Node from greenflow.dataframe_flow.metaSpec import MetaDataSchema class DiffNode(TemplateNodeMixin, Node): def init(self): Tem...
0.63114
0.235108
from random import randint class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.contacts = {} self.interests = {} def add_contact(self, contact): self.contacts[contact.first_name] = contact return...
source.py
from random import randint class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.contacts = {} self.interests = {} def add_contact(self, contact): self.contacts[contact.first_name] = contact return...
0.379378
0.164953
import megengine as mge import megengine.functional as F import megengine.module as M from basecore.config import ConfigDict __all__ = ["build_loss", "BinaryCrossEntropy", "CrossEntropy"] def build_loss(cfg: ConfigDict) -> M.Module: """The factory function to build loss. Args: cfg: config for buildi...
basecls/layers/losses.py
import megengine as mge import megengine.functional as F import megengine.module as M from basecore.config import ConfigDict __all__ = ["build_loss", "BinaryCrossEntropy", "CrossEntropy"] def build_loss(cfg: ConfigDict) -> M.Module: """The factory function to build loss. Args: cfg: config for buildi...
0.927133
0.512998
import requests rubrik_host = '' username = '' api_token = '' base_url = 'https://{}/api/'.format(rubrik_host) headers = { 'accept': 'application/json', 'Authorization': 'Bearer {}'.format(api_token), 'Content-Type': 'application/json' } # VARIABLES sql_db = 'AdventureWorks2014' sql_instance = 'MSSQLSER...
python/hackathon.py
import requests rubrik_host = '' username = '' api_token = '' base_url = 'https://{}/api/'.format(rubrik_host) headers = { 'accept': 'application/json', 'Authorization': 'Bearer {}'.format(api_token), 'Content-Type': 'application/json' } # VARIABLES sql_db = 'AdventureWorks2014' sql_instance = 'MSSQLSER...
0.480479
0.103658
from datetime import datetime from asnake.aspace import ASpace from asnake.jsonmodel import JSONModelObject from cartographer_backend import settings from django.core.exceptions import FieldError from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.utils.timezone import make_awar...
maps/views.py
from datetime import datetime from asnake.aspace import ASpace from asnake.jsonmodel import JSONModelObject from cartographer_backend import settings from django.core.exceptions import FieldError from django.db.models import Sum from django.shortcuts import get_object_or_404 from django.utils.timezone import make_awar...
0.822011
0.234472
from __future__ import print_function import numpy as np from lensit.misc.misc_utils import timer from lensit.ffs_deflect.ffs_deflect import ffs_id_displacement from lensit.ffs_covs import ffs_specmat as SM verbose = False typs = ['T', 'QU', 'TQU'] def get_qlms_wl(typ, lib_sky, TQU_Mlik, ResTQU_Mlik, lib_qlm, f=Non...
lensit/ffs_qlms/qlms.py
from __future__ import print_function import numpy as np from lensit.misc.misc_utils import timer from lensit.ffs_deflect.ffs_deflect import ffs_id_displacement from lensit.ffs_covs import ffs_specmat as SM verbose = False typs = ['T', 'QU', 'TQU'] def get_qlms_wl(typ, lib_sky, TQU_Mlik, ResTQU_Mlik, lib_qlm, f=Non...
0.713531
0.550184
from unit_tester import test def share_diagonal(x0, y0, x1, y1): """ Is (x0, y0) on a shared diagonal with (x1, y1)? """ dy = abs(y1 - y0) # Calc the absolute y distance dx = abs(x1 - x0) # CXalc the absolute x distance return dx == dy # They clash if dx == dy test(not share_d...
src/Fourteenth Chapter/Example6.py
from unit_tester import test def share_diagonal(x0, y0, x1, y1): """ Is (x0, y0) on a shared diagonal with (x1, y1)? """ dy = abs(y1 - y0) # Calc the absolute y distance dx = abs(x1 - x0) # CXalc the absolute x distance return dx == dy # They clash if dx == dy test(not share_d...
0.749179
0.701311
import datetime from flask import Flask, render_template, redirect, url_for, request, flash from classes import db, app, Teacher, Paper, Version, Fixed_Invigilation, Invigilation, Pool from sqlalchemy.orm import noload from generate import generate_largest_pools, generate_department_pools @app.route('/papers', methods...
flask_app.py
import datetime from flask import Flask, render_template, redirect, url_for, request, flash from classes import db, app, Teacher, Paper, Version, Fixed_Invigilation, Invigilation, Pool from sqlalchemy.orm import noload from generate import generate_largest_pools, generate_department_pools @app.route('/papers', methods...
0.134463
0.069038
import collections import random import numpy as np import config import obj_canvas class Paddle(object): """ Represents the breakout paddle. """ def __init__(self, canvas): """ Args: canvas: The Canvas to draw the paddle on. """ self.__canvas = canvas # Old position measurements to aver...
breakout_graphics.py
import collections import random import numpy as np import config import obj_canvas class Paddle(object): """ Represents the breakout paddle. """ def __init__(self, canvas): """ Args: canvas: The Canvas to draw the paddle on. """ self.__canvas = canvas # Old position measurements to aver...
0.836454
0.257563
import os import discord import requests from discord import CategoryChannel, Guild, RawReactionActionEvent from discord.channel import VoiceChannel from discord.ext import commands from discord.member import Member, VoiceState from dotenv import load_dotenv from Database.bot_db import BotDb load_dotenv(...
main.py
import os import discord import requests from discord import CategoryChannel, Guild, RawReactionActionEvent from discord.channel import VoiceChannel from discord.ext import commands from discord.member import Member, VoiceState from dotenv import load_dotenv from Database.bot_db import BotDb load_dotenv(...
0.190197
0.045884
from sys import argv from kwz import KWZParser, PALETTE import pygame import numpy as np class layerSurface: def __init__(self, size=(320, 240)): self.surface = pygame.Surface(size, depth=8) self.surface.set_colorkey(0) self.surface.set_palette_at(0, (255, 255, 255)) def set_palette_at(self, index, c...
kwzViewer.py
from sys import argv from kwz import KWZParser, PALETTE import pygame import numpy as np class layerSurface: def __init__(self, size=(320, 240)): self.surface = pygame.Surface(size, depth=8) self.surface.set_colorkey(0) self.surface.set_palette_at(0, (255, 255, 255)) def set_palette_at(self, index, c...
0.197097
0.316369
import base64 import logging from datetime import timedelta from django.conf import settings from django.utils import timezone from six.moves.urllib.parse import quote_plus, unquote_plus, parse_qsl from zooniverse_web.models import Verification logger = logging.getLogger(__name__) def check_path(path): """Chec...
zooniverse_web/utility/utils.py
import base64 import logging from datetime import timedelta from django.conf import settings from django.utils import timezone from six.moves.urllib.parse import quote_plus, unquote_plus, parse_qsl from zooniverse_web.models import Verification logger = logging.getLogger(__name__) def check_path(path): """Chec...
0.701304
0.217982
import array import logging from fontTools import ttLib from fontTools.pens.hashPointPen import HashPointPen from fontTools.ttLib.tables._g_l_y_f import ( OVERLAP_COMPOUND, ROUND_XY_TO_GRID, USE_MY_METRICS, ) logger = logging.getLogger(__name__) TRUETYPE_INSTRUCTIONS_KEY = "public.truetype.instructions" ...
Lib/ufo2ft/instructionCompiler.py
import array import logging from fontTools import ttLib from fontTools.pens.hashPointPen import HashPointPen from fontTools.ttLib.tables._g_l_y_f import ( OVERLAP_COMPOUND, ROUND_XY_TO_GRID, USE_MY_METRICS, ) logger = logging.getLogger(__name__) TRUETYPE_INSTRUCTIONS_KEY = "public.truetype.instructions" ...
0.511717
0.144571
from django.conf import settings HIDE_PROMO = getattr( settings, 'COMPONENTS_HIDE_PROMO', False, ) HIDE_PROMO_ROLLOVER = getattr( settings, 'COMPONENTS_HIDE_PROMO_ROLLOVER', True, ) HIDE_PROMO_VIDEO = getattr( settings, 'COMPONENTS_HIDE_PROMO_VIDEO', True, ) PROMO_LAYOUTS = getattr...
js_components/constants.py
from django.conf import settings HIDE_PROMO = getattr( settings, 'COMPONENTS_HIDE_PROMO', False, ) HIDE_PROMO_ROLLOVER = getattr( settings, 'COMPONENTS_HIDE_PROMO_ROLLOVER', True, ) HIDE_PROMO_VIDEO = getattr( settings, 'COMPONENTS_HIDE_PROMO_VIDEO', True, ) PROMO_LAYOUTS = getattr...
0.326593
0.058239
import assessment.builder.validators from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Activity', ...
assessment/builder/migrations/0001_initial.py
import assessment.builder.validators from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Activity', ...
0.688887
0.177027
from django.db import migrations def reviewer_to_user(models, reviewer): if reviewer.user: user, created = models.User.objects.get_or_create( internal=reviewer.user, ) return user else: external_user, created = models.ExternalUser.objects.get_or_create( ...
wagtail_review/migrations/0005_migrate_to_new_models.py
from django.db import migrations def reviewer_to_user(models, reviewer): if reviewer.user: user, created = models.User.objects.get_or_create( internal=reviewer.user, ) return user else: external_user, created = models.ExternalUser.objects.get_or_create( ...
0.621656
0.138987
#!/usr/bin/env python3 import argparse import logging import json import sys import requests import uuid import time import boto3 import botocore from utils.config_loader import Config from pprint import pprint as pretty import json import random from datetime import datetime from payloadHandler import payloadHand...
generateDTC.py
#!/usr/bin/env python3 import argparse import logging import json import sys import requests import uuid import time import boto3 import botocore from utils.config_loader import Config from pprint import pprint as pretty import json import random from datetime import datetime from payloadHandler import payloadHand...
0.250363
0.048316
import logging from typing import List, Literal, Optional from pydantic import Field from pydantic.class_validators import validator from pydantic.types import NonNegativeInt from hydrolib.core.io.ini.models import INIBasedModel, INIGeneral, INIModel from hydrolib.core.io.ini.util import ( get_split_string_on_del...
hydrolib/core/io/onedfield/models.py
import logging from typing import List, Literal, Optional from pydantic import Field from pydantic.class_validators import validator from pydantic.types import NonNegativeInt from hydrolib.core.io.ini.models import INIBasedModel, INIGeneral, INIModel from hydrolib.core.io.ini.util import ( get_split_string_on_del...
0.902542
0.385953
from aws_cdk.core import ( App, CfnOutput, Tags, Stack ) from aws_cdk import aws_elasticache as elasticache from config import config_util as config from cache.helper import ( log_group, secret, user_group, vpc ) class ElastiCacheStack(Stack): # Class for the ReplicationGroup stac...
python/elasticache/cache/elasticache_stack.py
from aws_cdk.core import ( App, CfnOutput, Tags, Stack ) from aws_cdk import aws_elasticache as elasticache from config import config_util as config from cache.helper import ( log_group, secret, user_group, vpc ) class ElastiCacheStack(Stack): # Class for the ReplicationGroup stac...
0.852614
0.105763
import tblink_rpc import ctypes @tblink_rpc.iftype("i2c_bfms.initiator") class I2cInitiatorBfm(object): def __init__(self): self._ev = tblink_rpc.event() self._lock = tblink_rpc.lock() self._is_reset = False self._is_reset_ev = tblink_rpc.event() self._data = 0 ...
frontends/python/i2c_bfms/i2c_initiator_bfm.py
import tblink_rpc import ctypes @tblink_rpc.iftype("i2c_bfms.initiator") class I2cInitiatorBfm(object): def __init__(self): self._ev = tblink_rpc.event() self._lock = tblink_rpc.lock() self._is_reset = False self._is_reset_ev = tblink_rpc.event() self._data = 0 ...
0.205217
0.080141
# Este codigo plota os valores do ruido de leitura encontrados #pela biblioteca hyperopt em funcao do numero de iteracao. #22/11/2019. <NAME>. from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import json from sys import exit ##arq = open(r'Logs\Para...
Codigos_python/Graficos/Iteracoes_ruido_parametros/plot_parameters_vs_iteration.py
# Este codigo plota os valores do ruido de leitura encontrados #pela biblioteca hyperopt em funcao do numero de iteracao. #22/11/2019. <NAME>. from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import json from sys import exit ##arq = open(r'Logs\Para...
0.19888
0.433262
from expfactory.views import preview_experiment, run_battery, run_single from expfactory.battery import generate, generate_local from expfactory.experiment import validate, load_experiment from expfactory.tests import validate_surveys from glob import glob import argparse import sys import os def main(): parser = ...
expfactory/scripts.py
from expfactory.views import preview_experiment, run_battery, run_single from expfactory.battery import generate, generate_local from expfactory.experiment import validate, load_experiment from expfactory.tests import validate_surveys from glob import glob import argparse import sys import os def main(): parser = ...
0.440229
0.169784
import os, json from uSocket import send COUNTRY_NAMES = { "al": "Albania", "ar": "Argentina", "au": "Australia", "at": "Austria", "be": "Belgium", "ba": "Bosnia and Herzegovina", "br": "Brazil", "bg": "Bulgaria", "ca": "Canada", "cl": "Chile", "cr": "Costa Rica", "hr": ...
vpncontrol/helperFlaglist.py
import os, json from uSocket import send COUNTRY_NAMES = { "al": "Albania", "ar": "Argentina", "au": "Australia", "at": "Austria", "be": "Belgium", "ba": "Bosnia and Herzegovina", "br": "Brazil", "bg": "Bulgaria", "ca": "Canada", "cl": "Chile", "cr": "Costa Rica", "hr": ...
0.469034
0.370624
import string import os from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException import pandas as pd """ references browsy scraper.py https://github.com/beepscore/browsy websearcher browser_driver.py https://github.com/beepscore/we...
malaria_scraper.py
import string import os from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException import pandas as pd """ references browsy scraper.py https://github.com/beepscore/browsy websearcher browser_driver.py https://github.com/beepscore/we...
0.383988
0.210807
#pylint: disable=missing-docstring,invalid-name,bare-except,wrong-import-position,import-error import sys from os.path import dirname, abspath from datetime import datetime import unittest sys.path.insert(0, dirname(dirname(dirname(abspath(__file__))))) from linga import app, db, User from linga.auth impor...
tests/python/test_auth.py
#pylint: disable=missing-docstring,invalid-name,bare-except,wrong-import-position,import-error import sys from os.path import dirname, abspath from datetime import datetime import unittest sys.path.insert(0, dirname(dirname(dirname(abspath(__file__))))) from linga import app, db, User from linga.auth impor...
0.180648
0.140454
#문자열 msg = 'Hello, World!!' #파이썬에서는 자료구조를 의미하는 접미사를 #변수명에 사용하기도 한다 list1_list=[] #빈 리스트 list2_list=[1,2,3,4,5] #숫자 list3_list=['a','b','c'] #문자 list4_list=['a','b','c',1,2,3,True] #혼합 print(list1_list) #간단한 연산 #요소 존재 여부 파악 : in/not in 연산자 print(1 in list1_list) print('a' in list1_list) print(3 in lis...
Python3Lab/List.py
#문자열 msg = 'Hello, World!!' #파이썬에서는 자료구조를 의미하는 접미사를 #변수명에 사용하기도 한다 list1_list=[] #빈 리스트 list2_list=[1,2,3,4,5] #숫자 list3_list=['a','b','c'] #문자 list4_list=['a','b','c',1,2,3,True] #혼합 print(list1_list) #간단한 연산 #요소 존재 여부 파악 : in/not in 연산자 print(1 in list1_list) print('a' in list1_list) print(3 in lis...
0.064403
0.331674
from __future__ import annotations import math from prettyqt import constants, core, custom_models def size_to_string(size): if size <= 0: return "0 b" decimals = 2 units = ["b", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] power = int(math.log(size, 1024)) try: unit = units[p...
prettyqt/custom_models/storageinfomodel.py
from __future__ import annotations import math from prettyqt import constants, core, custom_models def size_to_string(size): if size <= 0: return "0 b" decimals = 2 units = ["b", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] power = int(math.log(size, 1024)) try: unit = units[p...
0.626353
0.394376
import click import re import sys class Tester: def __init__(self): self.errors = [] def __str__(self): str = "" if self.errors: str += f"{self.title} Errors\n" for item in self.errors: str += f"\t{item}\n" return str def __bool__(...
rplint/__main__.py
import click import re import sys class Tester: def __init__(self): self.errors = [] def __str__(self): str = "" if self.errors: str += f"{self.title} Errors\n" for item in self.errors: str += f"\t{item}\n" return str def __bool__(...
0.400632
0.431644
import os, subprocess, glob, time, shutil import argparse, uuid, json, csv import logging from logging.handlers import RotatingFileHandler import Selenzy from flask import Flask, flash, render_template, request, redirect, url_for, send_from_directory, jsonify from flask_restful import Resource, Api from flask import se...
selenzy_wrapper/selenzy/flaskform.py
import os, subprocess, glob, time, shutil import argparse, uuid, json, csv import logging from logging.handlers import RotatingFileHandler import Selenzy from flask import Flask, flash, render_template, request, redirect, url_for, send_from_directory, jsonify from flask_restful import Resource, Api from flask import se...
0.29696
0.042942
import string import sys import json from os import curdir, sep from sets import Set allRoutes = Set() goldstandard = [] computed_results = [] # route user iso_ts responsetime # 1002 8550102e445ac626 2013-12-19 21:24:04 1444 with open('extract_route_user_ts_responsetime_out.csv', 'r') as f: for line in f: cols...
server/SLDLogViewer/merge_and_count.py
import string import sys import json from os import curdir, sep from sets import Set allRoutes = Set() goldstandard = [] computed_results = [] # route user iso_ts responsetime # 1002 8550102e445ac626 2013-12-19 21:24:04 1444 with open('extract_route_user_ts_responsetime_out.csv', 'r') as f: for line in f: cols...
0.128717
0.178795
import connexion from swagger_server.models.inline_response20013 import InlineResponse20013 from swagger_server.models.inline_response202 import InlineResponse202 from swagger_server.models.transition_request import TransitionRequest from datetime import date, datetime from typing import List, Dict from six import iter...
osm-adaptor/swagger_server/controllers/lifecycle_controller_controller.py
import connexion from swagger_server.models.inline_response20013 import InlineResponse20013 from swagger_server.models.inline_response202 import InlineResponse202 from swagger_server.models.transition_request import TransitionRequest from datetime import date, datetime from typing import List, Dict from six import iter...
0.686265
0.048294
import doctest import errno import os import socket import unittest import webbrowser try: from cStringIO import StringIO except ImportError: from io import StringIO from mock import Mock, patch import docutils.utils from restview.restviewhttp import (MyRequestHandler, RestViewer, ...
Libraries/Python/restview/v2.9.1/restview/tests.py
import doctest import errno import os import socket import unittest import webbrowser try: from cStringIO import StringIO except ImportError: from io import StringIO from mock import Mock, patch import docutils.utils from restview.restviewhttp import (MyRequestHandler, RestViewer, ...
0.394201
0.075176
from unittest import TestCase from unittest.mock import patch, MagicMock, PropertyMock from bson import ObjectId from django_mock_queries.query import MockSet from mlplaygrounds.datasets.tests.mocks.managers import MockDatasetManager from ..models import User, CustomUserManager class TestUserModel(TestCase): d...
mlplaygrounds/users/tests/test_user_model.py
from unittest import TestCase from unittest.mock import patch, MagicMock, PropertyMock from bson import ObjectId from django_mock_queries.query import MockSet from mlplaygrounds.datasets.tests.mocks.managers import MockDatasetManager from ..models import User, CustomUserManager class TestUserModel(TestCase): d...
0.597256
0.333666
from app import app import datetime import urllib.request,json from .models import news,sources,entertainment News = news.News Sources = sources.Sources Entertainment = entertainment.Entertainment # Getting api key api_key = app.config['NEWS_API_KEY'] # Getting the news base url news_base_url = app.config["NEWS_HIGH...
app/request.py
from app import app import datetime import urllib.request,json from .models import news,sources,entertainment News = news.News Sources = sources.Sources Entertainment = entertainment.Entertainment # Getting api key api_key = app.config['NEWS_API_KEY'] # Getting the news base url news_base_url = app.config["NEWS_HIGH...
0.220007
0.048631
import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import datetime plt.style.use(['science', 'no-latex']) df = pd.read_excel('data/pf_result_new_with_benchmark.xlsx') df.columns = ['timestamp', 'Portfolio Monthly Return', 'Benchmark Monthly Return', 'Portfolio Total Return (0 -> t)', ...
draw_graph_performance.py
import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import datetime plt.style.use(['science', 'no-latex']) df = pd.read_excel('data/pf_result_new_with_benchmark.xlsx') df.columns = ['timestamp', 'Portfolio Monthly Return', 'Benchmark Monthly Return', 'Portfolio Total Return (0 -> t)', ...
0.490724
0.550366
from collections import deque dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def solution(land, height): labels = [[0 for _ in range(len(land))] for _ in range(len(land))] label_number = 1 for y in range(len(land)): for x in range(len(land)): if labels[y][x] == 0: bfs(y, x, lab...
programmers/lv4_review/p2_1.py
from collections import deque dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def solution(land, height): labels = [[0 for _ in range(len(land))] for _ in range(len(land))] label_number = 1 for y in range(len(land)): for x in range(len(land)): if labels[y][x] == 0: bfs(y, x, lab...
0.331336
0.498413
import numpy as np import pandas as pd from io import BytesIO from zipfile import ZipFile from urllib.request import urlopen from database.base import Session, engine, Base from database.cip_history import CipCode class CipFile: """ Class for a particular year's CIP assignments """ def __init__(self, year: i...
netfile/cip_file.py
import numpy as np import pandas as pd from io import BytesIO from zipfile import ZipFile from urllib.request import urlopen from database.base import Session, engine, Base from database.cip_history import CipCode class CipFile: """ Class for a particular year's CIP assignments """ def __init__(self, year: i...
0.422386
0.230184
import os, sys; import h5py, user_config, cppext; from numpy import *; from share_fun import val_def; from functions import generate_Umatrix; def init_solver(parms, np): solver_type = parms['SOLVER_TYPE']; print '%s solver is used...'%solver_type; input_args = { 'solver_path' : parms.get('SOLV...
solver_types.py
import os, sys; import h5py, user_config, cppext; from numpy import *; from share_fun import val_def; from functions import generate_Umatrix; def init_solver(parms, np): solver_type = parms['SOLVER_TYPE']; print '%s solver is used...'%solver_type; input_args = { 'solver_path' : parms.get('SOLV...
0.247714
0.094594
import sys sys.path.insert(0, '../utils') import os import os.path as osp import numpy as np import torch import tqdm import torch.nn as nn from sklearn.metrics import confusion_matrix, classification_report import yaml from model import Model from particle_dataset import ParticleDataset from segment_scan import segm...
voxel_classification/src/evaluate_models.py
import sys sys.path.insert(0, '../utils') import os import os.path as osp import numpy as np import torch import tqdm import torch.nn as nn from sklearn.metrics import confusion_matrix, classification_report import yaml from model import Model from particle_dataset import ParticleDataset from segment_scan import segm...
0.663996
0.27903
import subprocess import argparse import shutil import sys import time from datetime import datetime import re import os.path import pandas as pd import sys from Bio.Seq import Seq fixed_file = open("filtered_variants.txt", "w+") def translate(seq): table = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',...
annotation/correct_AF_bcftools.py
import subprocess import argparse import shutil import sys import time from datetime import datetime import re import os.path import pandas as pd import sys from Bio.Seq import Seq fixed_file = open("filtered_variants.txt", "w+") def translate(seq): table = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',...
0.079523
0.218544
import numpy as np from numpy.testing import assert_almost_equal, assert_allclose import pytest from km3pipe.testing import TestCase from km3pipe import Table from km3pipe.math import ( angle_between, dist, pld3, com, zenith, azimuth, Polygon, IrregularPrism, rotation_matrix, s...
km3pipe/tests/test_math.py
import numpy as np from numpy.testing import assert_almost_equal, assert_allclose import pytest from km3pipe.testing import TestCase from km3pipe import Table from km3pipe.math import ( angle_between, dist, pld3, com, zenith, azimuth, Polygon, IrregularPrism, rotation_matrix, s...
0.698227
0.611527
""" Definition of views. """ from datetime import datetime from django.shortcuts import render from django.http import HttpRequest from app.euro_spider import euro_start_scraper from app.me_spider import me_start_scraper from app.mm_spider import mm_start_scraper from app.models import clean_json_files, json_reader, ...
app/views.py
""" Definition of views. """ from datetime import datetime from django.shortcuts import render from django.http import HttpRequest from app.euro_spider import euro_start_scraper from app.me_spider import me_start_scraper from app.mm_spider import mm_start_scraper from app.models import clean_json_files, json_reader, ...
0.267408
0.182644
import os import sys import prody as pr #You can either add the python package path. #sys.path.append(r'/mnt/e/GitHub_Design/Metalprot') from metalprot import generate_sse as gss from metalprot import extract_vdm def generate_c4s(outdir, target_path, metal_sel, pre_flag = 'target_c4_', x = 20, y = 10, delta = 3): ...
scrips/construct_helix/run_gss_c4.py
import os import sys import prody as pr #You can either add the python package path. #sys.path.append(r'/mnt/e/GitHub_Design/Metalprot') from metalprot import generate_sse as gss from metalprot import extract_vdm def generate_c4s(outdir, target_path, metal_sel, pre_flag = 'target_c4_', x = 20, y = 10, delta = 3): ...
0.084984
0.136695
import typing import PIL.Image from enum import Enum import preppipe.commontypes class VNContext: def __init__(self) -> None: self.background_music = None self.background_image = None class VNElement: """VNElement Representing an actionable data element inside the VN model """ def __init__(self)...
src/preppipe/visualnovelmodel.py
import typing import PIL.Image from enum import Enum import preppipe.commontypes class VNContext: def __init__(self) -> None: self.background_music = None self.background_image = None class VNElement: """VNElement Representing an actionable data element inside the VN model """ def __init__(self)...
0.68215
0.240607
import rclpy from rclpy.node import Node from sensor_msgs.msg import Image from gazebo_msgs.srv import SetEntityState from gazebo_msgs.msg import EntityState from geometry_msgs.msg import Pose, Twist from ament_index_python import get_package_share_directory from rclpy.qos import QoSPresetProfiles from cv_bridge import...
src/pose_estimation/pose_estimation/calibrate_sim.py
import rclpy from rclpy.node import Node from sensor_msgs.msg import Image from gazebo_msgs.srv import SetEntityState from gazebo_msgs.msg import EntityState from geometry_msgs.msg import Pose, Twist from ament_index_python import get_package_share_directory from rclpy.qos import QoSPresetProfiles from cv_bridge import...
0.587707
0.175945
__copyright__ = "Copyright (C) 2016-2021 Flexiv Ltd. All Rights Reserved." __author__ = "Flexiv" import time import argparse # Import Flexiv RDK Python library # fmt: off import sys sys.path.insert(0, "../lib/") import flexivrdk # fmt: on def main(): # Parse Arguments # =====================================...
example_py/plan_execution.py
__copyright__ = "Copyright (C) 2016-2021 Flexiv Ltd. All Rights Reserved." __author__ = "Flexiv" import time import argparse # Import Flexiv RDK Python library # fmt: off import sys sys.path.insert(0, "../lib/") import flexivrdk # fmt: on def main(): # Parse Arguments # =====================================...
0.530236
0.170957
from pathlib import Path import sanic import sanic.response import twitter from sanic.log import logger from sanic_ext.extensions.http.extension import HTTPExtension from sanic_ext.extensions.openapi.extension import OpenAPIExtension from .config import load_json_config from .link_cache import initialize_link_cache f...
src/twitfix/routes.py
from pathlib import Path import sanic import sanic.response import twitter from sanic.log import logger from sanic_ext.extensions.http.extension import HTTPExtension from sanic_ext.extensions.openapi.extension import OpenAPIExtension from .config import load_json_config from .link_cache import initialize_link_cache f...
0.388502
0.060863
import optapy import optapy.score import optapy.config def test_pinning_filter(): def is_entity_pinned(_, entity): return entity.is_pinned() @optapy.planning_entity(pinning_filter=is_entity_pinned) class Point: def __init__(self, value, is_pinned=False): self.value = value ...
optapy-core/tests/test_pinning.py
import optapy import optapy.score import optapy.config def test_pinning_filter(): def is_entity_pinned(_, entity): return entity.is_pinned() @optapy.planning_entity(pinning_filter=is_entity_pinned) class Point: def __init__(self, value, is_pinned=False): self.value = value ...
0.729616
0.417064
from email.parser import BytesParser from lxml import html from lxml.etree import ParserError, Comment import modules.port import codecs class HttpPort(modules.port.Port): def __init__(self, port): super().__init__("http", port) self.data = {} def add_data(self, row): if row["type"] n...
modules/http.py
from email.parser import BytesParser from lxml import html from lxml.etree import ParserError, Comment import modules.port import codecs class HttpPort(modules.port.Port): def __init__(self, port): super().__init__("http", port) self.data = {} def add_data(self, row): if row["type"] n...
0.176636
0.164953
from __future__ import unicode_literals from nose.plugins.attrib import attr from nose.tools import nottest from mogwai.tests import BaseMogwaiTestCase from mogwai._compat import PY2 from .base_tests import GraphPropertyBaseClassTestCase from mogwai.properties.properties import DateTime, GraphProperty from mogwai.model...
mogwai/tests/properties_tests/properties_tests/datetime_tests.py
from __future__ import unicode_literals from nose.plugins.attrib import attr from nose.tools import nottest from mogwai.tests import BaseMogwaiTestCase from mogwai._compat import PY2 from .base_tests import GraphPropertyBaseClassTestCase from mogwai.properties.properties import DateTime, GraphProperty from mogwai.model...
0.701815
0.488222
import ast import functools import re from copy import deepcopy from inspect import stack from pathlib import Path import executing import mat2py.config from mat2py.common.backends import numpy as np from mat2py.common.logger import logger from mat2py.common.utils import Singleton from .array import M, mp_detect_vec...
mat2py/core/_internal/helper.py
import ast import functools import re from copy import deepcopy from inspect import stack from pathlib import Path import executing import mat2py.config from mat2py.common.backends import numpy as np from mat2py.common.logger import logger from mat2py.common.utils import Singleton from .array import M, mp_detect_vec...
0.38943
0.208219
from __future__ import division import Tkinter as tk class Main_window: def __init__(self, master): self.master = master ## Main Frame self.main_frame = tk.Frame(master, bd=2, relief='sunken', padx=10,pady=20) self.main_frame.pack(anchor='c', padx= 10, pady= 20) ...
Code/line_helper_gui.py
from __future__ import division import Tkinter as tk class Main_window: def __init__(self, master): self.master = master ## Main Frame self.main_frame = tk.Frame(master, bd=2, relief='sunken', padx=10,pady=20) self.main_frame.pack(anchor='c', padx= 10, pady= 20) ...
0.510496
0.081046
from django.db import transaction from cms.models import CMSPlugin from cms.utils.plugins import reorder_plugins from .utils import get_plugin_class @transaction.atomic def import_plugins(plugins, placeholder, language, root_plugin_id=None): source_map = {} new_plugins = [] if root_plugin_id: r...
djangocms_transfer/importer.py
from django.db import transaction from cms.models import CMSPlugin from cms.utils.plugins import reorder_plugins from .utils import get_plugin_class @transaction.atomic def import_plugins(plugins, placeholder, language, root_plugin_id=None): source_map = {} new_plugins = [] if root_plugin_id: r...
0.322953
0.070304
from rest_framework import serializers, exceptions as drf_exceptions from .....models import ( WorkflowCollectionSubscription, WorkflowCollectionSubscriptionSchedule, WorkflowCollection, ) class WorkflowCollectionSubscriptionScheduleSummarySerializer( serializers.ModelSerializer ): """Model Seria...
django_workflow_system/api/serializers/user/workflows/subscription.py
from rest_framework import serializers, exceptions as drf_exceptions from .....models import ( WorkflowCollectionSubscription, WorkflowCollectionSubscriptionSchedule, WorkflowCollection, ) class WorkflowCollectionSubscriptionScheduleSummarySerializer( serializers.ModelSerializer ): """Model Seria...
0.674694
0.173393
import sys sys.path.append( "./src/") import unittest from undefined.API import trace from undefined.Calculator import * class TestAPI(unittest.TestCase): def setUp(self): self.a = 2 self.b = - 1.11 self.c = 99999.99 self.d = -99999.99 self.e = np.array([[self.a, self...
test/test_API.py
import sys sys.path.append( "./src/") import unittest from undefined.API import trace from undefined.Calculator import * class TestAPI(unittest.TestCase): def setUp(self): self.a = 2 self.b = - 1.11 self.c = 99999.99 self.d = -99999.99 self.e = np.array([[self.a, self...
0.287268
0.607314
import os import sys import re import sqlite3 as sqlite try: if sys.version_info < (2, 3): raise ImportError import unittest2 unittest = unittest2 except ImportError: import unittest unittest2 = None import xls2db def do_one(xls_filename, dbname, do_drop=False): if do_drop: x...
test.py
import os import sys import re import sqlite3 as sqlite try: if sys.version_info < (2, 3): raise ImportError import unittest2 unittest = unittest2 except ImportError: import unittest unittest2 = None import xls2db def do_one(xls_filename, dbname, do_drop=False): if do_drop: x...
0.167763
0.268893
from tempfile import TemporaryFile,gettempdir; import os as _os; from xlwt import Workbook,XFStyle; from datetime import datetime,date,time,timedelta; import calendar; class ProjectToExcel(object): def __init__(self): pass; def exportToExcel(self,objectProject): book = Workb...
comcenter/comcenter/controllers/util/exportexcel/projecttoexcel.py
from tempfile import TemporaryFile,gettempdir; import os as _os; from xlwt import Workbook,XFStyle; from datetime import datetime,date,time,timedelta; import calendar; class ProjectToExcel(object): def __init__(self): pass; def exportToExcel(self,objectProject): book = Workb...
0.181662
0.053108
import collections import numpy as np RunResults = collections.namedtuple('RunResults', ['total_clicks', 'total_impressions', 'total_ad_spend']) class BidSimulator: """Simulates given bidding strategy on a data...
rtb/bidding.py
import collections import numpy as np RunResults = collections.namedtuple('RunResults', ['total_clicks', 'total_impressions', 'total_ad_spend']) class BidSimulator: """Simulates given bidding strategy on a data...
0.892375
0.545225
from typing import List from flotypes import * from astree import * from lexer import TokType, Token from errors import SyntaxError from errors import Range def str_to_flotype(str): if str == "int": return FloInt(None) if str == "float": return FloFloat(None) elif str == "void":...
src/parser.py
from typing import List from flotypes import * from astree import * from lexer import TokType, Token from errors import SyntaxError from errors import Range def str_to_flotype(str): if str == "int": return FloInt(None) if str == "float": return FloFloat(None) elif str == "void":...
0.696887
0.140189
from kim.exception import RoleError class Role(set): """Roles are a fundamental feature of Kim. It's very common to need to provide a different view of your data or to only require a selection of fields when marshaling data. ``Roles`` in Kim allow users to shape their data at runtime in a simple ye...
kim/role.py
from kim.exception import RoleError class Role(set): """Roles are a fundamental feature of Kim. It's very common to need to provide a different view of your data or to only require a selection of fields when marshaling data. ``Roles`` in Kim allow users to shape their data at runtime in a simple ye...
0.885817
0.48377
from PIL import Image, UnidentifiedImageError from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from UserApp.m...
ProjectShop/UserApp/models.py
from PIL import Image, UnidentifiedImageError from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from UserApp.m...
0.672117
0.106319
from pymongo import MongoClient from datetime import datetime from dotenv import load_dotenv import os services_dummy_data = [ { 'name': 'dns-service', 'host': { 'type': 'ip', 'value': '1.1.1.1' }, 'port': '53', 'proto': 'udp', 'timestamps': ...
init_db.py
from pymongo import MongoClient from datetime import datetime from dotenv import load_dotenv import os services_dummy_data = [ { 'name': 'dns-service', 'host': { 'type': 'ip', 'value': '1.1.1.1' }, 'port': '53', 'proto': 'udp', 'timestamps': ...
0.486819
0.122681
import numpy as np from cykdtree import PyKDTree DIRECTION_MAPPING = { 'x': 0, 'y': 1, 'z': 2, } def _plot(plot_nodes, filename, outlines_only=False): from matplotlib import pyplot as plt from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection if outl...
qtree/kdtree.py
import numpy as np from cykdtree import PyKDTree DIRECTION_MAPPING = { 'x': 0, 'y': 1, 'z': 2, } def _plot(plot_nodes, filename, outlines_only=False): from matplotlib import pyplot as plt from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection if outl...
0.839701
0.651327
"""Integration tests for gcs_ocn_bq_ingest""" import json import os import uuid from typing import List import pytest from google.cloud import bigquery from google.cloud import error_reporting from google.cloud import storage import gcs_ocn_bq_ingest.common.ordering import gcs_ocn_bq_ingest.common.utils TEST_DIR = o...
tools/cloud_functions/gcs_event_based_ingest/tests/conftest.py
"""Integration tests for gcs_ocn_bq_ingest""" import json import os import uuid from typing import List import pytest from google.cloud import bigquery from google.cloud import error_reporting from google.cloud import storage import gcs_ocn_bq_ingest.common.ordering import gcs_ocn_bq_ingest.common.utils TEST_DIR = o...
0.543106
0.248278
import datetime import collections import os import unittest import pickle import numpy as np import xarray as xr import pyinterp.backends.xarray import pyinterp class Degraded(unittest.TestCase): def test_axis_identifier(self): ident = pyinterp.backends.xarray.AxisIdentifier(xr.DataArray()) self....
tests/test_interpolator.py
import datetime import collections import os import unittest import pickle import numpy as np import xarray as xr import pyinterp.backends.xarray import pyinterp class Degraded(unittest.TestCase): def test_axis_identifier(self): ident = pyinterp.backends.xarray.AxisIdentifier(xr.DataArray()) self....
0.651466
0.625667
import sys sys.path.append('../..') import unittest import numpy as np import pandas as pd from sklearn import linear_model from ramp.estimators import (Probabilities, BinaryProbabilities, wrap_sklearn_like_estimator) from ramp import shortcuts from ramp.tests...
ramp/tests/test_estimators.py
import sys sys.path.append('../..') import unittest import numpy as np import pandas as pd from sklearn import linear_model from ramp.estimators import (Probabilities, BinaryProbabilities, wrap_sklearn_like_estimator) from ramp import shortcuts from ramp.tests...
0.562417
0.455744
import numpy as np from sympl import ( Prognostic, get_constant, get_numpy_arrays_with_properties, restore_data_arrays_with_properties ) import spharm Re = get_constant('planetary_radius', 'm') Omega = get_constant('planetary_rotation_rate', 's^-1') class LinearizedDynamics(Prognostic): """ Prescribe...
barotropy/_core/dynamics.py
import numpy as np from sympl import ( Prognostic, get_constant, get_numpy_arrays_with_properties, restore_data_arrays_with_properties ) import spharm Re = get_constant('planetary_radius', 'm') Omega = get_constant('planetary_rotation_rate', 's^-1') class LinearizedDynamics(Prognostic): """ Prescribe...
0.888964
0.533337
from msvc.src.features.featurize import featurize, load_extractor class TestLoadExtractor(object): def test_lda(self) -> None: """test load LinearDiscriminantAnalysis""" from sklearn.discriminant_analysis import LinearDiscriminantAnalysis for lda in [ "ocSVM_sgdline...
msvc/tests/features/test_featurize.py
from msvc.src.features.featurize import featurize, load_extractor class TestLoadExtractor(object): def test_lda(self) -> None: """test load LinearDiscriminantAnalysis""" from sklearn.discriminant_analysis import LinearDiscriminantAnalysis for lda in [ "ocSVM_sgdline...
0.797675
0.349366
import json import re from kobold import compare def parse_body(content_type, content): if content_type is None: return content if content_type == 'application/json': return json.loads(content) elif re.compile('application/json;.*').search(content_type): return json.loads(content)...
kobold/response.py
import json import re from kobold import compare def parse_body(content_type, content): if content_type is None: return content if content_type == 'application/json': return json.loads(content) elif re.compile('application/json;.*').search(content_type): return json.loads(content)...
0.561455
0.319639
import os import unittest import warnings from nose.tools import eq_, ok_ from ddtrace.utils.deprecation import deprecation, deprecated, format_message from ddtrace.utils.formats import asbool, get_env class TestUtilities(unittest.TestCase): def test_asbool(self): # ensure the value is properly cast ...
tests/test_utils.py
import os import unittest import warnings from nose.tools import eq_, ok_ from ddtrace.utils.deprecation import deprecation, deprecated, format_message from ddtrace.utils.formats import asbool, get_env class TestUtilities(unittest.TestCase): def test_asbool(self): # ensure the value is properly cast ...
0.613237
0.242935
import datetime from sqlalchemy import Boolean, Column, Integer, String, Table, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql.sqltypes import DateTime from ..database import mapper_registry from app.entities.case import Case, DocketEntry, DistrictCase, AppellateCase cases_table = Table( '...
app/data/case/case.py
import datetime from sqlalchemy import Boolean, Column, Integer, String, Table, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql.sqltypes import DateTime from ..database import mapper_registry from app.entities.case import Case, DocketEntry, DistrictCase, AppellateCase cases_table = Table( '...
0.458591
0.131619
import math import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import Dense, Input def MLP(input_dim, hidden_dim_list, w_init=tf.initializers.Orthogonal(0.2), activation=tf.nn.relu, *args, **kwargs): """Multiple fully-connected layers for approximation Args: input_dim (...
rlzoo/common/basic_nets.py
import math import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import Dense, Input def MLP(input_dim, hidden_dim_list, w_init=tf.initializers.Orthogonal(0.2), activation=tf.nn.relu, *args, **kwargs): """Multiple fully-connected layers for approximation Args: input_dim (...
0.889307
0.403508
from __future__ import print_function import os import io try: import httplib2 from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from apiclient import errors from apiclient import http except: print('Run ...
connect_to_drive.py
from __future__ import print_function import os import io try: import httplib2 from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from apiclient import errors from apiclient import http except: print('Run ...
0.517815
0.146606
# A. Distinct values # 1. Comparing sets # Countries recorded as countries of death but not as countries of birth. Distinct method will show the unique values in the document countries = set(db.laureates.distinct("diedCountry")) - set(db.laureates.distinct("bornCountry")) print(countries) # 2. Count countries of affi...
Python/MongoDB/distinct-sets.py
# A. Distinct values # 1. Comparing sets # Countries recorded as countries of death but not as countries of birth. Distinct method will show the unique values in the document countries = set(db.laureates.distinct("diedCountry")) - set(db.laureates.distinct("bornCountry")) print(countries) # 2. Count countries of affi...
0.532668
0.766337
import argparse import plistlib import subprocess import fileinput PLIST_PATH = "MVVMKit/Info.plist" def increment_version(version): components = str(version).split('.') init, last = components[:-1], components[-1:] init.append(str(int(last[0]) + 1)) return ".".join(init) def get_version(): glo...
script/version.py
import argparse import plistlib import subprocess import fileinput PLIST_PATH = "MVVMKit/Info.plist" def increment_version(version): components = str(version).split('.') init, last = components[:-1], components[-1:] init.append(str(int(last[0]) + 1)) return ".".join(init) def get_version(): glo...
0.286369
0.156427
import cmdc import nose from nose.plugins.skip import SkipTest from maya import cmds from maya.api import OpenMaya from . import assert_equals, as_obj, as_plug, new_scene def test_createNode(): return node = cmds.createNode('transform', name='root') node_obj = as_obj(node) null_obj = cmdc.Object()...
tests/test_MDagModifier.py
import cmdc import nose from nose.plugins.skip import SkipTest from maya import cmds from maya.api import OpenMaya from . import assert_equals, as_obj, as_plug, new_scene def test_createNode(): return node = cmds.createNode('transform', name='root') node_obj = as_obj(node) null_obj = cmdc.Object()...
0.471953
0.301086
from collections import OrderedDict from onegov.ballot.constants import election_day_i18n_used_locales from onegov.ballot.models.election.candidate import Candidate from onegov.ballot.models.election.candidate_result import CandidateResult from onegov.ballot.models.election.election import Election from onegov.ballot.m...
src/onegov/ballot/models/election/election_compound.py
from collections import OrderedDict from onegov.ballot.constants import election_day_i18n_used_locales from onegov.ballot.models.election.candidate import Candidate from onegov.ballot.models.election.candidate_result import CandidateResult from onegov.ballot.models.election.election import Election from onegov.ballot.m...
0.835215
0.196479
import xlrd import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from viaReservation.test_genericFunctions import generic class test_flightReservat...
Automation project demo/Page Object Model/flightReservationPage.py
import xlrd import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from viaReservation.test_genericFunctions import generic class test_flightReservat...
0.210848
0.057203
import sys import urllib import utils import json import argparse import urllib.request from rdflib import URIRef, BNode, Literal, Graph import glob def parse_args(args=sys.argv[1:]): """ Get the parsed arguments specified on this script. """ parser = argparse.ArgumentParser(description="") parser.add...
src/LdGenerator.py
import sys import urllib import utils import json import argparse import urllib.request from rdflib import URIRef, BNode, Literal, Graph import glob def parse_args(args=sys.argv[1:]): """ Get the parsed arguments specified on this script. """ parser = argparse.ArgumentParser(description="") parser.add...
0.344443
0.096025
from collections import namedtuple import numpy as np from scipy.interpolate import PPoly import cvxopt cvxopt.solvers.options['show_progress'] = False cvxopt.solvers.options['maxiters'] = 500 # seems to reduce errors (unconfirmed) from likelihood_funcs import * ''' TODO - improve "smoothness" input parameter ...
cdf_est_CVXOPT.py
from collections import namedtuple import numpy as np from scipy.interpolate import PPoly import cvxopt cvxopt.solvers.options['show_progress'] = False cvxopt.solvers.options['maxiters'] = 500 # seems to reduce errors (unconfirmed) from likelihood_funcs import * ''' TODO - improve "smoothness" input parameter ...
0.374791
0.539105
# pyright: reportMissingImports=false # pylint: disable=import-error import numpy as np import tensorflow as tf from ..utils.tensor import from_float32_to_uint8, from_uint8_to_float32 # pylint: enable=import-error __email__ = "<EMAIL>" __author__ = "Deezer Research" __license__ = "MIT License" def to_n_channels(wa...
spleeter/audio/convertor.py
# pyright: reportMissingImports=false # pylint: disable=import-error import numpy as np import tensorflow as tf from ..utils.tensor import from_float32_to_uint8, from_uint8_to_float32 # pylint: enable=import-error __email__ = "<EMAIL>" __author__ = "Deezer Research" __license__ = "MIT License" def to_n_channels(wa...
0.941808
0.52275
from intern.remote import Remote from intern.resource.local.resource import * from intern.service.local.metadata import MetadataService import os.path LATEST_VERSION = 'v0' CONFIG_HOST = "host" CONFIG_DATASTORE = "datastore" filePath = "" datastore = "" class LocalRemote(Remote): def __init__(self, specs, version=...
intern/remote/local/remote.py
from intern.remote import Remote from intern.resource.local.resource import * from intern.service.local.metadata import MetadataService import os.path LATEST_VERSION = 'v0' CONFIG_HOST = "host" CONFIG_DATASTORE = "datastore" filePath = "" datastore = "" class LocalRemote(Remote): def __init__(self, specs, version=...
0.765681
0.319201
from flask import current_app as app from wtforms import StringField, SubmitField from flask_wtf import FlaskForm from wtforms.validators import ValidationError, DataRequired # CONTAINS CLASS: # Paper # Authors # Abstract class Paper: def __init__(self, pid, title, year, conference): self.pid = pid ...
app/models/paper.py
from flask import current_app as app from wtforms import StringField, SubmitField from flask_wtf import FlaskForm from wtforms.validators import ValidationError, DataRequired # CONTAINS CLASS: # Paper # Authors # Abstract class Paper: def __init__(self, pid, title, year, conference): self.pid = pid ...
0.559771
0.133868
import pathlib from ted_sws import config from ted_sws.mapping_suite_processor.adapters.allegro_triple_store import AllegroGraphTripleStore def repository_exists(triple_store: AllegroGraphTripleStore, repository_name) -> bool: """ Method to check if the repository is in the triple store :param triple_sto...
ted_sws/mapping_suite_processor/services/load_mapping_suite_output_into_triple_store.py
import pathlib from ted_sws import config from ted_sws.mapping_suite_processor.adapters.allegro_triple_store import AllegroGraphTripleStore def repository_exists(triple_store: AllegroGraphTripleStore, repository_name) -> bool: """ Method to check if the repository is in the triple store :param triple_sto...
0.473414
0.160858
from sqlalchemy.exc import SQLAlchemyError from setup import Category, Item import bleach def getCategories(session): """ Retrieve all categories. :param session: (DBSession) SQLAlchemy session :return: List of Category objects. """ try: categories = (session.query(Category) ...
queryhelpers.py
from sqlalchemy.exc import SQLAlchemyError from setup import Category, Item import bleach def getCategories(session): """ Retrieve all categories. :param session: (DBSession) SQLAlchemy session :return: List of Category objects. """ try: categories = (session.query(Category) ...
0.617628
0.258391
from django.db import models from django.contrib.auth.models import User """ customized, app specific imports """ from laptops101 import customValidators as v class AssetTag(models.Model): """ Maintains a list of Asset Tags for sole purpose of input validation across several tables """ ASSET_TAG = m...
laptops101/models.py
from django.db import models from django.contrib.auth.models import User """ customized, app specific imports """ from laptops101 import customValidators as v class AssetTag(models.Model): """ Maintains a list of Asset Tags for sole purpose of input validation across several tables """ ASSET_TAG = m...
0.532668
0.139367
from pathlib import Path import logging class RecordingManager: """ Manages the recordings of a Vesper archive. The main responsibility of a recording manager is to convert recording file paths between relative and absolute forms. The relative form of a recording file path, stored in the ar...
vesper/util/recording_manager.py
from pathlib import Path import logging class RecordingManager: """ Manages the recordings of a Vesper archive. The main responsibility of a recording manager is to convert recording file paths between relative and absolute forms. The relative form of a recording file path, stored in the ar...
0.786869
0.310511
from __future__ import absolute_import from fortrace.botnet.common.loggerbase import LoggerBase from fortrace.core.guest import Guest __author__ = '<NAME>' class GroupManager(LoggerBase): """ Manages symbolic names. Bridge between symbolic names and bot registry as well as the payload registry. R...
src/fortrace/botnet/core/bmoncomponents/groupmanager.py
from __future__ import absolute_import from fortrace.botnet.common.loggerbase import LoggerBase from fortrace.core.guest import Guest __author__ = '<NAME>' class GroupManager(LoggerBase): """ Manages symbolic names. Bridge between symbolic names and bot registry as well as the payload registry. R...
0.560373
0.187821
from __future__ import absolute_import, print_function import logging import threading import requests from . import wake_on_lan from .utils import LogIt, LogItWithReturn logger = logging.getLogger('samsungctl') class WebSocketBase(object): """Base class for TV's with websocket connection.""" @LogIt de...
samsungctl/websocket_base.py
from __future__ import absolute_import, print_function import logging import threading import requests from . import wake_on_lan from .utils import LogIt, LogItWithReturn logger = logging.getLogger('samsungctl') class WebSocketBase(object): """Base class for TV's with websocket connection.""" @LogIt de...
0.736874
0.069258
import json from vutil import * import os from vulkan import * from buffer import * from pathlib import Path here = os.path.dirname(os.path.abspath(__file__)) class Stage(Sinode): def __init__(self, pipeline, setupDict): Sinode.__init__(self, pipeline) self.vkInstance = pipeline.instance.vkInstance self.vkDevic...
vulkanese/stage.py
import json from vutil import * import os from vulkan import * from buffer import * from pathlib import Path here = os.path.dirname(os.path.abspath(__file__)) class Stage(Sinode): def __init__(self, pipeline, setupDict): Sinode.__init__(self, pipeline) self.vkInstance = pipeline.instance.vkInstance self.vkDevic...
0.107907
0.084342
class FiniteField: """ 有限体 """ def __init__(self, p): self.p = p def xgcd(self, a, b): x0, x1, y0, y1 = 1, 0, 0, 1 while b != 0: q, a, b = a // b, b, a % b x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return a, x0, y0 def modIn...
Gathered CTF writeups/ptr-yudai-writeups/2019/Newbie_CTF_2019/is_it_ecc/EllipticCurve.py
class FiniteField: """ 有限体 """ def __init__(self, p): self.p = p def xgcd(self, a, b): x0, x1, y0, y1 = 1, 0, 0, 1 while b != 0: q, a, b = a // b, b, a % b x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return a, x0, y0 def modIn...
0.500488
0.464719
import numpy as np import matplotlib.pyplot as plt from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from pathlib import Path import re #%% parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("--result_dir", type=Path, required=True) parser.add_argument("--figu...
Experiment_1/src/NPB-DAA/summary_summary.py
import numpy as np import matplotlib.pyplot as plt from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from pathlib import Path import re #%% parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("--result_dir", type=Path, required=True) parser.add_argument("--figu...
0.424173
0.235229