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 |
|---|---|---|---|---|
"""Punctuator input generator."""
import string
import lingvo.compat as tf
from lingvo.core import base_input_generator
from lingvo.core import datasource
from lingvo.core import py_utils
from lingvo.core import tokenizers
class TextLines(datasource.TFDatasetSource):
"""Returns a tf.data.Dataset containing lines f... | lingvo/tasks/punctuator/input_generator.py | """Punctuator input generator."""
import string
import lingvo.compat as tf
from lingvo.core import base_input_generator
from lingvo.core import datasource
from lingvo.core import py_utils
from lingvo.core import tokenizers
class TextLines(datasource.TFDatasetSource):
"""Returns a tf.data.Dataset containing lines f... | 0.863089 | 0.436202 |
from __future__ import absolute_import
from argparse import Action, ArgumentTypeError, Namespace, _ActionsContainer
from pex import pex_warnings
from pex.argparse import HandleBoolAction
from pex.network_configuration import NetworkConfiguration
from pex.orderedset import OrderedSet
from pex.resolve.lockfile import ... | pex/resolve/resolver_options.py |
from __future__ import absolute_import
from argparse import Action, ArgumentTypeError, Namespace, _ActionsContainer
from pex import pex_warnings
from pex.argparse import HandleBoolAction
from pex.network_configuration import NetworkConfiguration
from pex.orderedset import OrderedSet
from pex.resolve.lockfile import ... | 0.818664 | 0.084078 |
import inspect
import os
import pkgutil
try:
from importlib import reload
except ImportError:
pass
class StepmaniaPlugin(object):
def __init__(self, server):
self.server = server
def on_packet(self, session, serv, packet):
pass
def on_nscping(self, session, serv, packet):
... | smserver/pluginmanager.py | import inspect
import os
import pkgutil
try:
from importlib import reload
except ImportError:
pass
class StepmaniaPlugin(object):
def __init__(self, server):
self.server = server
def on_packet(self, session, serv, packet):
pass
def on_nscping(self, session, serv, packet):
... | 0.326916 | 0.095307 |
import os # Used to validate filepaths
import sys # Used to fix arglengths of 0 for CLI
import logging # Used to log (obviously)
from copy import deepcopy
from typing import Generator # Used to typehint generator returns
from secrets import token_hex # Us... | otp_emoji.py | import os # Used to validate filepaths
import sys # Used to fix arglengths of 0 for CLI
import logging # Used to log (obviously)
from copy import deepcopy
from typing import Generator # Used to typehint generator returns
from secrets import token_hex # Us... | 0.32896 | 0.337395 |
from typing import List
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
import torch.nn.functional as F
from ..utils.generic_utils import to_cuda
from ..utils.constants import VERY_SMALL_NUMBER
def dropout(x, drop_prob, shared_axes=[], training=False):
... | src/core/layers/common.py | from typing import List
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
import torch.nn.functional as F
from ..utils.generic_utils import to_cuda
from ..utils.constants import VERY_SMALL_NUMBER
def dropout(x, drop_prob, shared_axes=[], training=False):
... | 0.927831 | 0.560854 |
import os
import re
import datetime
import configparser
import numpy as np
import astropy.io.fits as fits
from astropy.table import Table
from ...utils.misc import extract_date
from ..common import load_config
from .common import get_region_lst, get_std_setup, print_wrapper
from .reduce import reduce_rawdata
def mak... | gamse/pipelines/hds/__init__.py | import os
import re
import datetime
import configparser
import numpy as np
import astropy.io.fits as fits
from astropy.table import Table
from ...utils.misc import extract_date
from ..common import load_config
from .common import get_region_lst, get_std_setup, print_wrapper
from .reduce import reduce_rawdata
def mak... | 0.339937 | 0.137446 |
import discord
import asyncio
import aiohttp
import random
#custom libs
import config
import db
from event import Emitter
#Discord client PhiBot
class PhiBot(discord.Client):
def __init__(self, lock):
super().__init__()
self.running = True
self.lock = lock
self.eb_quotes = [
'It is certain',
'It is deci... | phi.py | import discord
import asyncio
import aiohttp
import random
#custom libs
import config
import db
from event import Emitter
#Discord client PhiBot
class PhiBot(discord.Client):
def __init__(self, lock):
super().__init__()
self.running = True
self.lock = lock
self.eb_quotes = [
'It is certain',
'It is deci... | 0.266644 | 0.103612 |
from zone_api import platform_encapsulator as pe
from zone_api.core.actions.turn_off_adjacent_zones import TurnOffAdjacentZones
from zone_api.core.event_info import EventInfo
from zone_api.core.zone import Zone
from zone_api.core.zone_event import ZoneEvent
from zone_api.core.neighbor import Neighbor, NeighborType
from... | tests/zone_api_test/core/actions/turn_off_adjacent_zones_test.py | from zone_api import platform_encapsulator as pe
from zone_api.core.actions.turn_off_adjacent_zones import TurnOffAdjacentZones
from zone_api.core.event_info import EventInfo
from zone_api.core.zone import Zone
from zone_api.core.zone_event import ZoneEvent
from zone_api.core.neighbor import Neighbor, NeighborType
from... | 0.629319 | 0.29044 |
import json
import os
import unittest
import pytest
from mock import patch
import requests
import requests_mock
from gitdl import gitdl
class TestGitdl(unittest.TestCase):
def test_params_invalid_api_token(self):
old_env = os.environ
os.environ = {}
with pytest.raises(Exception) as ex... | tests/test_gitdl.py | import json
import os
import unittest
import pytest
from mock import patch
import requests
import requests_mock
from gitdl import gitdl
class TestGitdl(unittest.TestCase):
def test_params_invalid_api_token(self):
old_env = os.environ
os.environ = {}
with pytest.raises(Exception) as ex... | 0.390708 | 0.225278 |
from CNC import CNC
from rgv import RGV
def sea_info(cnc_list):
"""找出当前发出信号的所有CNC,并记录故障机器"""
cnc_loc_list = []
error_cnc_list = []
for cnc_call in cnc_list:
cnc_stat = cnc_call.call_rgv()
if cnc_stat[1] in ['off', 'empty']:
cnc_loc_list.append(cnc_stat)
elif cnc_sta... | CUMCM_2018/RGV_CNC/simulate.py | from CNC import CNC
from rgv import RGV
def sea_info(cnc_list):
"""找出当前发出信号的所有CNC,并记录故障机器"""
cnc_loc_list = []
error_cnc_list = []
for cnc_call in cnc_list:
cnc_stat = cnc_call.call_rgv()
if cnc_stat[1] in ['off', 'empty']:
cnc_loc_list.append(cnc_stat)
elif cnc_sta... | 0.144511 | 0.141786 |
import pytest
from mocks import MockDAO
# RAMSTK Package Imports
from ramstk.models import RAMSTKEnvironmentRecord
@pytest.fixture
def mock_program_dao(monkeypatch):
_environment_1 = RAMSTKEnvironmentRecord()
_environment_1.revision_id = 1
_environment_1.mission_id = 1
_environment_1.phase_id = 1
... | tests/models/programdb/environment/conftest.py | import pytest
from mocks import MockDAO
# RAMSTK Package Imports
from ramstk.models import RAMSTKEnvironmentRecord
@pytest.fixture
def mock_program_dao(monkeypatch):
_environment_1 = RAMSTKEnvironmentRecord()
_environment_1.revision_id = 1
_environment_1.mission_id = 1
_environment_1.phase_id = 1
... | 0.59408 | 0.510985 |
import md5
import os
import random
import time
from tashi.aws.wsdl.AmazonEC2_services_server import *
from tashi.rpycservices.rpyctypes import *
from tashi.aws.util import *
import tashi.aws.util
import tashi
def getImages():
IMGDIR="/mnt/merkabah/tashi/images/"
imgList = os.listdir(IMGDIR)
images = {}
for img in... | src/tashi/aws/impl/instances.py |
import md5
import os
import random
import time
from tashi.aws.wsdl.AmazonEC2_services_server import *
from tashi.rpycservices.rpyctypes import *
from tashi.aws.util import *
import tashi.aws.util
import tashi
def getImages():
IMGDIR="/mnt/merkabah/tashi/images/"
imgList = os.listdir(IMGDIR)
images = {}
for img in... | 0.140838 | 0.071106 |
from __future__ import absolute_import, division, print_function
import numpy as np
import time
import argparse
import sys
import os
import json
from make_data import sample_IHDP
from utils.metrics import compute_PEHE, mean_confidence_interval
from models.causal_models import CMGP
import initpath_alg
initpath_alg.in... | alg/causal_multitask_gaussian_processes_ite/test_models.py |
from __future__ import absolute_import, division, print_function
import numpy as np
import time
import argparse
import sys
import os
import json
from make_data import sample_IHDP
from utils.metrics import compute_PEHE, mean_confidence_interval
from models.causal_models import CMGP
import initpath_alg
initpath_alg.in... | 0.419291 | 0.231571 |
from keras.layers import Input, Conv2D, Conv2DTranspose, Concatenate, MaxPooling2D, UpSampling2D, Add
from keras.applications.vgg19 import VGG19
from keras.models import Model
from DWT import DWT_Pooling, IWT_UpSampling
def down_block(input_layer, filters, kernel_size=(3,3), activation="relu"):
output = Co... | main/Network_2.py | from keras.layers import Input, Conv2D, Conv2DTranspose, Concatenate, MaxPooling2D, UpSampling2D, Add
from keras.applications.vgg19 import VGG19
from keras.models import Model
from DWT import DWT_Pooling, IWT_UpSampling
def down_block(input_layer, filters, kernel_size=(3,3), activation="relu"):
output = Co... | 0.924511 | 0.598987 |
from create import random_image
import glob
import random
import numpy as np
from PIL import Image
from keras.models import Sequential, load_model
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
background = Image.open('background.png')
LETTERS = 'ab... | train.py | from create import random_image
import glob
import random
import numpy as np
from PIL import Image
from keras.models import Sequential, load_model
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
background = Image.open('background.png')
LETTERS = 'ab... | 0.668447 | 0.455804 |
import py_cui
class StatusBar:
"""Very simple class representing a status bar
Attributes
----------
text : str
status bar text
color : py_cui.COLOR
color to display the statusbar
root : py_cui.PyCUI
Main PyCUI object reference
is_title_bar : bool
Is the Stat... | py_cui/statusbar.py | import py_cui
class StatusBar:
"""Very simple class representing a status bar
Attributes
----------
text : str
status bar text
color : py_cui.COLOR
color to display the statusbar
root : py_cui.PyCUI
Main PyCUI object reference
is_title_bar : bool
Is the Stat... | 0.811825 | 0.361616 |
<<<<<<< HEAD
#### Healthy Neighborhoods Project: Using Ecological Data to Improve Community Health
### Cedric subproject: Developing better ways to measure equity in health using the Gini coefficient
## Florida Charts Census Tract Mortality Data: Pyhton Computing Language Code Script by DrewC!
### Step 1: Import Libr... | _archive/_archive/neville_acs_flcharts_join.py | <<<<<<< HEAD
#### Healthy Neighborhoods Project: Using Ecological Data to Improve Community Health
### Cedric subproject: Developing better ways to measure equity in health using the Gini coefficient
## Florida Charts Census Tract Mortality Data: Pyhton Computing Language Code Script by DrewC!
### Step 1: Import Libr... | 0.281406 | 0.557845 |
class Element():
"""
Represents <name>body</name>.
(Where `body' is either a string or a list of sub-elements.)
"""
@property
def tag(self): return self.name
def __init__(self, name, body):
"""Initialize with the tag's name and the body (i.e. content)."""
if body == []:
... | irods/message/quasixml.py |
class Element():
"""
Represents <name>body</name>.
(Where `body' is either a string or a list of sub-elements.)
"""
@property
def tag(self): return self.name
def __init__(self, name, body):
"""Initialize with the tag's name and the body (i.e. content)."""
if body == []:
... | 0.874265 | 0.202364 |
# Stdlib
from unittest.mock import patch
# External packages
import nose
import nose.tools as ntools
from dnslib import DNSLabel
# SCION
from infrastructure.dns_server.main import SCIONDnsServer
from lib.defines import (
BEACON_SERVICE,
CERTIFICATE_SERVICE,
DNS_SERVICE,
PATH_SERVICE,
SCION_DNS_POR... | test/infrastructure/dns_server/main_test.py | # Stdlib
from unittest.mock import patch
# External packages
import nose
import nose.tools as ntools
from dnslib import DNSLabel
# SCION
from infrastructure.dns_server.main import SCIONDnsServer
from lib.defines import (
BEACON_SERVICE,
CERTIFICATE_SERVICE,
DNS_SERVICE,
PATH_SERVICE,
SCION_DNS_POR... | 0.449151 | 0.160825 |
import unittest
from faker import Faker
from src.logica.coleccion import Coleccion
from src.modelo.album import Album
from src.modelo.cancion import Cancion
from src.modelo.declarative_base import Session
from src.modelo.interprete import Interprete
class CancionTestCase(unittest.TestCase):
def setUp(self):
... | tests/test_cancion.py | import unittest
from faker import Faker
from src.logica.coleccion import Coleccion
from src.modelo.album import Album
from src.modelo.cancion import Cancion
from src.modelo.declarative_base import Session
from src.modelo.interprete import Interprete
class CancionTestCase(unittest.TestCase):
def setUp(self):
... | 0.325628 | 0.276239 |
# Stdlib
import json
try:
import cStringIO as StringIO
except ImportError:
import StringIO as StringIO
# Local
import doekbase.workspace.client
from . import thrift_service, ttypes
from doekbase.data_api.util import get_logger, log_start, log_end
from doekbase.data_api.rpc_util import thrift_validate
_log = g... | lib/doekbase/data_api/baseobj/impl.py |
# Stdlib
import json
try:
import cStringIO as StringIO
except ImportError:
import StringIO as StringIO
# Local
import doekbase.workspace.client
from . import thrift_service, ttypes
from doekbase.data_api.util import get_logger, log_start, log_end
from doekbase.data_api.rpc_util import thrift_validate
_log = g... | 0.246624 | 0.16975 |
from typing import Counter
import scrapy
from tutorial.items import QuoteItem
from scrapy.http.request import Request
class QuotesSpider(scrapy.Spider):
# 爬虫名称, 唯一的
name = 'quotes'
# 请求url非该域名则过滤
# allowed_domains = ['quotes.toscrape.com']
# is_open_count = True
# count = 0
# MAX = 5
... | quotes.toscrape.com/tutorial/tutorial/spiders/quotes.py | from typing import Counter
import scrapy
from tutorial.items import QuoteItem
from scrapy.http.request import Request
class QuotesSpider(scrapy.Spider):
# 爬虫名称, 唯一的
name = 'quotes'
# 请求url非该域名则过滤
# allowed_domains = ['quotes.toscrape.com']
# is_open_count = True
# count = 0
# MAX = 5
... | 0.270866 | 0.119948 |
import re
import itertools
from django import forms
from django.utils.text import slugify
from freenodejobs.jobs.enums import StateEnum
from ..models import Job
from ..jobs_tags.models import Tag
class AddEditForm(forms.ModelForm):
class Meta:
model = Job
fields = (
'title',
... | freenodejobs/jobs/jobs_add_edit/forms.py | import re
import itertools
from django import forms
from django.utils.text import slugify
from freenodejobs.jobs.enums import StateEnum
from ..models import Job
from ..jobs_tags.models import Tag
class AddEditForm(forms.ModelForm):
class Meta:
model = Job
fields = (
'title',
... | 0.485356 | 0.104614 |
import requests
import configparser
global token
global instance_
global server_
"""
Obtengo el modulo que fue invocado
"""
module = GetParams("module")
if module == "loginNOC":
ruta_ = GetParams("ruta_")
config = configparser.ConfigParser()
config.read(ruta_)
email_ = config.get('USER', 'user')... | __init__.py | import requests
import configparser
global token
global instance_
global server_
"""
Obtengo el modulo que fue invocado
"""
module = GetParams("module")
if module == "loginNOC":
ruta_ = GetParams("ruta_")
config = configparser.ConfigParser()
config.read(ruta_)
email_ = config.get('USER', 'user')... | 0.105458 | 0.072178 |
import os
import numpy as np
import tensorflow as tf
import tensorflow.contrib as tc
from utils import tf_utils
from module import Model
from actor_critic import ActorCritic
from replaybuffer import ReplayBuffer
class DDPG(Model):
""" Interface """
def __init__(self, name, args, sess=None, reuse=False, log_ten... | ddpg-bipedal/tensorflow-imp/ddpg_tf.py | import os
import numpy as np
import tensorflow as tf
import tensorflow.contrib as tc
from utils import tf_utils
from module import Model
from actor_critic import ActorCritic
from replaybuffer import ReplayBuffer
class DDPG(Model):
""" Interface """
def __init__(self, name, args, sess=None, reuse=False, log_ten... | 0.841011 | 0.12326 |
import os
import json
import tensorflow as tf
import numpy as np
from pycocotools.cocoeval import COCOeval
from detection.datasets import coco, data_generator
from detection.models.detectors import faster_rcnn
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
for gpu in tf.config... | ObjectDetection/Faster R-CNN/evaluate.py | import os
import json
import tensorflow as tf
import numpy as np
from pycocotools.cocoeval import COCOeval
from detection.datasets import coco, data_generator
from detection.models.detectors import faster_rcnn
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
for gpu in tf.config... | 0.340814 | 0.251605 |
from Tkinter import *
class Dialog(Toplevel):
"""Class to open dialogs.
This class is intended as a base class for custom dialogs
"""
def __init__(self, parent, title=None):
"""Initialize a dialog.
Arguments:
parent -- a parent window (the application... | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/lib-tk/tkSimpleDialog.py | from Tkinter import *
class Dialog(Toplevel):
"""Class to open dialogs.
This class is intended as a base class for custom dialogs
"""
def __init__(self, parent, title=None):
"""Initialize a dialog.
Arguments:
parent -- a parent window (the application... | 0.709925 | 0.122078 |
import csv
import numpy as np
import cv2
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Conv2D, Lambda, Dropout
from keras.layers.convolutional import Cropping2D
from keras.opt... | Workshops/09/Self_Driving_Car_Excursion/generator.py | import csv
import numpy as np
import cv2
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Conv2D, Lambda, Dropout
from keras.layers.convolutional import Cropping2D
from keras.opt... | 0.752195 | 0.378115 |
import os
import yaml
import logging
import collections
from ConfigParser import NoSectionError, NoOptionError, DuplicateSectionError
from ratatosk import backend
from ratatosk.utils import update, config_to_dict
from ratatosk.log import get_logger
logger = get_logger()
try:
from collections import OrderedDict as... | ratatosk/config.py | import os
import yaml
import logging
import collections
from ConfigParser import NoSectionError, NoOptionError, DuplicateSectionError
from ratatosk import backend
from ratatosk.utils import update, config_to_dict
from ratatosk.log import get_logger
logger = get_logger()
try:
from collections import OrderedDict as... | 0.539226 | 0.072834 |
from gevent.monkey import patch_all; patch_all()
import pytest
from utils import sleep_try
@pytest.fixture(scope='module')
def pool(app):
return app.pools['test-pool']
# ============================================================================
@pytest.mark.usefixtures('client_class', 'docker_client')
class Te... | test/test_01_basic_api.py | from gevent.monkey import patch_all; patch_all()
import pytest
from utils import sleep_try
@pytest.fixture(scope='module')
def pool(app):
return app.pools['test-pool']
# ============================================================================
@pytest.mark.usefixtures('client_class', 'docker_client')
class Te... | 0.441673 | 0.272666 |
from unittest.mock import MagicMock
from graphql_relay import to_global_id
from creator.studies.models import Study
from creator.projects.models import Project
from creator.events.models import Event
from creator.studies.factories import StudyFactory
from creator.organizations.factories import OrganizationFactory
from ... | tests/events/test_studies.py | from unittest.mock import MagicMock
from graphql_relay import to_global_id
from creator.studies.models import Study
from creator.projects.models import Project
from creator.events.models import Event
from creator.studies.factories import StudyFactory
from creator.organizations.factories import OrganizationFactory
from ... | 0.722331 | 0.395718 |
from knack.help_files import helps
helps['ad ds'] = """
type: group
short-summary: Manage domain service with ad
"""
helps['ad ds list'] = """
type: command
short-summary: "The List Domain Services in Resource Group operation lists all the domain services available under \
the given resource group. ... | src/ad/azext_ad/generated/_help.py |
from knack.help_files import helps
helps['ad ds'] = """
type: group
short-summary: Manage domain service with ad
"""
helps['ad ds list'] = """
type: command
short-summary: "The List Domain Services in Resource Group operation lists all the domain services available under \
the given resource group. ... | 0.752377 | 0.233859 |
import numpy as np
import os
os.chdir('C:/Users/DELL/Desktop/Quant_macro/Pset4')
import rep_VFI_shock_labor as ra
import matplotlib.pyplot as plt
###parameters
para = {}
para['theta'] = 0.679
para['beta'] = 0.988
para['delta'] = 0.013
para['kappa'] = 5.24
para['nu'] = 2
para['h'] = 1
kss = (((1-para['the... | Pset4_hand_in/Pset_shock_labor_VFI.py | import numpy as np
import os
os.chdir('C:/Users/DELL/Desktop/Quant_macro/Pset4')
import rep_VFI_shock_labor as ra
import matplotlib.pyplot as plt
###parameters
para = {}
para['theta'] = 0.679
para['beta'] = 0.988
para['delta'] = 0.013
para['kappa'] = 5.24
para['nu'] = 2
para['h'] = 1
kss = (((1-para['the... | 0.31059 | 0.189802 |
from rest_framework import status
from rest_framework.test import APITestCase
from django.test import override_settings
from django.urls import reverse
from oems.settings import PAGINATION_SIZE, TEST_MEDIA_ROOT
from api import models
from api.tests import utils
@override_settings(MEDIA_ROOT=TEST_MEDIA_ROOT)
class Nam... | api/tests/name_list.py | from rest_framework import status
from rest_framework.test import APITestCase
from django.test import override_settings
from django.urls import reverse
from oems.settings import PAGINATION_SIZE, TEST_MEDIA_ROOT
from api import models
from api.tests import utils
@override_settings(MEDIA_ROOT=TEST_MEDIA_ROOT)
class Nam... | 0.438064 | 0.217608 |
u"""
combine_shapfiles.py
<NAME> (08/2020)
Combine all individual shapefiles for all tracks into 1 file
"""
import os
import sys
import getopt
import pandas as pd
import geopandas as gpd
from rasterio.crs import CRS
#-- main function
def main():
#-- Read the system arguments listed after the program
long_options=['... | combine_shapefiles_allTracks.py | u"""
combine_shapfiles.py
<NAME> (08/2020)
Combine all individual shapefiles for all tracks into 1 file
"""
import os
import sys
import getopt
import pandas as pd
import geopandas as gpd
from rasterio.crs import CRS
#-- main function
def main():
#-- Read the system arguments listed after the program
long_options=['... | 0.054563 | 0.194865 |
import argparse
import random
import numpy as np
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torch.utils.data import DataLoader
from models.fewshot_anom import FewShotSeg
from dataloading.datas... | main_inference.py |
import argparse
import random
import numpy as np
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torch.utils.data import DataLoader
from models.fewshot_anom import FewShotSeg
from dataloading.datas... | 0.78609 | 0.225587 |
widget = WidgetDefault()
widget.halign = "Center"
commonDefaults["ListWidget"] = widget
def generateListWidget(file, screen, list, parentName):
name = list.getName()
file.write(" %s = leListWidget_New();" % (name))
generateBaseWidget(file, screen, list)
mode = list.getSelectionMode().toString()
... | middleware/legato/library/plugins_java/scripts/generator/widget_list.py | widget = WidgetDefault()
widget.halign = "Center"
commonDefaults["ListWidget"] = widget
def generateListWidget(file, screen, list, parentName):
name = list.getName()
file.write(" %s = leListWidget_New();" % (name))
generateBaseWidget(file, screen, list)
mode = list.getSelectionMode().toString()
... | 0.202601 | 0.119305 |
import os
from tensorflow.python.platform import gfile
import numpy as np
from csp.utils import wav_utils
import tensorflow as tf
from tensorflow.python.ops import io_ops
from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio
import numpy as np
from struct import unpack, pack
from ..utils impo... | src/preproc/vivos/vivos_feature.py | import os
from tensorflow.python.platform import gfile
import numpy as np
from csp.utils import wav_utils
import tensorflow as tf
from tensorflow.python.ops import io_ops
from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio
import numpy as np
from struct import unpack, pack
from ..utils impo... | 0.486819 | 0.159283 |
import datetime
import dateutil.tz
import logging
import random
import time
from xmlrpclib import ServerProxy, Transport, Error, Fault, ProtocolError
dt = datetime.datetime.now()
dt_now = dt
delta = datetime.timedelta(minutes=20)
d = (dt + delta)
dt_20min = d
class SpecialTransport(Transport):
# Override
def... | src/ocs/send_xml_to_sdp/offer_to_sdp.py | import datetime
import dateutil.tz
import logging
import random
import time
from xmlrpclib import ServerProxy, Transport, Error, Fault, ProtocolError
dt = datetime.datetime.now()
dt_now = dt
delta = datetime.timedelta(minutes=20)
d = (dt + delta)
dt_20min = d
class SpecialTransport(Transport):
# Override
def... | 0.049854 | 0.069573 |
__import__("pkg_resources").declare_namespace(__name__)
import os
import sys
import time
import psutil
import logging
logger = logging.getLogger(__name__)
EXTENSION = '.exe' if os.name == 'nt' else ''
def is_in_bindir(pathname, cwd, bin_abspaths):
if os.path.isabs(pathname) and os.path.dirname(pathname) in bin_... | src/infi/recipe/close_application/__init__.py | __import__("pkg_resources").declare_namespace(__name__)
import os
import sys
import time
import psutil
import logging
logger = logging.getLogger(__name__)
EXTENSION = '.exe' if os.name == 'nt' else ''
def is_in_bindir(pathname, cwd, bin_abspaths):
if os.path.isabs(pathname) and os.path.dirname(pathname) in bin_... | 0.169337 | 0.057652 |
from mocasin.gui.utils import platformOperations, listOperations
class mappingInformation:
"""Data object that holds the necessary information to draw a mapping.
:ivar Mapping __mMappingObject: The actual mocasin Mapping object.
:ivar {str, list[str]} __mappingDescription: A dictionary with core names as... | mocasin/gui/dataTemplates.py |
from mocasin.gui.utils import platformOperations, listOperations
class mappingInformation:
"""Data object that holds the necessary information to draw a mapping.
:ivar Mapping __mMappingObject: The actual mocasin Mapping object.
:ivar {str, list[str]} __mappingDescription: A dictionary with core names as... | 0.913452 | 0.565299 |
import asyncio
import os
from serial import Serial
from serial.tools import list_ports
from .pybricks import PybricksHub
from ..tools import chunk
FILE_PACKET_SIZE = 1024
FILE_TRANSFER_SCRIPT = f"""
import sys
import micropython
import utime
PACKETSIZE = {FILE_PACKET_SIZE}
def receive_file(filename, filesize):
... | pybricksdev/connections/lego.py |
import asyncio
import os
from serial import Serial
from serial.tools import list_ports
from .pybricks import PybricksHub
from ..tools import chunk
FILE_PACKET_SIZE = 1024
FILE_TRANSFER_SCRIPT = f"""
import sys
import micropython
import utime
PACKETSIZE = {FILE_PACKET_SIZE}
def receive_file(filename, filesize):
... | 0.566498 | 0.188492 |
import requests
from bs4 import BeautifulSoup
import os
url="https://www.airbnb.com.tw/s/Tainan-City/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_dates%5B%5D=august&flexible_trip_dates%5B%5D=september&flexible_trip_lengths%5B%5D=weekend_trip&date_picker_type=calendar&query=Tainan%20City&pla... | lesson2_web_crawler/08_13.py | import requests
from bs4 import BeautifulSoup
import os
url="https://www.airbnb.com.tw/s/Tainan-City/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_dates%5B%5D=august&flexible_trip_dates%5B%5D=september&flexible_trip_lengths%5B%5D=weekend_trip&date_picker_type=calendar&query=Tainan%20City&pla... | 0.082771 | 0.09236 |
import os
import sys
import time
import numpy as np
from datetime import timedelta
from tensorboardX import SummaryWriter
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
class Logger(object):
"""
generate logger files(train.log and tensorboard log file) in experiment root
"""
... | reid/utils/trainer.py | import os
import sys
import time
import numpy as np
from datetime import timedelta
from tensorboardX import SummaryWriter
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
class Logger(object):
"""
generate logger files(train.log and tensorboard log file) in experiment root
"""
... | 0.574395 | 0.239227 |
import apps.basics.op_drf.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... | backend/apps/projects/point/migrations/0001_initial.py |
import apps.basics.op_drf.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... | 0.402979 | 0.212538 |
import pytest
from common.switch import SaiObjType
from ptf.testutils import simple_tcp_packet, send_packet, verify_packets, verify_no_packet_any
def test_l2_access_to_access_vlan(sai, dataplane):
vlan_id = "10"
macs = ['00:11:11:11:11:11', '00:22:22:22:22:22']
port_oids = []
vlan_oid = sai.get_vid(S... | tests/test_l2_basic.py | import pytest
from common.switch import SaiObjType
from ptf.testutils import simple_tcp_packet, send_packet, verify_packets, verify_no_packet_any
def test_l2_access_to_access_vlan(sai, dataplane):
vlan_id = "10"
macs = ['00:11:11:11:11:11', '00:22:22:22:22:22']
port_oids = []
vlan_oid = sai.get_vid(S... | 0.118347 | 0.268003 |
from enum import Enum
import os
try:
import pathlib
except ImportError as e:
try:
import pathlib2 as pathlib
except ImportError:
raise e
from . import constants as exob
VALID_CHARACTERS = ("abcdefghijklmnopqrstuvwxyz1234567890_-.")
class NamingRule(Enum):
SIMPLE = 1
STRICT = 2
... | exdir/core/validation.py | from enum import Enum
import os
try:
import pathlib
except ImportError as e:
try:
import pathlib2 as pathlib
except ImportError:
raise e
from . import constants as exob
VALID_CHARACTERS = ("abcdefghijklmnopqrstuvwxyz1234567890_-.")
class NamingRule(Enum):
SIMPLE = 1
STRICT = 2
... | 0.449634 | 0.219547 |
import copy
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import widgets
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.utils import model_meta
from ..core.validators import validate_password
clas... | orchestra/api/serializers.py | import copy
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import widgets
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.utils import model_meta
from ..core.validators import validate_password
clas... | 0.441432 | 0.141875 |
from unittest import TestCase
from microfreshener.core.model.microtosca import MicroToscaModel
from microfreshener.core.model.nodes import Service, Datastore, MessageBroker, MessageRouter
from microfreshener.core.errors import MicroToscaModelError, GroupNotFoundError, GroupNotFoundError
from microfreshener.core.model ... | tests/test_model/test_group.py | from unittest import TestCase
from microfreshener.core.model.microtosca import MicroToscaModel
from microfreshener.core.model.nodes import Service, Datastore, MessageBroker, MessageRouter
from microfreshener.core.errors import MicroToscaModelError, GroupNotFoundError, GroupNotFoundError
from microfreshener.core.model ... | 0.727201 | 0.461623 |
from typing import List, Tuple, Union
import matplotlib as mpl
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
import matplotlib.pyplot as plt
from numpy import ndarray
from .extend import ExtendDict
from .color import PLOT_COLORS
# DEFAULT PARAMETERS
class PlotProperty(object):
FIGURE... | src/plot.py |
from typing import List, Tuple, Union
import matplotlib as mpl
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
import matplotlib.pyplot as plt
from numpy import ndarray
from .extend import ExtendDict
from .color import PLOT_COLORS
# DEFAULT PARAMETERS
class PlotProperty(object):
FIGURE... | 0.925306 | 0.430327 |
from zope.interface import implements
from twisted.python import log
from twisted.web.client import HTTP11ClientProtocol
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import ClientFactory, Protocol
from devicehive import ApiInfoRequest
from devicehive.i... | Software/src/liv/iotConnectors/devicehive/devicehive/auto.py |
from zope.interface import implements
from twisted.python import log
from twisted.web.client import HTTP11ClientProtocol
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import ClientFactory, Protocol
from devicehive import ApiInfoRequest
from devicehive.i... | 0.509276 | 0.071397 |
import RPi.GPIO as GPIO
import argparse
import ast
import logging as l
from marcs.CubeSolver.logger import log, set_log_level
from pathlib import Path
from time import sleep
class Winding:
def __init__(self, pin1: int, pin2: int):
self.pin1 = pin1
self.pin2 = pin2
self.energized = 0
... | stepper.py | import RPi.GPIO as GPIO
import argparse
import ast
import logging as l
from marcs.CubeSolver.logger import log, set_log_level
from pathlib import Path
from time import sleep
class Winding:
def __init__(self, pin1: int, pin2: int):
self.pin1 = pin1
self.pin2 = pin2
self.energized = 0
... | 0.515864 | 0.344085 |
from typing import Iterable, Dict, Tuple, List, Set, Optional, Any
import datetime
import hashlib
import io
import re
import boto3
from botocore.config import Config # type: ignore
from .config import S3EnvConfig
from ..data_store_util import wide
from ...api.data_store import ConfigEntity
from ...api.data_store.ab... | old-stuff-for-reference/nightjar-base/nightjar-src/python-src/nightjar/backend/impl/data_store_s3/backend.py |
from typing import Iterable, Dict, Tuple, List, Set, Optional, Any
import datetime
import hashlib
import io
import re
import boto3
from botocore.config import Config # type: ignore
from .config import S3EnvConfig
from ..data_store_util import wide
from ...api.data_store import ConfigEntity
from ...api.data_store.ab... | 0.846117 | 0.150247 |
import cv2
import numpy as np
from openvino.inference_engine import IECore,IENetwork
class FacialLandmarksDetectionModel:
'''
Class for the Face Detection Model.
'''
def __init__(self, model_name, device='CPU', extensions=None):
self.model_name = model_name
self.device = devic... | src/facial_landmarks_detection.py | import cv2
import numpy as np
from openvino.inference_engine import IECore,IENetwork
class FacialLandmarksDetectionModel:
'''
Class for the Face Detection Model.
'''
def __init__(self, model_name, device='CPU', extensions=None):
self.model_name = model_name
self.device = devic... | 0.36523 | 0.158565 |
import logging
from karmabot.db import db_session
from karmabot.db.karma_transaction import KarmaTransaction
from karmabot.db.karma_user import KarmaUser
from karmabot.settings import KARMABOT_ID, MAX_POINTS, SLACK_CLIENT, SLACK_ID_FORMAT
from karmabot.slack import get_available_username, get_channel_name, post_msg
... | src/karmabot/karma.py | import logging
from karmabot.db import db_session
from karmabot.db.karma_transaction import KarmaTransaction
from karmabot.db.karma_user import KarmaUser
from karmabot.settings import KARMABOT_ID, MAX_POINTS, SLACK_CLIENT, SLACK_ID_FORMAT
from karmabot.slack import get_available_username, get_channel_name, post_msg
... | 0.391871 | 0.086131 |
from urllib.request import unquote
from neomodel import db
from neomodel.exception import DoesNotExist, RequiredProperty, UniqueProperty
import grest.messages as msg
from grest.exceptions import HTTPException
from grest.utils import serialize
from grest.validation import validate_models
from grest.global_config impo... | grest/verbs/delete.py |
from urllib.request import unquote
from neomodel import db
from neomodel.exception import DoesNotExist, RequiredProperty, UniqueProperty
import grest.messages as msg
from grest.exceptions import HTTPException
from grest.utils import serialize
from grest.validation import validate_models
from grest.global_config impo... | 0.426202 | 0.06165 |
import requests # You will need to install requests through pip or another mechanism
import getpass # This allows us to collect the password without showing it in the terminal
# Ask for credentials
jss_username = raw_input("Please enter your JSS username: ")
jss_password = getpass.getpass("Please enter your JSS passw... | JSS_device_search.py | import requests # You will need to install requests through pip or another mechanism
import getpass # This allows us to collect the password without showing it in the terminal
# Ask for credentials
jss_username = raw_input("Please enter your JSS username: ")
jss_password = getpass.getpass("Please enter your JSS passw... | 0.242564 | 0.118003 |
import librosa
import soundfile
import os, glob, pickle
import numpy as np
import subprocess
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
from tkinter import messagebox
from PIL import Image, ImageTk
def prepareFile(rut... | src/funcionalidad.py | import librosa
import soundfile
import os, glob, pickle
import numpy as np
import subprocess
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
from tkinter import messagebox
from PIL import Image, ImageTk
def prepareFile(rut... | 0.267791 | 0.178347 |
import requests
import json
import re
# 好看视频解析入口
class Bili(object):
def __init__(self, bv):
self.bv = bv
def get_video(self):
url = self.bv
if len(url) >= 23:
base_url = url
else:
base_url = "https://m.bilibili.com/video/" + str(self.bv)
header... | app/src/main/python/haokan.py | import requests
import json
import re
# 好看视频解析入口
class Bili(object):
def __init__(self, bv):
self.bv = bv
def get_video(self):
url = self.bv
if len(url) >= 23:
base_url = url
else:
base_url = "https://m.bilibili.com/video/" + str(self.bv)
header... | 0.108626 | 0.098469 |
import numpy as np
from ivac.utils import get_nfeatures
# equilibrium IVAC
def c0_all(trajs):
nfeatures = get_nfeatures(trajs)
numer = np.zeros((nfeatures, nfeatures))
denom = 0.0
for traj in trajs:
numer += traj.T @ traj
denom += len(traj)
return numer / denom
def ct_all(traj... | tests/ref_corr.py |
import numpy as np
from ivac.utils import get_nfeatures
# equilibrium IVAC
def c0_all(trajs):
nfeatures = get_nfeatures(trajs)
numer = np.zeros((nfeatures, nfeatures))
denom = 0.0
for traj in trajs:
numer += traj.T @ traj
denom += len(traj)
return numer / denom
def ct_all(traj... | 0.567457 | 0.478894 |
from collections import defaultdict
from itertools import permutations
import numpy as np
import sys
def read_scan(input):
lines = input.splitlines()
assert(lines[0].startswith("---"))
scan = []
for line in lines[1:]:
scan.append(tuple(map(int, line.split(","))))
return scan
def read_scan... | day19_scanner.py | from collections import defaultdict
from itertools import permutations
import numpy as np
import sys
def read_scan(input):
lines = input.splitlines()
assert(lines[0].startswith("---"))
scan = []
for line in lines[1:]:
scan.append(tuple(map(int, line.split(","))))
return scan
def read_scan... | 0.386995 | 0.444806 |
import numpy as np
from fitter import *
from scipy.constants import hbar
cons_w = 2*3.14*6.002e9
cons_ke = 2*3.14*0.017e6
cons_k = 2*3.14*1.4e6
cons_delta = 0
def Plin(p):
return 10.**(p/10.-3.)
def photons(power):
return Plin(power)/(hbar*cons_w)*(cons_ke/((cons_k/2)**2+cons_delta**2))
path = ... | scripts/Qubit/Analysis/Fit/quick_S11_fit.py | import numpy as np
from fitter import *
from scipy.constants import hbar
cons_w = 2*3.14*6.002e9
cons_ke = 2*3.14*0.017e6
cons_k = 2*3.14*1.4e6
cons_delta = 0
def Plin(p):
return 10.**(p/10.-3.)
def photons(power):
return Plin(power)/(hbar*cons_w)*(cons_ke/((cons_k/2)**2+cons_delta**2))
path = ... | 0.162879 | 0.234862 |
import prediction_grid as pg
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
from knn import knn_predict
import matplotlib.pyplot as plt
import numpy as np
import synth_data as sd
# Point to find the distance from
point = np.array([2.4, 2.2])
# Toy data points
points = np.array([[1, 1], ... | KNN Classification/scripts/testing.py | import prediction_grid as pg
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
from knn import knn_predict
import matplotlib.pyplot as plt
import numpy as np
import synth_data as sd
# Point to find the distance from
point = np.array([2.4, 2.2])
# Toy data points
points = np.array([[1, 1], ... | 0.886365 | 0.707361 |
import re
import sys
from pathlib import Path
from toollib import utils, regexp
from toollib.decorator import sys_required
from toollib.tcli import here
from toollib.tcli.base import BaseCmd
from toollib.tcli.option import Options, Arg
class Cmd(BaseCmd):
def __init__(self):
super().__init__()
def ... | toollib/tcli/commands/_set_sshkey.py | import re
import sys
from pathlib import Path
from toollib import utils, regexp
from toollib.decorator import sys_required
from toollib.tcli import here
from toollib.tcli.base import BaseCmd
from toollib.tcli.option import Options, Arg
class Cmd(BaseCmd):
def __init__(self):
super().__init__()
def ... | 0.171581 | 0.083928 |
def _get_buffer_view(in_obj):
if isinstance(in_obj, str):
raise TypeError('Unicode-objects must be encoded before calculating a CRC')
mv = memoryview(in_obj)
if mv.ndim > 1:
raise BufferError('Buffer must be single dimension')
return mv
def _crc8(data, crc, table):
mv = _get_buffe... | third_party/gsutil/third_party/crcmod/python3/crcmod/_crcfunpy.py |
def _get_buffer_view(in_obj):
if isinstance(in_obj, str):
raise TypeError('Unicode-objects must be encoded before calculating a CRC')
mv = memoryview(in_obj)
if mv.ndim > 1:
raise BufferError('Buffer must be single dimension')
return mv
def _crc8(data, crc, table):
mv = _get_buffe... | 0.566738 | 0.152916 |
import numpy
import dolfin
from ocellaris.utils import timeit, OcellarisError
@timeit
def get_dof_region_marks(simulation, V):
"""
Given a function space, return a dictionary mapping dof number to a
list of region number (indexed from 0, same as region list from the
input file).
Many dofs will n... | ocellaris/solver_parts/boundary_conditions/dof_marker.py |
import numpy
import dolfin
from ocellaris.utils import timeit, OcellarisError
@timeit
def get_dof_region_marks(simulation, V):
"""
Given a function space, return a dictionary mapping dof number to a
list of region number (indexed from 0, same as region list from the
input file).
Many dofs will n... | 0.758332 | 0.64607 |
import math
from openmdao.lib.datatypes.api import Float
from nastranwrapper.nastran import NastranComponent
class BladeStatic(NastranComponent):
""" Model of a Blade quad elements - Nastran Implementation."""
group1_thickness = Float(0.5, nastran_card="PSHELL",
nastran_id="1", nast... | src/nastranwrapper/test/nastran_models/blade_2dv_static_nastran.py | import math
from openmdao.lib.datatypes.api import Float
from nastranwrapper.nastran import NastranComponent
class BladeStatic(NastranComponent):
""" Model of a Blade quad elements - Nastran Implementation."""
group1_thickness = Float(0.5, nastran_card="PSHELL",
nastran_id="1", nast... | 0.63023 | 0.40928 |
import argparse as _argparse
from game import *
from player import *
from util import timefn
parser = _argparse.ArgumentParser()
parser.add_argument("-ep", "--epochs", type=int, help="Training epochs",
default=20000)
parser.add_argument("-l", "--length", type=int, help="Board length",
default=3)
parser.ad... | main.py | import argparse as _argparse
from game import *
from player import *
from util import timefn
parser = _argparse.ArgumentParser()
parser.add_argument("-ep", "--epochs", type=int, help="Training epochs",
default=20000)
parser.add_argument("-l", "--length", type=int, help="Board length",
default=3)
parser.ad... | 0.275227 | 0.117724 |
import csv
import numpy as np
import matplotlib.pyplot as plt
gpudata = np.zeros((5,6))
with open('exhongpugen9.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
line_count = 0
for row in csvreader:
if line_count == 0:
gpunames = row
line_count += 1
... | benchmarks/exhaustive_search/exhresplots.py | import csv
import numpy as np
import matplotlib.pyplot as plt
gpudata = np.zeros((5,6))
with open('exhongpugen9.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
line_count = 0
for row in csvreader:
if line_count == 0:
gpunames = row
line_count += 1
... | 0.27973 | 0.592519 |
import sys
sys.path.append('../code/')
import os
import math
import numpy as np
import AEPDGP_net
from tools import *
from dataset.UCIdataset import UCIDataset
from dataset.Facedataset import FaceDataset
import argparse
import time
parser = argparse.ArgumentParser(description='run regression experiment',
f... | dGP/numpy/tests/run_reg_data.py | import sys
sys.path.append('../code/')
import os
import math
import numpy as np
import AEPDGP_net
from tools import *
from dataset.UCIdataset import UCIDataset
from dataset.Facedataset import FaceDataset
import argparse
import time
parser = argparse.ArgumentParser(description='run regression experiment',
f... | 0.219003 | 0.167491 |
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(1)
sm.sendDelay(30)
sm.forcedInput(4)
OBJECT_1 = sm.sendNpcController(1032209, -15, -30)
sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0)
sm.showEffect("Effect/OnUserEff.img/guideEffect/evan... | scripts/field/enter_q25587e.py |
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(1)
sm.sendDelay(30)
sm.forcedInput(4)
OBJECT_1 = sm.sendNpcController(1032209, -15, -30)
sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0)
sm.showEffect("Effect/OnUserEff.img/guideEffect/evan... | 0.182753 | 0.22194 |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.cred import portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.conch import avatar
from twisted.conch.checkers import SSHPublicKeyChecker, InMemorySSHKeyDB
from twisted.conch.ssh import fact... | core/ssh.py |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.cred import portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.conch import avatar
from twisted.conch.checkers import SSHPublicKeyChecker, InMemorySSHKeyDB
from twisted.conch.ssh import fact... | 0.677581 | 0.148047 |
import json
import logging
import click
import numpy as np
from scipy.special import softmax
from sklearn import metrics
from .... import utils
from ....baselines.metrics import METRICS
logger = logging.getLogger(__name__)
# constants
REPORT_TEMPLATE =\
"""Scruples Resource Predictions Performance Report
======... | src/scruples/scripts/analyze/resource/predictions.py |
import json
import logging
import click
import numpy as np
from scipy.special import softmax
from sklearn import metrics
from .... import utils
from ....baselines.metrics import METRICS
logger = logging.getLogger(__name__)
# constants
REPORT_TEMPLATE =\
"""Scruples Resource Predictions Performance Report
======... | 0.705075 | 0.353121 |
import tensorflow as tf
import math
from capsule.capsule_layer import Capsule
from capsule.em_capsule_layer import EMCapsule
from capsule.gamma_capsule_layer import GammaCapsule
from capsule.conv_capsule_layer import ConvCapsule
from capsule.primary_capsule_layer import PrimaryCapsule
from capsule.reconstruction_netwo... | capsule/conv_capsule_network.py | import tensorflow as tf
import math
from capsule.capsule_layer import Capsule
from capsule.em_capsule_layer import EMCapsule
from capsule.gamma_capsule_layer import GammaCapsule
from capsule.conv_capsule_layer import ConvCapsule
from capsule.primary_capsule_layer import PrimaryCapsule
from capsule.reconstruction_netwo... | 0.814938 | 0.451387 |
import sys
from twisted.internet import defer, endpoints, protocol, reactor, ssl, task
from twisted.python import log
from twisted.words.protocols import irc
import config
import database
class IRCProtocol(irc.IRCClient):
nickname = config.nickname
def __init__(self):
self.deferred = defer.Deferre... | src/blahblahblahbot/bot.py | import sys
from twisted.internet import defer, endpoints, protocol, reactor, ssl, task
from twisted.python import log
from twisted.words.protocols import irc
import config
import database
class IRCProtocol(irc.IRCClient):
nickname = config.nickname
def __init__(self):
self.deferred = defer.Deferre... | 0.343562 | 0.051463 |
from django.core.exceptions import ObjectDoesNotExist
from rdkit.Chem import AllChem
from rdkit import Chem
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem import rdDepictor
from django_rdkit import models
import datetime
from django.contrib.auth.models import User
class Molecule(models.Model):
"""
Rep... | chemoinformatics/molecule_web_database/moldb/models.py | from django.core.exceptions import ObjectDoesNotExist
from rdkit.Chem import AllChem
from rdkit import Chem
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem import rdDepictor
from django_rdkit import models
import datetime
from django.contrib.auth.models import User
class Molecule(models.Model):
"""
Rep... | 0.527803 | 0.348562 |
import os
import numpy as np
import pandas as pd
from util import DATA_DIR, DOWNLOAD_DIR, load_data, reduce_dataset, keystrokes2events, events2keystrokes
GREYC_NISLAB_DATASET_URL = 'http://www.epaymentbiometrics.ensicaen.fr/wp-content/uploads/2015/04/greyc-nislab-keystroke-benchmark-dataset.xls'
CITEFA_DATASET_URL = ... | preprocess.py | import os
import numpy as np
import pandas as pd
from util import DATA_DIR, DOWNLOAD_DIR, load_data, reduce_dataset, keystrokes2events, events2keystrokes
GREYC_NISLAB_DATASET_URL = 'http://www.epaymentbiometrics.ensicaen.fr/wp-content/uploads/2015/04/greyc-nislab-keystroke-benchmark-dataset.xls'
CITEFA_DATASET_URL = ... | 0.459076 | 0.220941 |
from __future__ import absolute_import
import logging
from geocoder.location import Location
from geocoder.base import OneResult
from geocoder.uscensus import USCensusQuery
class USCensusReverseResult(OneResult):
@property
def ok(self):
return bool(self.raw['States'])
@property
def state(s... | geocoder/uscensus_reverse.py | from __future__ import absolute_import
import logging
from geocoder.location import Location
from geocoder.base import OneResult
from geocoder.uscensus import USCensusQuery
class USCensusReverseResult(OneResult):
@property
def ok(self):
return bool(self.raw['States'])
@property
def state(s... | 0.746971 | 0.21307 |
import json
from typing import Dict, Union
from peewee import (
SQL,
AutoField,
BlobField,
BooleanField,
Case,
CharField,
DoesNotExist,
FloatField,
ForeignKeyField,
IntegerField,
Model,
SqliteDatabase,
TextField,
fn,
)
from playhouse.hybrid import hybrid_property... | jukebox/db_models.py | import json
from typing import Dict, Union
from peewee import (
SQL,
AutoField,
BlobField,
BooleanField,
Case,
CharField,
DoesNotExist,
FloatField,
ForeignKeyField,
IntegerField,
Model,
SqliteDatabase,
TextField,
fn,
)
from playhouse.hybrid import hybrid_property... | 0.649912 | 0.201283 |
import mock
import unittest2
from squirrel_api import VoicemailUser, VoicemailMessage, VoicemailSuperUser
from squirrel_api.exceptions import SquirrelException, SquirrelApiException
from contextlib import contextmanager
class SquirrelUserAPI(unittest2.TestCase):
def setUp(self):
pass
@contextmanager... | tests/test_squirrel.py | import mock
import unittest2
from squirrel_api import VoicemailUser, VoicemailMessage, VoicemailSuperUser
from squirrel_api.exceptions import SquirrelException, SquirrelApiException
from contextlib import contextmanager
class SquirrelUserAPI(unittest2.TestCase):
def setUp(self):
pass
@contextmanager... | 0.443118 | 0.1933 |
import time
from functools import lru_cache
from trie import PrefixTree
class NumberConverter(object):
def __init__(self):
self.trie = PrefixTree()
with open('words_en.txt') as file:
lines = [line.rstrip('\n') for line in file]
for line in lines:
self.trie... | number_converter.py | import time
from functools import lru_cache
from trie import PrefixTree
class NumberConverter(object):
def __init__(self):
self.trie = PrefixTree()
with open('words_en.txt') as file:
lines = [line.rstrip('\n') for line in file]
for line in lines:
self.trie... | 0.598899 | 0.36376 |
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import forestci as fci
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
use_ci = True
mod0_rmse = []
mod1_rmse = []
def picp(y_true, y_pred, y_std, sigma=1):
cnt = 0
i... | parkinsons/utils.py | from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import forestci as fci
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
use_ci = True
mod0_rmse = []
mod1_rmse = []
def picp(y_true, y_pred, y_std, sigma=1):
cnt = 0
i... | 0.378459 | 0.420362 |
import sys
import itertools
class TipRemoval:
# Tips are error-prone ends of the reads that do not form a bubble but instead
# form a path starting in a vertex without incoming edges or ending in a vertex
# without outgoing edges in the de Bruijn graph.
def __init__(self, k, reads):
self.k ... | week3/Tip Removal.py | import sys
import itertools
class TipRemoval:
# Tips are error-prone ends of the reads that do not form a bubble but instead
# form a path starting in a vertex without incoming edges or ending in a vertex
# without outgoing edges in the de Bruijn graph.
def __init__(self, k, reads):
self.k ... | 0.368747 | 0.407746 |
import io
import os
import sys
from setuptools import find_packages, setup
DESCRIPTION = 'so eazy to interact with wechat api'
URL = 'https://github.com/chuter/wechat-requests'
EMAIL = '<EMAIL>'
AUTHOR = 'chuter'
VERSION = None
# What packages are required for this module to be executed?
REQUIRED = [
'six',
... | setup.py |
import io
import os
import sys
from setuptools import find_packages, setup
DESCRIPTION = 'so eazy to interact with wechat api'
URL = 'https://github.com/chuter/wechat-requests'
EMAIL = '<EMAIL>'
AUTHOR = 'chuter'
VERSION = None
# What packages are required for this module to be executed?
REQUIRED = [
'six',
... | 0.267026 | 0.177276 |
import mysql.connector
def conectar():
"""
Função para conectar ao servidor
"""
try:
conn = mysql.connector.connect(
host='localhost',
database='todos_filmes',
user='root',
password='<PASSWORD>')
return conn
except mysql... | PythonCruds/CrudFilmes.py | import mysql.connector
def conectar():
"""
Função para conectar ao servidor
"""
try:
conn = mysql.connector.connect(
host='localhost',
database='todos_filmes',
user='root',
password='<PASSWORD>')
return conn
except mysql... | 0.155303 | 0.157105 |
from __future__ import unicode_literals, division
import subprocess
import os
import shutil
import logging
from monty.shutil import decompress_dir
from monty.os.path import zpath
from pymatgen.io.cp2k.inputs import Cp2kInput, Keyword
from custodian.custodian import Job
from custodian.cp2k.interpreter import Cp2kModder... | custodian/cp2k/jobs.py | from __future__ import unicode_literals, division
import subprocess
import os
import shutil
import logging
from monty.shutil import decompress_dir
from monty.os.path import zpath
from pymatgen.io.cp2k.inputs import Cp2kInput, Keyword
from custodian.custodian import Job
from custodian.cp2k.interpreter import Cp2kModder... | 0.464173 | 0.18188 |
from common.deprecated import deprecated
from enum import IntEnum
from field_type import FieldType
_INT_TO_LEN_MAP = {
FieldType.Int8:1,
FieldType.Int16:2,
FieldType.Int32:4,
FieldType.Int64:8,
}
class _WireTypes(IntEnum):
VAR_INT = 0
LENGTH_DELIMITED = 1
#TODO: consider more optimal way to w... | proto/_tokenizer.py | from common.deprecated import deprecated
from enum import IntEnum
from field_type import FieldType
_INT_TO_LEN_MAP = {
FieldType.Int8:1,
FieldType.Int16:2,
FieldType.Int32:4,
FieldType.Int64:8,
}
class _WireTypes(IntEnum):
VAR_INT = 0
LENGTH_DELIMITED = 1
#TODO: consider more optimal way to w... | 0.227727 | 0.281057 |
class HashTableSeparateChaining(object):
'''
A Hash Table implementation by using normal Python List. Method supports for functions like:
Inserting Key, Removing Key, Getting Key, Checking the size, Iterating through all the keys etc.
Class allows to define a custom Hash Function, Initial List Capacity... | HASH_TABLES/SEPARATE_CHAINING/HashTable.py | class HashTableSeparateChaining(object):
'''
A Hash Table implementation by using normal Python List. Method supports for functions like:
Inserting Key, Removing Key, Getting Key, Checking the size, Iterating through all the keys etc.
Class allows to define a custom Hash Function, Initial List Capacity... | 0.608012 | 0.508605 |
from __future__ import division
import numpy as np
np.seterr(all='raise')
import logging
import os
import signal
import alsaaudio
from multiprocessing import Process
from pyffmpeg import FFMpegReader, PixelFormats
import pygame
from OpenGL.GL.shaders import compileProgram, compileShader
import VisionEgg
import Visi... | StimControl/LightStim/Movie.py |
from __future__ import division
import numpy as np
np.seterr(all='raise')
import logging
import os
import signal
import alsaaudio
from multiprocessing import Process
from pyffmpeg import FFMpegReader, PixelFormats
import pygame
from OpenGL.GL.shaders import compileProgram, compileShader
import VisionEgg
import Visi... | 0.733738 | 0.155623 |
import pytest
from construct import Container, ListContainer
from construct_typed import DataclassStruct
from bonfo.msp.codes import MSP
from bonfo.msp.fields.base import Direction
from bonfo.msp.fields.pids import PidAdvanced, PidCoefficients
from bonfo.msp.versions import MSPVersions
from tests import messages
from ... | tests/fields/test_pids.py | import pytest
from construct import Container, ListContainer
from construct_typed import DataclassStruct
from bonfo.msp.codes import MSP
from bonfo.msp.fields.base import Direction
from bonfo.msp.fields.pids import PidAdvanced, PidCoefficients
from bonfo.msp.versions import MSPVersions
from tests import messages
from ... | 0.515376 | 0.474022 |
import sys, os
from glob import glob
from setuptools import setup, find_packages
import platutils
platinfo = platutils.get_platform()
NAME = "pycopia-storage"
VERSION = "1.0"
if platinfo.is_linux():
DATAFILES = [
('/etc/pycopia', glob("etc/*.example") + glob("etc/*.dist")),
('/etc/pam.d', glo... | storage/setup.py |
import sys, os
from glob import glob
from setuptools import setup, find_packages
import platutils
platinfo = platutils.get_platform()
NAME = "pycopia-storage"
VERSION = "1.0"
if platinfo.is_linux():
DATAFILES = [
('/etc/pycopia', glob("etc/*.example") + glob("etc/*.dist")),
('/etc/pam.d', glo... | 0.236781 | 0.073032 |
"""Tests involving the tf.distributed datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import reference_test_base
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
def dataset_no_vars_loop(ds, dds):
for pr in dds:
tf.print(ds.r... | reference_tests/distributed_dataset_test.py | """Tests involving the tf.distributed datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import reference_test_base
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
def dataset_no_vars_loop(ds, dds):
for pr in dds:
tf.print(ds.r... | 0.637708 | 0.366448 |
import json
import os
import sys
import time
from json.decoder import JSONDecodeError
from shutil import which
from selenium import webdriver
def get_exec_path():
driver_name = 'chromedriver'
path = which(driver_name)
if path is None:
path = which(driver_name, path='.')
if path is None:
... | App.py |
import json
import os
import sys
import time
from json.decoder import JSONDecodeError
from shutil import which
from selenium import webdriver
def get_exec_path():
driver_name = 'chromedriver'
path = which(driver_name)
if path is None:
path = which(driver_name, path='.')
if path is None:
... | 0.108685 | 0.090253 |
from catm00dz.data import MoodExperienceImageCalendar
import collections
def average_mood_by_weekday(img_path):
weekday_counter = collections.defaultdict(int)
gpa_counter = collections.defaultdict(float)
experience_cal = MoodExperienceImageCalendar.from_path(
img_path
)
for experience i... | catm00dz/statistics.py | from catm00dz.data import MoodExperienceImageCalendar
import collections
def average_mood_by_weekday(img_path):
weekday_counter = collections.defaultdict(int)
gpa_counter = collections.defaultdict(float)
experience_cal = MoodExperienceImageCalendar.from_path(
img_path
)
for experience i... | 0.563258 | 0.439206 |
from django.utils import timezone
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework_simplejwt.views import TokenObtainPairView
from drf_yasg.utils import swagger_... | api/staff_api/views.py | from django.utils import timezone
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework_simplejwt.views import TokenObtainPairView
from drf_yasg.utils import swagger_... | 0.61231 | 0.094845 |
import math
from typing import Sequence
import fastfilters
import numpy
from sklearn.base import BaseEstimator, TransformerMixin
class Filter(BaseEstimator, TransformerMixin):
def fit(self, X=None, y=None, **kwargs):
return self
def transform(self, X):
raise NotImplementedError
@propert... | src/napari_ilastik/filters.py | import math
from typing import Sequence
import fastfilters
import numpy
from sklearn.base import BaseEstimator, TransformerMixin
class Filter(BaseEstimator, TransformerMixin):
def fit(self, X=None, y=None, **kwargs):
return self
def transform(self, X):
raise NotImplementedError
@propert... | 0.776029 | 0.271338 |
from server.databases.utils import database, convert_helper
from bson.objectid import ObjectId
from bson.errors import InvalidId
from typing import List, Tuple
from server.models.utils import ErrorModel
course_collection = database.get_collection("Classes")
async def get_all_courses() -> List[dict]:
""" Get all... | backend/server/databases/course.py | from server.databases.utils import database, convert_helper
from bson.objectid import ObjectId
from bson.errors import InvalidId
from typing import List, Tuple
from server.models.utils import ErrorModel
course_collection = database.get_collection("Classes")
async def get_all_courses() -> List[dict]:
""" Get all... | 0.434581 | 0.279116 |
from serene_load.helpers.containers.container_base import TempFileContainer, BaseContainer, BaseProcessor
import logging
import datetime
import io
import re
import subprocess
log = logging.getLogger()
class SevenZipFileContainer(TempFileContainer):
def decompress(self, source, target):
subprocess.check_c... | serene_load/serene_load/helpers/containers/container_7za.py | from serene_load.helpers.containers.container_base import TempFileContainer, BaseContainer, BaseProcessor
import logging
import datetime
import io
import re
import subprocess
log = logging.getLogger()
class SevenZipFileContainer(TempFileContainer):
def decompress(self, source, target):
subprocess.check_c... | 0.257018 | 0.103341 |
from selenium import webdriver
class AmazonScrapperChrome:
"""
Class that scrapes the amazon.in for the provided link
if any failure occurs during scraping, getter methods will return string: `failure`
operating flow:
constructor -> init_chrome_window -> set_product_url ->
... | scripts/amzn.py | from selenium import webdriver
class AmazonScrapperChrome:
"""
Class that scrapes the amazon.in for the provided link
if any failure occurs during scraping, getter methods will return string: `failure`
operating flow:
constructor -> init_chrome_window -> set_product_url ->
... | 0.483648 | 0.069668 |
import cupy as cp
def cdf(y,x,bw_method='scott',weight=1):
'''
Nadaraya watson conditional probability estimation is a way to estimate the conditional probability of a
random variable y given random variable x in a non-parametric way. It works for both uni-variate and
multi-variate data. It includes ... | kde_gpu/conditional_probability.py | import cupy as cp
def cdf(y,x,bw_method='scott',weight=1):
'''
Nadaraya watson conditional probability estimation is a way to estimate the conditional probability of a
random variable y given random variable x in a non-parametric way. It works for both uni-variate and
multi-variate data. It includes ... | 0.658527 | 0.686055 |