code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from .PyDIP_bin import ImageDisplay import importlib.util hasMatPlotLib = True reportedPlotLib = False if importlib.util.find_spec('matplotlib') is None: hasMatPlotLib = False else: import matplotlib import matplotlib.pyplot as pp import numpy as np # Label color map from the function of the same nam...
pydip/src/PyDIP_py.py
from .PyDIP_bin import ImageDisplay import importlib.util hasMatPlotLib = True reportedPlotLib = False if importlib.util.find_spec('matplotlib') is None: hasMatPlotLib = False else: import matplotlib import matplotlib.pyplot as pp import numpy as np # Label color map from the function of the same nam...
0.754282
0.614799
import argparse import os.path from xml.dom.minidom import Document, parse import traceback from io import StringIO, SEEK_SET import logging logger = logging.getLogger(__name__) def read_colors_xml(filepath_or_stream, orig_color_map: dict = None): if orig_color_map is not None: color_map = orig_color_map...
drawable2svg/VectorDrawable2Svg.py
import argparse import os.path from xml.dom.minidom import Document, parse import traceback from io import StringIO, SEEK_SET import logging logger = logging.getLogger(__name__) def read_colors_xml(filepath_or_stream, orig_color_map: dict = None): if orig_color_map is not None: color_map = orig_color_map...
0.542863
0.132122
import json import logging from datetime import datetime class PluginManager(object): def __init__(self, bot, test_mode=False): self.bot = bot self.config = bot.config self.dispatcher = bot.dispatcher self.log = logging.getLogger(type(self).__name__) self.plugins = [] ...
slackminion/plugin/manager.py
import json import logging from datetime import datetime class PluginManager(object): def __init__(self, bot, test_mode=False): self.bot = bot self.config = bot.config self.dispatcher = bot.dispatcher self.log = logging.getLogger(type(self).__name__) self.plugins = [] ...
0.192312
0.062962
import subprocess import sys import os __author__ = "<NAME>" __copyright__ = "Copyright (C) Nginx, Inc. All rights reserved." __credits__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"] __license__ = "" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" def color_print(message, color='green'): if col...
tools/builders/util.py
import subprocess import sys import os __author__ = "<NAME>" __copyright__ = "Copyright (C) Nginx, Inc. All rights reserved." __credits__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"] __license__ = "" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" def color_print(message, color='green'): if col...
0.182936
0.053601
import os import copy from minio import Minio from .cache_model import CacheModel class COSModel(CacheModel): """ Abstract implementation of a model cached from Cloud Object Storage (COS). """ def __init__( self, uri, task, data_type, cache_dir, filename=None, **kwargs ): """ ...
depiction/models/uri/cache/cos_model.py
import os import copy from minio import Minio from .cache_model import CacheModel class COSModel(CacheModel): """ Abstract implementation of a model cached from Cloud Object Storage (COS). """ def __init__( self, uri, task, data_type, cache_dir, filename=None, **kwargs ): """ ...
0.797004
0.146697
import vtk def main(): colors = vtk.vtkNamedColors() Pr = 10.0 # The Lorenz parameters b = 2.667 r = 28.0 # x = 0.0 # y = 0.0 # z = 0.0 # starting (and current) x, y, z h = 0.01 # integration step size resolution = 200 # slice resolution iterations = 10000000 # number of ...
src/Python/Visualization/Lorenz.py
import vtk def main(): colors = vtk.vtkNamedColors() Pr = 10.0 # The Lorenz parameters b = 2.667 r = 28.0 # x = 0.0 # y = 0.0 # z = 0.0 # starting (and current) x, y, z h = 0.01 # integration step size resolution = 200 # slice resolution iterations = 10000000 # number of ...
0.61878
0.49585
import torch import torch.nn as nn import sys sys.path.append(r'../input/timmyy/pytorch-image-models-master') import timm import numpy as np from torch.utils.data import Dataset, DataLoader import torch.optim as optim import pandas as pd import matplotlib.pyplot as plt import os import cv2 from sklearn.model_selection ...
final.py
import torch import torch.nn as nn import sys sys.path.append(r'../input/timmyy/pytorch-image-models-master') import timm import numpy as np from torch.utils.data import Dataset, DataLoader import torch.optim as optim import pandas as pd import matplotlib.pyplot as plt import os import cv2 from sklearn.model_selection ...
0.779322
0.376423
import logging import os import celery from celery import chain from django.conf import settings from django.utils import timezone from annotation.annotation_version_querysets import get_unannotated_variants_qs from annotation.models import AnnotationStatus, GenomeBuild from annotation.models.models import Annotation...
annotation/tasks/annotate_variants.py
import logging import os import celery from celery import chain from django.conf import settings from django.utils import timezone from annotation.annotation_version_querysets import get_unannotated_variants_qs from annotation.models import AnnotationStatus, GenomeBuild from annotation.models.models import Annotation...
0.350199
0.080755
import sys import unittest import numpy import ideep4py from ideep4py import linear try: import testing from testing import condition except Exception as ex: print('*** testing directory is missing: %s' % ex) sys.exit(-1) @testing.parameterize(*testing.product({ 'x_dtype': [numpy.float32], 'W...
tests/dnn_tests/test_linear_py_f32.py
import sys import unittest import numpy import ideep4py from ideep4py import linear try: import testing from testing import condition except Exception as ex: print('*** testing directory is missing: %s' % ex) sys.exit(-1) @testing.parameterize(*testing.product({ 'x_dtype': [numpy.float32], 'W...
0.463687
0.610076
from django.db import models, transaction from django.utils import timezone from django.core import validators from django.contrib.auth.models import AbstractUser from main.utils.string_utils import generate_noise from main.utils.user_utils import validate_multiuser_csv class User(AbstractUser): """用户""" cl...
main/models/user.py
from django.db import models, transaction from django.utils import timezone from django.core import validators from django.contrib.auth.models import AbstractUser from main.utils.string_utils import generate_noise from main.utils.user_utils import validate_multiuser_csv class User(AbstractUser): """用户""" cl...
0.371365
0.135604
from typing import Any from kivy.app import App from kivy.lang.builder import Builder from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty, NumericProperty, ListProperty Builder.load_string(""" <LabeledValue>: canvas: Color: rgba: root.box_color Line: ...
src/kwidgets/text/labeledvalue.py
from typing import Any from kivy.app import App from kivy.lang.builder import Builder from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty, NumericProperty, ListProperty Builder.load_string(""" <LabeledValue>: canvas: Color: rgba: root.box_color Line: ...
0.894453
0.360686
import superimport import os import time import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import PIL import imageio import torch from torch import nn from torch.nn import functional as F import torchvision from torchvision import transforms from torchvision import datasets from torch.utils...
scripts/vae_helpers_pytorch.py
import superimport import os import time import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import PIL import imageio import torch from torch import nn from torch.nn import functional as F import torchvision from torchvision import transforms from torchvision import datasets from torch.utils...
0.882984
0.415373
from control.parse.base.baseparser import baseparser import xml.sax.handler from utils.singleton import singleton #Graph Imports from model.graph import GraphIncidenceSet as Graph from utils.map_utils import geo_distance #Source Management Imports from os.path import isfile as isfile import StringIO #Exception Import f...
control/parse/sax.py
from control.parse.base.baseparser import baseparser import xml.sax.handler from utils.singleton import singleton #Graph Imports from model.graph import GraphIncidenceSet as Graph from utils.map_utils import geo_distance #Source Management Imports from os.path import isfile as isfile import StringIO #Exception Import f...
0.632843
0.16455
import os import sys from django.contrib.messages import ERROR, INFO, SUCCESS, WARNING from django.utils.translation import ugettext_lazy as _ SITE = { "project_name": "itDAGENE 2018", "name": "itDAGENE", "email": "<EMAIL>", "contact_email": "<EMAIL>", "domain": "itdagene.no", "mail_base": "ht...
itdagene/settings/base.py
import os import sys from django.contrib.messages import ERROR, INFO, SUCCESS, WARNING from django.utils.translation import ugettext_lazy as _ SITE = { "project_name": "itDAGENE 2018", "name": "itDAGENE", "email": "<EMAIL>", "contact_email": "<EMAIL>", "domain": "itdagene.no", "mail_base": "ht...
0.223123
0.148109
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import urllib3 import traceback from typing import Any, Dict, List, Optional # Disable insecure warnings urllib3.disable_warnings() ''' CONSTANTS ''' ACCEPTED_TAGS = ['account_takeover', 'bec', 'brand_impersonation...
Packs/EmailRepIO/Integrations/EmailRepIO/EmailRepIO.py
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import urllib3 import traceback from typing import Any, Dict, List, Optional # Disable insecure warnings urllib3.disable_warnings() ''' CONSTANTS ''' ACCEPTED_TAGS = ['account_takeover', 'bec', 'brand_impersonation...
0.727685
0.096706
import os import re from google.appengine.ext import testbed import webapp2 import webtest from handlers import build_failure from handlers import handlers_util from handlers import result_status from model.wf_analysis import WfAnalysis from model import analysis_status from model.wf_analysis import WfAnalysis from...
appengine/findit/handlers/test/build_failure_test.py
import os import re from google.appengine.ext import testbed import webapp2 import webtest from handlers import build_failure from handlers import handlers_util from handlers import result_status from model.wf_analysis import WfAnalysis from model import analysis_status from model.wf_analysis import WfAnalysis from...
0.336767
0.130729
import pandas as pd import numpy as np import requests import unicodedata import string import re from fuzzywuzzy import fuzz, process from bs4 import BeautifulSoup from tqdm import tqdm # ----------- UTILITY --------------- def clean_string(string): string = unicodedata.normalize('NFKD',string) \ .encode(...
scraper.py
import pandas as pd import numpy as np import requests import unicodedata import string import re from fuzzywuzzy import fuzz, process from bs4 import BeautifulSoup from tqdm import tqdm # ----------- UTILITY --------------- def clean_string(string): string = unicodedata.normalize('NFKD',string) \ .encode(...
0.467818
0.275367
import math from sys import maxsize MAX_XY = 50 # 地图尺寸 class State(object): def __init__(self, x, y): self.x = x self.y = y self.parent = None self.state = "." self.t = "new" self.g = maxsize self.h = 0 self.f = maxsize self.fvalue = max...
ARA-star/ara_star.py
import math from sys import maxsize MAX_XY = 50 # 地图尺寸 class State(object): def __init__(self, x, y): self.x = x self.y = y self.parent = None self.state = "." self.t = "new" self.g = maxsize self.h = 0 self.f = maxsize self.fvalue = max...
0.080847
0.286107
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library import time,threading import os import sys import Adafruit_DHT import syslog from mikezlcd import * lcd = lcd_module(2004, 25, 24, 22, 18, 17,23) lcd.disp(0,0,"Booting...") import psycopg2 try: f = open("/etc/dbconn.txt", "r") dsn=f.readline().strip(...
controller.py
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library import time,threading import os import sys import Adafruit_DHT import syslog from mikezlcd import * lcd = lcd_module(2004, 25, 24, 22, 18, 17,23) lcd.disp(0,0,"Booting...") import psycopg2 try: f = open("/etc/dbconn.txt", "r") dsn=f.readline().strip(...
0.128717
0.090133
from random import choice import faker f = faker.Faker('zh_CN') # address print('f.country(): {}'.format(f.country())) print('f.country_code(): {}'.format(f.country_code())) print('f.address(): {}'.format(f.address())) print('f.city: {}'.format(f.city())) print('f.city_name: {}'.format(f.city_name())) print('f.city_...
demo/lib/faker_demo.py
from random import choice import faker f = faker.Faker('zh_CN') # address print('f.country(): {}'.format(f.country())) print('f.country_code(): {}'.format(f.country_code())) print('f.address(): {}'.format(f.address())) print('f.city: {}'.format(f.city())) print('f.city_name: {}'.format(f.city_name())) print('f.city_...
0.093704
0.086439
from pypyr.context import Context from pypyr.dsl import SicString from pypyr.errors import KeyInContextHasNoValueError, KeyNotInContextError import pypyr.steps.jsonparse as jsonparse import pytest def test_jsonparse_no_jsonparse_raises(): """No jsonparse input raises.""" context = Context({ 'k1': 'v1'...
tests/unit/pypyr/steps/jsonparse_test.py
from pypyr.context import Context from pypyr.dsl import SicString from pypyr.errors import KeyInContextHasNoValueError, KeyNotInContextError import pypyr.steps.jsonparse as jsonparse import pytest def test_jsonparse_no_jsonparse_raises(): """No jsonparse input raises.""" context = Context({ 'k1': 'v1'...
0.835148
0.531939
import os import json import numpy as np from tqdm import tqdm import torch import argparse from amortized_synthesis.utils import add_args, AverageMeter, stable_smooth_regularizer, rb_state_proj, \ rb_smooth_regularizer, rb_sample_obs, rb_collision_penalty, rb_collision_detection, load_rb_mesh_points_to_opt from am...
amortized_synthesis/train.py
import os import json import numpy as np from tqdm import tqdm import torch import argparse from amortized_synthesis.utils import add_args, AverageMeter, stable_smooth_regularizer, rb_state_proj, \ rb_smooth_regularizer, rb_sample_obs, rb_collision_penalty, rb_collision_detection, load_rb_mesh_points_to_opt from am...
0.617974
0.412057
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, unescapeHTML, ) class SteamIE(InfoExtractor): _VALID_URL = r"""(?x) https?://store\.steampowered\.com/ (agecheck/)? (?P<urltype>video|app)/ #If the pa...
youtube_dl/extractor/steam.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, unescapeHTML, ) class SteamIE(InfoExtractor): _VALID_URL = r"""(?x) https?://store\.steampowered\.com/ (agecheck/)? (?P<urltype>video|app)/ #If the pa...
0.298798
0.154121
from pypint.communicators.i_communication_provider import ICommunicationProvider from pypint.utilities import assert_condition, assert_named_argument from pypint.utilities.logging import this_got_called class ForwardSendingMessaging(ICommunicationProvider): """A linear forward-directed communication pattern "...
pypint/communicators/forward_sending_messaging.py
from pypint.communicators.i_communication_provider import ICommunicationProvider from pypint.utilities import assert_condition, assert_named_argument from pypint.utilities.logging import this_got_called class ForwardSendingMessaging(ICommunicationProvider): """A linear forward-directed communication pattern "...
0.855625
0.164148
import base64 import datetime import hashlib import json import logging import os import pathlib import re import shutil import subprocess import tempfile import time from homie.node.node_base import Node_Base from homie.node.property.property_datetime import Property_DateTime from homie.node.property.property_enum im...
src/homie-nodes/homie-apparatus/node_recentimages.py
import base64 import datetime import hashlib import json import logging import os import pathlib import re import shutil import subprocess import tempfile import time from homie.node.node_base import Node_Base from homie.node.property.property_datetime import Property_DateTime from homie.node.property.property_enum im...
0.443118
0.171685
import os import sublime SETTINGS = sublime.load_settings("env-import.sublime-settings") FILES = SETTINGS.get("files") def parse(line): """parse line and return a dictionary with variable value""" if line.lstrip().startswith('#'): return {} if not line.lstrip(): return {} """find the ...
env_import.py
import os import sublime SETTINGS = sublime.load_settings("env-import.sublime-settings") FILES = SETTINGS.get("files") def parse(line): """parse line and return a dictionary with variable value""" if line.lstrip().startswith('#'): return {} if not line.lstrip(): return {} """find the ...
0.400984
0.10226
from ....errors import SimMemoryError class IndirectJumpResolver: def __init__(self, project, timeless=False, base_state=None): self.project = project self.timeless = timeless self.base_state = base_state def filter(self, cfg, addr, func_addr, block, jumpkind): """ Che...
angr/analyses/cfg/indirect_jump_resolvers/resolver.py
from ....errors import SimMemoryError class IndirectJumpResolver: def __init__(self, project, timeless=False, base_state=None): self.project = project self.timeless = timeless self.base_state = base_state def filter(self, cfg, addr, func_addr, block, jumpkind): """ Che...
0.836655
0.44059
import sys import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KDTree from mpl_toolkits.mplot3d import Axes3D from sklearn.mixture import GaussianMixture class PrincipalCurve: """Subspace Constrained Mean Shift algorithm based on the paper "Locally Defined Principal Cur...
principal_curve.py
import sys import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KDTree from mpl_toolkits.mplot3d import Axes3D from sklearn.mixture import GaussianMixture class PrincipalCurve: """Subspace Constrained Mean Shift algorithm based on the paper "Locally Defined Principal Cur...
0.684686
0.61708
"""Module for creating yaml based configuration files for adding layers in the neuroglancer.""" import os import yaml defaultconfigdata = [ dict(ngspace='FAFB', dimension=dict( x=1, y=1, z=1, units='um'), voxelsize=dict( x=4, ...
pyroglancer/createconfig.py
"""Module for creating yaml based configuration files for adding layers in the neuroglancer.""" import os import yaml defaultconfigdata = [ dict(ngspace='FAFB', dimension=dict( x=1, y=1, z=1, units='um'), voxelsize=dict( x=4, ...
0.756447
0.14885
from urllib.parse import quote_plus import logging from typing import List from dacite import from_dict from dacite.exceptions import ( DaciteFieldError, ForwardReferenceError, MissingValueError, UnexpectedDataError, WrongTypeError, ) from pymongo import MongoClient from pymongo.errors import Connec...
bridges/database/mongo.py
from urllib.parse import quote_plus import logging from typing import List from dacite import from_dict from dacite.exceptions import ( DaciteFieldError, ForwardReferenceError, MissingValueError, UnexpectedDataError, WrongTypeError, ) from pymongo import MongoClient from pymongo.errors import Connec...
0.617513
0.090977
import numpy as np import matplotlib.pyplot as plt import math def feval(funcName, *args): return eval(funcName)(*args) def RungeKutta4thOrder(func, yinit, xspan, h): m = len(yinit) n = int((xspan[-1] - xspan[0]) / h) x = xspan[0] y = yinit xsol = np.empty((0)) xsol = np.append(xsol, x)...
Topic 5 - Solving Differential Equations/29.ADAMs/Adam4.py
import numpy as np import matplotlib.pyplot as plt import math def feval(funcName, *args): return eval(funcName)(*args) def RungeKutta4thOrder(func, yinit, xspan, h): m = len(yinit) n = int((xspan[-1] - xspan[0]) / h) x = xspan[0] y = yinit xsol = np.empty((0)) xsol = np.append(xsol, x)...
0.203391
0.712548
import numpy as np import torch import torch.nn.functional as F from pprint import pprint def to_tensor(x): if isinstance(x, torch.Tensor): return x elif isinstance(x, list): if isinstance(x[0], float): return torch.Tensor(x) elif isinstance(x[0], int): return...
utility/common_utils/tensor_utils.py
import numpy as np import torch import torch.nn.functional as F from pprint import pprint def to_tensor(x): if isinstance(x, torch.Tensor): return x elif isinstance(x, list): if isinstance(x[0], float): return torch.Tensor(x) elif isinstance(x[0], int): return...
0.57093
0.627752
import tensorflow as tf from .. import layers from ..utils import anchors as utils_anchors def add_target_ops( annotations_batch, anchors, num_classes, use_class_specific_bbox=False, positive_overlap=0.5, negative_overlap=0.4 ): """ Compute the classification and regression targets giv...
tensorbreeze/retinanet/_loss.py
import tensorflow as tf from .. import layers from ..utils import anchors as utils_anchors def add_target_ops( annotations_batch, anchors, num_classes, use_class_specific_bbox=False, positive_overlap=0.5, negative_overlap=0.4 ): """ Compute the classification and regression targets giv...
0.84891
0.411229
import csv import datetime from collections import defaultdict from dateutil import parser from copy import deepcopy import sys, getopt from collections import OrderedDict, Callable import argparse #http://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python class DefaultOrderedDict(OrderedDi...
churn_by_cohort.py
import csv import datetime from collections import defaultdict from dateutil import parser from copy import deepcopy import sys, getopt from collections import OrderedDict, Callable import argparse #http://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python class DefaultOrderedDict(OrderedDi...
0.261425
0.117319
from numpy import linalg as LA import matplotlib.pyplot as plt import numpy as np def computeErrorForaSample(w, k, y, d=5): error = 0 for i in range(1, d+1): error += w[i]*y[k-i] error = y[k]-error return error def computeDerivativeComponent(w, y, d=5): derivative = 0 for i in range...
Supervised Learning/SMAI HWS/17/3.py
from numpy import linalg as LA import matplotlib.pyplot as plt import numpy as np def computeErrorForaSample(w, k, y, d=5): error = 0 for i in range(1, d+1): error += w[i]*y[k-i] error = y[k]-error return error def computeDerivativeComponent(w, y, d=5): derivative = 0 for i in range...
0.404037
0.645986
import asyncio from tortoise.transactions import atomic from html import unescape from aiohttp import ClientSession import re from typing import Any, Coroutine, Dict, List from libkol import Bonus, Effect, Item, Modifier, Skill, Outfit, Familiar from libkol.util import expression from util import load_mafia_data, ma...
tools/bonuses.py
import asyncio from tortoise.transactions import atomic from html import unescape from aiohttp import ClientSession import re from typing import Any, Coroutine, Dict, List from libkol import Bonus, Effect, Item, Modifier, Skill, Outfit, Familiar from libkol.util import expression from util import load_mafia_data, ma...
0.646906
0.20201
import bpy import mathutils import string import math scene = bpy.context.scene dummy = bpy.data.objects.new('voodoo_scene', None) dummy.location = (0.0, 0.0, 0.0) dummy.rotation_euler = ( -3.141593/2, 0.0, 0.0) dummy.scale = (0.2, 0.2, 0.2) scene.objects.link(dummy) data = bpy.data.cameras.new('voodoo_rend...
DVF/Final Project/11.py
import bpy import mathutils import string import math scene = bpy.context.scene dummy = bpy.data.objects.new('voodoo_scene', None) dummy.location = (0.0, 0.0, 0.0) dummy.rotation_euler = ( -3.141593/2, 0.0, 0.0) dummy.scale = (0.2, 0.2, 0.2) scene.objects.link(dummy) data = bpy.data.cameras.new('voodoo_rend...
0.260672
0.115187
import socket, os, threading, datetime MAX_SIZE=512 KEY="Compu2_2020" TODAY=datetime.datetime.now().strftime("%d-%m-%Y_%H:%M:%S") def th_server(sock_full): name = "_" key="_" email="_" sock,addr = sock_full print("Launching thread... addr: %s" % str(addr)) exit = False ip=str(addr) s...
exercises/exercise11_server_stream.py
import socket, os, threading, datetime MAX_SIZE=512 KEY="Compu2_2020" TODAY=datetime.datetime.now().strftime("%d-%m-%Y_%H:%M:%S") def th_server(sock_full): name = "_" key="_" email="_" sock,addr = sock_full print("Launching thread... addr: %s" % str(addr)) exit = False ip=str(addr) s...
0.03293
0.068257
import sys from typing import Any, Dict, Tuple import boto3 import click import tabulate from botocore.exceptions import ClientError from mypy_boto3_codecommit.client import CodeCommitClient def get_account_alias(session: boto3.Session) -> str: """ Returns the account alias if one is available, otherwise the...
all_open_prs.py
import sys from typing import Any, Dict, Tuple import boto3 import click import tabulate from botocore.exceptions import ClientError from mypy_boto3_codecommit.client import CodeCommitClient def get_account_alias(session: boto3.Session) -> str: """ Returns the account alias if one is available, otherwise the...
0.373762
0.096195
import pytest from diffy_api.analysis.views import * # noqa @pytest.mark.parametrize("token,status", [("", 200)]) def test_analysis_list_get(client, token, status): assert client.get(api.url_for(AnalysisList), headers=token).status_code == status @pytest.mark.parametrize("token,status", [("", 400)]) def test_a...
tests/test_analysis.py
import pytest from diffy_api.analysis.views import * # noqa @pytest.mark.parametrize("token,status", [("", 200)]) def test_analysis_list_get(client, token, status): assert client.get(api.url_for(AnalysisList), headers=token).status_code == status @pytest.mark.parametrize("token,status", [("", 400)]) def test_a...
0.491212
0.500305
import flask import flask_cors import os # I had to get these values from env, # because We can initialize these values from flask config only on app context, # and some modules already got these values before initialization. restapi_version: str = os.environ.get('RESTAPI_VERSION') server_name: str = os.environ.get('S...
app/api/__init__.py
import flask import flask_cors import os # I had to get these values from env, # because We can initialize these values from flask config only on app context, # and some modules already got these values before initialization. restapi_version: str = os.environ.get('RESTAPI_VERSION') server_name: str = os.environ.get('S...
0.192312
0.047228
from unittest import skip from django.template.defaultfilters import date as datefilter from hth.core.tests.selenium import SeleniumTestCase from hth.shows.tests.factories import ( GigFactory, PastGigFactory, UpcomingGigFactory) @skip('Out of sync with markup') class ShowsTestCase(SeleniumTestCase): def se...
hth/tests/test_shows.py
from unittest import skip from django.template.defaultfilters import date as datefilter from hth.core.tests.selenium import SeleniumTestCase from hth.shows.tests.factories import ( GigFactory, PastGigFactory, UpcomingGigFactory) @skip('Out of sync with markup') class ShowsTestCase(SeleniumTestCase): def se...
0.575588
0.381738
# Imagine you are building a compiler. # Before running any code, the compiler must check that the parentheses in the program are balanced. # Every opening bracket must have a corresponding closing bracket. We can approximate this using strings. # Given a string containing just the characters '(', ')', '{', '}', '[' ...
Array/Balanced Paranthesis Problem.py
# Imagine you are building a compiler. # Before running any code, the compiler must check that the parentheses in the program are balanced. # Every opening bracket must have a corresponding closing bracket. We can approximate this using strings. # Given a string containing just the characters '(', ')', '{', '}', '[' ...
0.741768
0.425009
from __future__ import print_function, absolute_import # Compatibility with python 2 and 3 class PixelMask: """ CXI bitmasks follow the formalism described in Maia (2012) [#Maia2012]_ (see also `www.cxidb.org <http://www.cxidb.org>`_) and encode the status of detector pixels. In *Condor* these bitmasks are rep...
condor/utils/pixelmask.py
from __future__ import print_function, absolute_import # Compatibility with python 2 and 3 class PixelMask: """ CXI bitmasks follow the formalism described in Maia (2012) [#Maia2012]_ (see also `www.cxidb.org <http://www.cxidb.org>`_) and encode the status of detector pixels. In *Condor* these bitmasks are rep...
0.821044
0.677194
import numpy as np import sys import optwrapper as ow A = np.array( [ [1.0979, -.0105, .0167 ], [-.0105, 1.0481, .0825], [.0167, .0825, 1.1540] ] ) def instcost( x, u, grad=True ): Q = np.zeros( (3,3) ) R = .01 if( not grad ): return x.dot(Q).dot(x) + u.dot(R).dot(u) return ( x.dot(Q).dot(x)...
examples/socp_sparse_ex1.py
import numpy as np import sys import optwrapper as ow A = np.array( [ [1.0979, -.0105, .0167 ], [-.0105, 1.0481, .0825], [.0167, .0825, 1.1540] ] ) def instcost( x, u, grad=True ): Q = np.zeros( (3,3) ) R = .01 if( not grad ): return x.dot(Q).dot(x) + u.dot(R).dot(u) return ( x.dot(Q).dot(x)...
0.310904
0.487978
import json from urllib.parse import urlencode # py2 import pytest import responses from dhis2 import exceptions from dhis2.api import Api from .common import BASEURL, API_URL @pytest.fixture # BASE FIXTURE def api(): return Api(BASEURL, "admin", "district") @pytest.fixture # BASE FIXTURE def api_with_ap...
tests/test_api.py
import json from urllib.parse import urlencode # py2 import pytest import responses from dhis2 import exceptions from dhis2.api import Api from .common import BASEURL, API_URL @pytest.fixture # BASE FIXTURE def api(): return Api(BASEURL, "admin", "district") @pytest.fixture # BASE FIXTURE def api_with_ap...
0.308919
0.338132
from __future__ import absolute_import import logging from unittest import TestCase import settings import sys, traceback reload(sys) sys.setdefaultencoding("utf-8") import os from AppCompatProcessor import main import tempfile # Setup the logger logger = logging.getLogger() DB = None class TestAppReconscan(TestCase...
test/test_reconscan.py
from __future__ import absolute_import import logging from unittest import TestCase import settings import sys, traceback reload(sys) sys.setdefaultencoding("utf-8") import os from AppCompatProcessor import main import tempfile # Setup the logger logger = logging.getLogger() DB = None class TestAppReconscan(TestCase...
0.415492
0.115063
import os import re import tempfile from plumbum import local from elftools.elf.elffile import ELFFile from elftools.elf.sections import SymbolTableSection from elftools.elf.enums import ENUM_ST_INFO_TYPE from functools import lru_cache def camel_to_snake_case(s): return re.sub(r'(?<!^)(?=[A-Z])', '_', s).lowe...
src/grader/util.py
import os import re import tempfile from plumbum import local from elftools.elf.elffile import ELFFile from elftools.elf.sections import SymbolTableSection from elftools.elf.enums import ENUM_ST_INFO_TYPE from functools import lru_cache def camel_to_snake_case(s): return re.sub(r'(?<!^)(?=[A-Z])', '_', s).lowe...
0.223208
0.113875
import torch def bbox_area(bboxes): """ Compute the areas of bounding boxes. Args: bboxes (:obj:`nn.Tensor[N, 4]`): Bounding boxes to be computed. They are expected to be in ``(x1, y1, x2, y2)`` format. Returns: :obj:`nn.Tensor[N]`: The computed areas. """ return...
nncore/ops/bbox.py
import torch def bbox_area(bboxes): """ Compute the areas of bounding boxes. Args: bboxes (:obj:`nn.Tensor[N, 4]`): Bounding boxes to be computed. They are expected to be in ``(x1, y1, x2, y2)`` format. Returns: :obj:`nn.Tensor[N]`: The computed areas. """ return...
0.975449
0.920861
from __future__ import absolute_import import logging import os import socket import sys import mitogen import mitogen.core import mitogen.master import mitogen.parent import mitogen.service import mitogen.unix import mitogen.utils import ansible_mitogen.logging import ansible_mitogen.services LOG = logging.getLog...
ansible_mitogen/process.py
from __future__ import absolute_import import logging import os import socket import sys import mitogen import mitogen.core import mitogen.master import mitogen.parent import mitogen.service import mitogen.unix import mitogen.utils import ansible_mitogen.logging import ansible_mitogen.services LOG = logging.getLog...
0.540681
0.192862
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.contrib.table_block.blocks import wagtail.core.blocks import wagtail.core.fields import wagtail.images.blocks class Migration(migrations.Migration): dependencies = [ ('wagtail...
fec/home/migrations/0019_auto_20160907_2152.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.contrib.table_block.blocks import wagtail.core.blocks import wagtail.core.fields import wagtail.images.blocks class Migration(migrations.Migration): dependencies = [ ('wagtail...
0.536799
0.149066
import os import sys import time import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node = cluster.add_instance("node", stay_alive=T...
tests/integration/test_executable_dictionary/test.py
import os import sys import time import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node = cluster.add_instance("node", stay_alive=T...
0.239794
0.361052
from savu.plugins.reconstructions.base_recon import BaseRecon from savu.data.plugin_list import CitationInformation from savu.plugins.driver.gpu_plugin import GpuPlugin import numpy as np # TOmographic MOdel-BAsed Reconstruction (ToMoBAR) # https://github.com/dkazanc/ToMoBAR from tomobar.methodsIR import RecToolsIR f...
savu/plugins/reconstructions/tomobar_recon.py
from savu.plugins.reconstructions.base_recon import BaseRecon from savu.data.plugin_list import CitationInformation from savu.plugins.driver.gpu_plugin import GpuPlugin import numpy as np # TOmographic MOdel-BAsed Reconstruction (ToMoBAR) # https://github.com/dkazanc/ToMoBAR from tomobar.methodsIR import RecToolsIR f...
0.684686
0.636099
from __future__ import division import numpy as np import pandas as pd from glob import glob from astropy.io import fits import matplotlib.pyplot as plt plt.rcParams['xtick.direction'] = 'in' plt.rcParams['ytick.direction'] = 'in' plt.rcParams['axes.spines.right'] = False plt.rcParams['axes.spines.top'] = False plt.rc...
figures/NIRspectra/spectra.py
from __future__ import division import numpy as np import pandas as pd from glob import glob from astropy.io import fits import matplotlib.pyplot as plt plt.rcParams['xtick.direction'] = 'in' plt.rcParams['ytick.direction'] = 'in' plt.rcParams['axes.spines.right'] = False plt.rcParams['axes.spines.top'] = False plt.rc...
0.65368
0.46308
import logging from pathlib import Path from typing import Mapping from tile_processor.db import Db log = logging.getLogger(__name__) class Output: def __init__( self, dir: "DirOutput" = None, db: "DbOutput" = None, kwargs=None ): if kwargs is None: kwargs = {} self.dir =...
tile_processor/output.py
import logging from pathlib import Path from typing import Mapping from tile_processor.db import Db log = logging.getLogger(__name__) class Output: def __init__( self, dir: "DirOutput" = None, db: "DbOutput" = None, kwargs=None ): if kwargs is None: kwargs = {} self.dir =...
0.795142
0.116211
from flask import Flask, render_template, request import sys sys.path.append('C:/Users/900159/Documents/GitHub/TrabalhosPython/Aula35 17-01') sys.path.append('C:/Users/Usuario/Documents/GitHub/TrabalhosPython/Aula35 17-01') from Controller.pessoa_controller import PessoaController from Model.pessoa import Pessoa app =...
Aula35 17-01 HTML/View/web.py
from flask import Flask, render_template, request import sys sys.path.append('C:/Users/900159/Documents/GitHub/TrabalhosPython/Aula35 17-01') sys.path.append('C:/Users/Usuario/Documents/GitHub/TrabalhosPython/Aula35 17-01') from Controller.pessoa_controller import PessoaController from Model.pessoa import Pessoa app =...
0.331228
0.059565
import logging from collections import namedtuple from itertools import groupby from typing import ( Any, Dict, Iterator, Union, ) from pyhocon import ConfigFactory, ConfigTree from databuilder import Scoped from databuilder.extractor.base_extractor import Extractor from databuilder.extractor.sql_alchemy_extract...
databuilder/databuilder/extractor/vertica_metadata_extractor.py
import logging from collections import namedtuple from itertools import groupby from typing import ( Any, Dict, Iterator, Union, ) from pyhocon import ConfigFactory, ConfigTree from databuilder import Scoped from databuilder.extractor.base_extractor import Extractor from databuilder.extractor.sql_alchemy_extract...
0.645455
0.110711
import os import subprocess from util import debug import util max_result = 50 excluded_file_types = ["jpg", "jpeg", "gif", "png", "tif", "psd", "pyc"] class FuzzySuggestion: def __init__( self, filepath, show_hidden=False, git=False ): self._filepath = filepath self._show_hidden = show_hidden self._git...
gnome/gnome2/gedit/plugins.symlink/fuzzyopen/suggestion.py
import os import subprocess from util import debug import util max_result = 50 excluded_file_types = ["jpg", "jpeg", "gif", "png", "tif", "psd", "pyc"] class FuzzySuggestion: def __init__( self, filepath, show_hidden=False, git=False ): self._filepath = filepath self._show_hidden = show_hidden self._git...
0.12552
0.149593
from svd.path_config import build_localized_explanations_path, build_figure_perturbation_path from svd.utils.io import pickle_load from svd.explanations.explanation_utils import THRESHOLD import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="whitegrid") import pandas as pd import numpy as np from ...
svd/visualizations/create_subset_perturbation_figure.py
from svd.path_config import build_localized_explanations_path, build_figure_perturbation_path from svd.utils.io import pickle_load from svd.explanations.explanation_utils import THRESHOLD import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="whitegrid") import pandas as pd import numpy as np from ...
0.616243
0.301362
from math import sqrt import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init import torchvision.models as models __all__ = [ 'PixelShuffleCNN', 'GradualPixelShuffleCNN', ] class PixelShuffleCNN(nn.Module): def __init__(self, upscale_factor): super(PixelShuffleCNN, self...
super_resolution/models.py
from math import sqrt import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init import torchvision.models as models __all__ = [ 'PixelShuffleCNN', 'GradualPixelShuffleCNN', ] class PixelShuffleCNN(nn.Module): def __init__(self, upscale_factor): super(PixelShuffleCNN, self...
0.948763
0.575588
from .generic_parser import GenericParser, ANSI_ESCAPE, REMOVE_CHARS class ZypperParser(GenericParser): @staticmethod def config_reader(stream): # ToDo: future feature raise NotImplementedError() @staticmethod def packages_reader(stream): """ :type stream collections.Iterable Sample text...
ambari-common/src/main/python/ambari_commons/repo_manager/zypper_parser.py
from .generic_parser import GenericParser, ANSI_ESCAPE, REMOVE_CHARS class ZypperParser(GenericParser): @staticmethod def config_reader(stream): # ToDo: future feature raise NotImplementedError() @staticmethod def packages_reader(stream): """ :type stream collections.Iterable Sample text...
0.406862
0.240278
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("node_man", "0048_merge_20210722_1733"), ] operations = [ migrations.AlterField( model_name="job", name="job_type", field=models.CharField( ...
apps/node_man/migrations/0049_auto_20210722_1733.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("node_man", "0048_merge_20210722_1733"), ] operations = [ migrations.AlterField( model_name="job", name="job_type", field=models.CharField( ...
0.385143
0.116036
import cgi import json import urlparse from nose.tools import eq_ import mock from django.core.cache import cache from django.core.urlresolvers import reverse from airmozilla.base.tests.testbase import DjangoTestCase, Response class TestCuratedGroups(DjangoTestCase): def tearDown(self): super(TestCura...
airmozilla/main/tests/views/test_misc.py
import cgi import json import urlparse from nose.tools import eq_ import mock from django.core.cache import cache from django.core.urlresolvers import reverse from airmozilla.base.tests.testbase import DjangoTestCase, Response class TestCuratedGroups(DjangoTestCase): def tearDown(self): super(TestCura...
0.432303
0.149128
import os from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, Optional from cookietemple.common.version import load_ct_template_version from cookietemple.create.domains.cookietemple_template_struct import CookietempleTemplateStruct from cookietemple.create.github_support import pro...
cookietemple/create/domains/cli_creator.py
import os from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, Optional from cookietemple.common.version import load_ct_template_version from cookietemple.create.domains.cookietemple_template_struct import CookietempleTemplateStruct from cookietemple.create.github_support import pro...
0.794943
0.181989
from lark import Lark, UnexpectedToken from .json_parser import json_grammar # Using the grammar from the json_parser example json_parser = Lark(json_grammar, parser='lalr') class JsonSyntaxError(SyntaxError): def __str__(self): context, line, column = self.args return '%s at line %s, column %...
examples/error_reporting_lalr.py
from lark import Lark, UnexpectedToken from .json_parser import json_grammar # Using the grammar from the json_parser example json_parser = Lark(json_grammar, parser='lalr') class JsonSyntaxError(SyntaxError): def __str__(self): context, line, column = self.args return '%s at line %s, column %...
0.57678
0.270766
from tag_type import AprilTagsType aprilStandard41h12 = AprilTagsType( name="aprilStandard41h12", tags=[ 0x000001BD8A64AD10, 0x000001BDC4F3B2D5, 0x000001BDFF82B89A, 0x000001BE3A11BE5F, 0x000001BE74A0C424, 0x000001BEAF2FC9E9, 0x000001BEE9BECFAE, 0x...
apriltag3_create_pdf/tag_aprilStandard41h12.py
from tag_type import AprilTagsType aprilStandard41h12 = AprilTagsType( name="aprilStandard41h12", tags=[ 0x000001BD8A64AD10, 0x000001BDC4F3B2D5, 0x000001BDFF82B89A, 0x000001BE3A11BE5F, 0x000001BE74A0C424, 0x000001BEAF2FC9E9, 0x000001BEE9BECFAE, 0x...
0.272993
0.093678
import sys import numpy as np import torch import torch.nn as nn from torch.nn import init import torch.optim as optim import math import random import os import csv from pathlib import Path from model import model import time from tqdm import tqdm TESTLOSS = False SAVEMODEL = False def read_input(task...
main.py
import sys import numpy as np import torch import torch.nn as nn from torch.nn import init import torch.optim as optim import math import random import os import csv from pathlib import Path from model import model import time from tqdm import tqdm TESTLOSS = False SAVEMODEL = False def read_input(task...
0.369315
0.265717
from io import StringIO import pytest from briefcase.config import parse_config from briefcase.exceptions import BriefcaseConfigError def test_invalid_toml(): "If the config file isn't TOML, raise an error" config_file = StringIO("this is not toml!") with pytest.raises(BriefcaseConfigError, match="Inva...
tests/config/test_parse_config.py
from io import StringIO import pytest from briefcase.config import parse_config from briefcase.exceptions import BriefcaseConfigError def test_invalid_toml(): "If the config file isn't TOML, raise an error" config_file = StringIO("this is not toml!") with pytest.raises(BriefcaseConfigError, match="Inva...
0.669529
0.342654
from datetime import datetime from future.utils import iteritems from . import parsetools as pt def eventChunk(key, lines): """ Parse EVENT chunks """ ## NOTE: RADAR file format not supported currently. ## TODO: Add Support for RADAR file format type values # Contants KEYWORDS = ('EVENT',...
gsshapy/lib/gag_chunk.py
from datetime import datetime from future.utils import iteritems from . import parsetools as pt def eventChunk(key, lines): """ Parse EVENT chunks """ ## NOTE: RADAR file format not supported currently. ## TODO: Add Support for RADAR file format type values # Contants KEYWORDS = ('EVENT',...
0.353986
0.283698
"""Unit tests for TBD.""" from os import getenv as os_getenv from pytest import mark from unittest import TestCase from pyTooling.Common import CurrentPlatform from pyTooling.Common.Platform import Platform if __name__ == "__main__": # pragma: no cover print("ERROR: you called a testcase declaration file as ...
tests/unit/Common/Platform.py
"""Unit tests for TBD.""" from os import getenv as os_getenv from pytest import mark from unittest import TestCase from pyTooling.Common import CurrentPlatform from pyTooling.Common.Platform import Platform if __name__ == "__main__": # pragma: no cover print("ERROR: you called a testcase declaration file as ...
0.479747
0.424114
from datetime import datetime import re from typing import Any, Dict, List, Optional from shapely.geometry import mapping, Polygon import pystac from pystac.utils import str_to_datetime from stactools.core.io import ReadHrefModifier from stactools.core.io.xml import XmlElement from stactools.core.utils import map_opt...
stactools_sentinel2/stactools/sentinel2/product_metadata.py
from datetime import datetime import re from typing import Any, Dict, List, Optional from shapely.geometry import mapping, Polygon import pystac from pystac.utils import str_to_datetime from stactools.core.io import ReadHrefModifier from stactools.core.io.xml import XmlElement from stactools.core.utils import map_opt...
0.831143
0.178383
import sys import os import aiohttp import asyncio import json import pkgutil import mimetypes from aiohttp import web from matlab_desktop_proxy import settings from matlab_desktop_proxy import mwi_environment_variables as mwi_env from matlab_desktop_proxy import util import matlab_desktop_proxy from matlab_desktop_pr...
matlab_desktop_proxy/app.py
import sys import os import aiohttp import asyncio import json import pkgutil import mimetypes from aiohttp import web from matlab_desktop_proxy import settings from matlab_desktop_proxy import mwi_environment_variables as mwi_env from matlab_desktop_proxy import util import matlab_desktop_proxy from matlab_desktop_pr...
0.559049
0.191952
import socket import check import sys import getopt from Tkinter import * def rotate(boardState,n): return boardState[n:] + boardState[:n] def pb(board, color): out = ""; if color == "red": out = "Red Players Move\n" if color == "black": out = "Black Players Move\n" for i in range(1,65): if board[i]...
client version/client.py
import socket import check import sys import getopt from Tkinter import * def rotate(boardState,n): return boardState[n:] + boardState[:n] def pb(board, color): out = ""; if color == "red": out = "Red Players Move\n" if color == "black": out = "Black Players Move\n" for i in range(1,65): if board[i]...
0.050658
0.150746
import os import sys from keras_tqdm import TQDMCallback, TQDMNotebookCallback from tqdm import tqdm, tqdm_notebook # Stupid Keras things is a smart way to always print. See: # https://github.com/keras-team/keras/issues/1406 stderr = sys.stderr sys.stderr = open(os.devnull, "w") from keras.layers import Input, Conv2D...
examples/ae.py
import os import sys from keras_tqdm import TQDMCallback, TQDMNotebookCallback from tqdm import tqdm, tqdm_notebook # Stupid Keras things is a smart way to always print. See: # https://github.com/keras-team/keras/issues/1406 stderr = sys.stderr sys.stderr = open(os.devnull, "w") from keras.layers import Input, Conv2D...
0.570092
0.325655
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=Tr...
services/forecasting_service/app/migrations/0002_auto_20201016_1811.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=Tr...
0.528047
0.155559
from neutronclient._i18n import _ from neutronclient.neutron import v2_0 as neutronV20 class ListHealthMonitor(neutronV20.ListCommand): """LBaaS v2 List healthmonitors that belong to a given tenant.""" resource = 'healthmonitor' shadow_resource = 'lbaas_healthmonitor' list_columns = ['id', 'name', '...
neutronclient/neutron/v2_0/lb/v2/healthmonitor.py
from neutronclient._i18n import _ from neutronclient.neutron import v2_0 as neutronV20 class ListHealthMonitor(neutronV20.ListCommand): """LBaaS v2 List healthmonitors that belong to a given tenant.""" resource = 'healthmonitor' shadow_resource = 'lbaas_healthmonitor' list_columns = ['id', 'name', '...
0.818084
0.199698
from __future__ import unicode_literals from django.contrib import admin from django.contrib.messages import info from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import force_text from mezzanine.conf.models import Setting from mezzanine.c...
mezzanine/conf/admin.py
from __future__ import unicode_literals from django.contrib import admin from django.contrib.messages import info from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import force_text from mezzanine.conf.models import Setting from mezzanine.c...
0.403802
0.042902
import argparse import time import textwrap import pytricia from _pybgpstream import BGPStream, BGPRecord, BGPElem import yaml def main(): parser = argparse.ArgumentParser() parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.description = textwrap.dedent('''\ a proof-of-concept u...
bgpwatch.py
import argparse import time import textwrap import pytricia from _pybgpstream import BGPStream, BGPRecord, BGPElem import yaml def main(): parser = argparse.ArgumentParser() parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.description = textwrap.dedent('''\ a proof-of-concept u...
0.338514
0.073497
from ..NCSource import * import pytz # Define constants class CosmoSource(NCSource): """ Handles the sources Sev created from the COSMO-REA6 dataset (cannot handle the orginal sources because they're whack) """ GWA50_CONTEXT_MEAN_SOURCE = None GWA100_CONTEXT_MEAN_SOURCE = None # a LARGE oov...
reskit/weather/CosmoSource/CosmoSource.py
from ..NCSource import * import pytz # Define constants class CosmoSource(NCSource): """ Handles the sources Sev created from the COSMO-REA6 dataset (cannot handle the orginal sources because they're whack) """ GWA50_CONTEXT_MEAN_SOURCE = None GWA100_CONTEXT_MEAN_SOURCE = None # a LARGE oov...
0.812459
0.491883
import pymysql import vk import networkx as nx import igraph import time import os import csv from datetime import datetime, timedelta from modules.get_student_graph import * from modules.get_student_group import * if __name__ == '__main__': start_time = time.time() session = vk.Session() api = vk.API(se...
scripts/get-groups/get_school_students_groups.py
import pymysql import vk import networkx as nx import igraph import time import os import csv from datetime import datetime, timedelta from modules.get_student_graph import * from modules.get_student_group import * if __name__ == '__main__': start_time = time.time() session = vk.Session() api = vk.API(se...
0.23926
0.130424
# ----- ---- --- -- - # Copyright 2019 Oneiro NA, Inc. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.apache.org/licens...
bin/sumAccounts.py
# ----- ---- --- -- - # Copyright 2019 Oneiro NA, Inc. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.apache.org/licens...
0.397938
0.287874
import math from seleniumbase import BaseCase class DownloadTests(BaseCase): def test_download_files(self): self.open("https://pypi.org/project/seleniumbase/#files") pkg_header = self.get_text("h1.package-header__name").strip() pkg_name = pkg_header.replace(" ", "-") whl...
examples/test_download_files.py
import math from seleniumbase import BaseCase class DownloadTests(BaseCase): def test_download_files(self): self.open("https://pypi.org/project/seleniumbase/#files") pkg_header = self.get_text("h1.package-header__name").strip() pkg_name = pkg_header.replace(" ", "-") whl...
0.405213
0.180576
from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.switch_to import SwitchTo, basestring from asyncselenium.common.async_alert import AsyncAlert from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException, NoSuchWindow...
asyncselenium/webdriver/remote/async_swith_to.py
from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.switch_to import SwitchTo, basestring from asyncselenium.common.async_alert import AsyncAlert from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException, NoSuchWindow...
0.79858
0.162413
__program__ = 'sortcss.py' __version__ = '0.1.2' __license__ = 'MIT' __description__ = 'CSS Property Sorter Script' __website__ = 'https://github.com/livibetter/css-prop-sorter' __author__ = '<NAME>' __email__ = '<EMAIL>' __credits__ = ['<NAME>', '<NAME>.', '<NAME>', 'xaicron'] import argparse import itertools import...
sortcss.py
__program__ = 'sortcss.py' __version__ = '0.1.2' __license__ = 'MIT' __description__ = 'CSS Property Sorter Script' __website__ = 'https://github.com/livibetter/css-prop-sorter' __author__ = '<NAME>' __email__ = '<EMAIL>' __credits__ = ['<NAME>', '<NAME>.', '<NAME>', 'xaicron'] import argparse import itertools import...
0.407333
0.037821
from game_objects import Chips, Hand def setup_players(deck): """ Create a list of players and their names """ while True: try: name = input("Enter the name of the player: ") except ValueError: print("Sorry, a player must be a string. Please try aga...
Project__4 (black_jack_simple)/game_methods.py
from game_objects import Chips, Hand def setup_players(deck): """ Create a list of players and their names """ while True: try: name = input("Enter the name of the player: ") except ValueError: print("Sorry, a player must be a string. Please try aga...
0.302906
0.277654
import pickle import re import constants class Data(object): def __init__(self, inputs=None, outputs=None): self.inputs = inputs # list of input sequences e.g. chars, words self.outputs = outputs # list of output sequences (label sequences) class RestorableData(Data): def __init__(self, i...
src/data_loaders/data_loader.py
import pickle import re import constants class Data(object): def __init__(self, inputs=None, outputs=None): self.inputs = inputs # list of input sequences e.g. chars, words self.outputs = outputs # list of output sequences (label sequences) class RestorableData(Data): def __init__(self, i...
0.441673
0.190724
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import os import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.examples.tutorials.mnist import input_data import mnist_data import cnn_model # user input from argparse i...
week2/mnist_data_augmentation/mnist_cnn_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import os import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.examples.tutorials.mnist import input_data import mnist_data import cnn_model # user input from argparse i...
0.823009
0.371279
from msrest.serialization import Model class ScheduleProperties(Model): """Definition of schedule parameters. Variables are only populated by the server, and will be ignored when sending a request. :param start_time: Gets or sets the start time of the schedule. :type start_time: datetime :i...
sdk/automation/azure-mgmt-automation/azure/mgmt/automation/models/schedule_properties_py3.py
from msrest.serialization import Model class ScheduleProperties(Model): """Definition of schedule parameters. Variables are only populated by the server, and will be ignored when sending a request. :param start_time: Gets or sets the start time of the schedule. :type start_time: datetime :i...
0.939429
0.663819
import datetime from django import http from django.utils import timezone from django.shortcuts import get_object_or_404, redirect, render from django.db.models import Count from django.contrib import messages from django.db import transaction from django.contrib.auth.decorators import login_required from airmozilla....
airmozilla/main/views/reports.py
import datetime from django import http from django.utils import timezone from django.shortcuts import get_object_or_404, redirect, render from django.db.models import Count from django.contrib import messages from django.db import transaction from django.contrib.auth.decorators import login_required from airmozilla....
0.492188
0.182062
import sqlite3 import atexit import datetime import traceback import threading import common log = common.get_logger() DATE_FORMAT = '%Y-%m-%d %H:%M:%S' def log_entry(fn): def new_fn(*args, **kw): try: log.debug('<== entering %s' % fn.__name__) log.debug((u' args: (' + u' %s,'*...
database.py
import sqlite3 import atexit import datetime import traceback import threading import common log = common.get_logger() DATE_FORMAT = '%Y-%m-%d %H:%M:%S' def log_entry(fn): def new_fn(*args, **kw): try: log.debug('<== entering %s' % fn.__name__) log.debug((u' args: (' + u' %s,'*...
0.167627
0.06804
from argparse import ArgumentParser as AP, RawDescriptionHelpFormatter import atexit import re import sys from . import __version__ as version ap = AP( epilog=""" Examples: # Add new room 'xyz': python3 -msogs --add-room xyz --name 'XYZ Room' # Add 2 admins to each of rooms 'xyz' and 'abc': pyt...
sogs/__main__.py
from argparse import ArgumentParser as AP, RawDescriptionHelpFormatter import atexit import re import sys from . import __version__ as version ap = AP( epilog=""" Examples: # Add new room 'xyz': python3 -msogs --add-room xyz --name 'XYZ Room' # Add 2 admins to each of rooms 'xyz' and 'abc': pyt...
0.434101
0.221603
import urllib2 debug = False class bitcoinapi(): def _debug(self, message): if debug == True: print message def _grabapi(self, apipaths): # This will attempt to grab the information using blockchain first, then blockexplorer. sources = ['http://blockchain.info', 'http://blockexplorer.com'] ...
bitcoin.py
import urllib2 debug = False class bitcoinapi(): def _debug(self, message): if debug == True: print message def _grabapi(self, apipaths): # This will attempt to grab the information using blockchain first, then blockexplorer. sources = ['http://blockchain.info', 'http://blockexplorer.com'] ...
0.29584
0.212273
import os import sublime import sublime_plugin import sys import traceback st2 = (sys.version_info[0] == 2) dist_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, dist_dir) ANN = '' VERSION = '' MARGO_EXE = '' fn = os.path.join(dist_dir, 'gosubl', 'about.py') execErr = '' try: with open(fn) as f: ...
GoSublime.py
import os import sublime import sublime_plugin import sys import traceback st2 = (sys.version_info[0] == 2) dist_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, dist_dir) ANN = '' VERSION = '' MARGO_EXE = '' fn = os.path.join(dist_dir, 'gosubl', 'about.py') execErr = '' try: with open(fn) as f: ...
0.221435
0.067855
import logging from madmigration.db_init.connection_engine import SourceDB from madmigration.db_init.connection_engine import DestinationDB from madmigration.utils.helpers import detect_driver, get_cast_type from sqlalchemy import Column, MetaData, Table from madmigration.config.conf import Config from madmigration.mys...
madmigration/main.py
import logging from madmigration.db_init.connection_engine import SourceDB from madmigration.db_init.connection_engine import DestinationDB from madmigration.utils.helpers import detect_driver, get_cast_type from sqlalchemy import Column, MetaData, Table from madmigration.config.conf import Config from madmigration.mys...
0.367838
0.10393
from pygitscrum.git import git_output, git_code from pygitscrum.scan import ( absolute_path_without_git, print_repo_if_first, update_dict, ) from pygitscrum.args import compute_args from pygitscrum.print import ( print_resume_map, print_debug, print_y, print_g, ) def git_prune(files): ...
pygitscrum/git_prune.py
from pygitscrum.git import git_output, git_code from pygitscrum.scan import ( absolute_path_without_git, print_repo_if_first, update_dict, ) from pygitscrum.args import compute_args from pygitscrum.print import ( print_resume_map, print_debug, print_y, print_g, ) def git_prune(files): ...
0.333395
0.146606
import smbus from LSM9DS0 import * from LSM9DS1 import * import time class BerryIMU: def __init__(self, is_virtual=False, gyr_addr=0, mag_addr=0, acc_addr=0): self.LSM9DS0 = 0 if is_virtual: self.bus = smbus.SMBus(0) else: self.bus = smbus.SMBus(1) self...
berryimu_publisher/IMU.py
import smbus from LSM9DS0 import * from LSM9DS1 import * import time class BerryIMU: def __init__(self, is_virtual=False, gyr_addr=0, mag_addr=0, acc_addr=0): self.LSM9DS0 = 0 if is_virtual: self.bus = smbus.SMBus(0) else: self.bus = smbus.SMBus(1) self...
0.393269
0.134208
import re from datetime import datetime from typing import Any, Dict, List, Optional, Type from uuid import UUID from pydantic import BaseModel, validator from .settings import settings class LogEventRegistration(BaseModel): reg_id: str address: str keyword: str reg_id: Optional[str] @validato...
app/app/models.py
import re from datetime import datetime from typing import Any, Dict, List, Optional, Type from uuid import UUID from pydantic import BaseModel, validator from .settings import settings class LogEventRegistration(BaseModel): reg_id: str address: str keyword: str reg_id: Optional[str] @validato...
0.854763
0.12424
import socket import threading import time from . import message as msg import re # remove globals DECODE = "utf-8" FLAG = "ignore" SOCK_RECV = 4096 SOCK_SLEEP = 0.1 class Queue(): def __init__(self): self.messages = [] def push(self, message): item = QueueItem(message) self.message...
2013/bot-core/ycore/network/network.py
import socket import threading import time from . import message as msg import re # remove globals DECODE = "utf-8" FLAG = "ignore" SOCK_RECV = 4096 SOCK_SLEEP = 0.1 class Queue(): def __init__(self): self.messages = [] def push(self, message): item = QueueItem(message) self.message...
0.2227
0.085289
import uuid from asynctest import TestCase as AsyncTestCase from asynctest import mock as async_mock from aries_cloudagent.issuer.base import BaseIssuer, IssuerError from aries_cloudagent.ledger.base import BaseLedger from aries_cloudagent.ledger.indy import IndyLedger from aries_cloudagent.wallet.base import BaseWal...
mydata_did/v1_0/tests/test_manager.py
import uuid from asynctest import TestCase as AsyncTestCase from asynctest import mock as async_mock from aries_cloudagent.issuer.base import BaseIssuer, IssuerError from aries_cloudagent.ledger.base import BaseLedger from aries_cloudagent.ledger.indy import IndyLedger from aries_cloudagent.wallet.base import BaseWal...
0.526099
0.328099
import collections import contextlib import functools import hashlib import itertools import logging import math import multiprocessing import numbers import os import pickle import queue import threading import time import traceback import numpy import pynng from .interface import Communicator import cicada import c...
cicada/communicator/nng.py
import collections import contextlib import functools import hashlib import itertools import logging import math import multiprocessing import numbers import os import pickle import queue import threading import time import traceback import numpy import pynng from .interface import Communicator import cicada import c...
0.704364
0.154026