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 avista_data.issue_type import IssueType
from .database import Base
from sqlalchemy import Column, Integer, String, ForeignKey, Enum
class Issue(Base):
"""Represents an issue associated with the measured equipment
Attributes:
**id (int)**: The primary key for this issue
**name (str)**: N... | avista_data/issue.py | from avista_data.issue_type import IssueType
from .database import Base
from sqlalchemy import Column, Integer, String, ForeignKey, Enum
class Issue(Base):
"""Represents an issue associated with the measured equipment
Attributes:
**id (int)**: The primary key for this issue
**name (str)**: N... | 0.915477 | 0.280711 |
from __future__ import annotations
import io
import struct
from ranges import Range
from ...stream import RangeStream
from .data import COMPRESSIONS, TarData
__all__ = ["TarStream", "TarredFileInfo"]
class TarStream(RangeStream):
"""
As for :class:`~range_streams.stream.RangeStream`, but if ``scan_headers... | src/range_streams/codecs/tar/stream.py | from __future__ import annotations
import io
import struct
from ranges import Range
from ...stream import RangeStream
from .data import COMPRESSIONS, TarData
__all__ = ["TarStream", "TarredFileInfo"]
class TarStream(RangeStream):
"""
As for :class:`~range_streams.stream.RangeStream`, but if ``scan_headers... | 0.81468 | 0.331039 |
import rospy
import numpy as np
import math
import tf
from ackermann_msgs.msg import AckermannDriveStamped
from geometry_msgs.msg import PoseArray, Pose, PoseStamped
from std_msgs.msg import Bool
from nav_msgs.msg import Path
def distFromLine(x,y,x1,y1,x2,y2):
numerator= abs(x*(y2-y1) - (y*(x2-x1)) +x2*y1 -y2*... | scripts/pid_controller.py |
import rospy
import numpy as np
import math
import tf
from ackermann_msgs.msg import AckermannDriveStamped
from geometry_msgs.msg import PoseArray, Pose, PoseStamped
from std_msgs.msg import Bool
from nav_msgs.msg import Path
def distFromLine(x,y,x1,y1,x2,y2):
numerator= abs(x*(y2-y1) - (y*(x2-x1)) +x2*y1 -y2*... | 0.451447 | 0.145479 |
from boa.interop.System.Storage import *
from boa.interop.System.Runtime import *
from boa.interop.System.ExecutionEngine import *
from boa.builtins import concat
from boa.interop.Ontology.Native import *
from boa.builtins import state
ctx = GetContext()
selfAddr = GetExecutingScriptHash()
#ONT native contract addres... | boa_test/example/DomainAuction.py | from boa.interop.System.Storage import *
from boa.interop.System.Runtime import *
from boa.interop.System.ExecutionEngine import *
from boa.builtins import concat
from boa.interop.Ontology.Native import *
from boa.builtins import state
ctx = GetContext()
selfAddr = GetExecutingScriptHash()
#ONT native contract addres... | 0.457864 | 0.290069 |
from baseapp import BaseApplication
from shortcut import ShortcutMapper, Keystroke, parseKeySequence
from res import DirectoryWalker
import sys
import resource
import config
class Application(BaseApplication):
def __init__(self, url):
super(Application, self).__init__()
self.config = config.loadCo... | jkbiv/app.py | from baseapp import BaseApplication
from shortcut import ShortcutMapper, Keystroke, parseKeySequence
from res import DirectoryWalker
import sys
import resource
import config
class Application(BaseApplication):
def __init__(self, url):
super(Application, self).__init__()
self.config = config.loadCo... | 0.27513 | 0.105165 |
import re, os, sys, shutil
from math import *
from string import *
from optparse import OptionParser
import operator
import BED
import GenomeData
import get_total_tag_counts
import Background_island_probscore_statistics
import Utility
"""
Take in coords for bed_gaph type summary files and find 'islands' of modi... | stjude_sicer_noControl/resources/home/SICER_V1.1/SICER/src/find_islands_in_pr.py |
import re, os, sys, shutil
from math import *
from string import *
from optparse import OptionParser
import operator
import BED
import GenomeData
import get_total_tag_counts
import Background_island_probscore_statistics
import Utility
"""
Take in coords for bed_gaph type summary files and find 'islands' of modi... | 0.24608 | 0.33734 |
import pandas as pd
import numpy as np
import dsbox.datapreprocessing.profiler.helper_funcs as hf
from collections import OrderedDict
from collections import defaultdict
from collections import Counter
from builtins import filter
def ordered_dict2(column, k):
unique,counts = np.unique(column, return_counts=True)
... | dsbox-profiling/dsbox/datapreprocessing/profiler/feature_compute_hih.py | import pandas as pd
import numpy as np
import dsbox.datapreprocessing.profiler.helper_funcs as hf
from collections import OrderedDict
from collections import defaultdict
from collections import Counter
from builtins import filter
def ordered_dict2(column, k):
unique,counts = np.unique(column, return_counts=True)
... | 0.461988 | 0.5083 |
import numpy as np
import pyhrv
from .. import utils
from .. import eda
import json
def eda_features(signal=None, TH=0.08, sampling_rate=1000.):
"""Compute EDA characteristic metrics describing the signal.
Parameters
----------
signal : array
Input signal.
sampling_rate : float
Sa... | biosppy/features/eda_features.py | import numpy as np
import pyhrv
from .. import utils
from .. import eda
import json
def eda_features(signal=None, TH=0.08, sampling_rate=1000.):
"""Compute EDA characteristic metrics describing the signal.
Parameters
----------
signal : array
Input signal.
sampling_rate : float
Sa... | 0.635109 | 0.497192 |
import datetime
import os
from atomicwrites import atomic_write
import icalendar
import icalendar.tools
from ._compat import string_types, to_unicode
from .exceptions import CliError
class Task(object):
#: the absolute path to the directory containing all calendars
basepath = None
#: the calendar name... | watdo/model.py | import datetime
import os
from atomicwrites import atomic_write
import icalendar
import icalendar.tools
from ._compat import string_types, to_unicode
from .exceptions import CliError
class Task(object):
#: the absolute path to the directory containing all calendars
basepath = None
#: the calendar name... | 0.643329 | 0.108661 |
from . import datasets, synthetic
from ._version import __version__
from .blockreduce import BlockMean, BlockReduce
from .chain import Chain
from .coordinates import (
block_split,
expanding_window,
get_region,
grid_coordinates,
inside,
longitude_continuity,
pad_region,
profile_coordinat... | verde/__init__.py | from . import datasets, synthetic
from ._version import __version__
from .blockreduce import BlockMean, BlockReduce
from .chain import Chain
from .coordinates import (
block_split,
expanding_window,
get_region,
grid_coordinates,
inside,
longitude_continuity,
pad_region,
profile_coordinat... | 0.902423 | 0.351061 |
import dtsa2 as dtsa2
import dtsa2.mcSimulate3 as mc3
import time
def fullSimBulkStd(mat, det, e0, nTraj, outPath, dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False):
"""
fullSimBulkStd(mat, det, e0, nTraj, outPath, dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False)
Use mc3 simulation to simulate an... | mc3Scripts/testNewSimBulkStandard.py |
import dtsa2 as dtsa2
import dtsa2.mcSimulate3 as mc3
import time
def fullSimBulkStd(mat, det, e0, nTraj, outPath, dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False):
"""
fullSimBulkStd(mat, det, e0, nTraj, outPath, dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False)
Use mc3 simulation to simulate an... | 0.537284 | 0.519704 |
import os
from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
import random
import string
from messaging.py import email_message
'''
cur.execute("CREATE TABLE TempData (username VARCHAR(20), temperature smallint)")
cur.execute("CREATE TABLE user_USERNAME (dateAndtime VARCHAR(20), sensor text)")
... | Backend/app.py | import os
from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
import random
import string
from messaging.py import email_message
'''
cur.execute("CREATE TABLE TempData (username VARCHAR(20), temperature smallint)")
cur.execute("CREATE TABLE user_USERNAME (dateAndtime VARCHAR(20), sensor text)")
... | 0.109539 | 0.055387 |
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404, Http404
from django.contrib.auth.decorators import login_required
from .models import Comment
from .forms imp... | comments/views.py | from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404, Http404
from django.contrib.auth.decorators import login_required
from .models import Comment
from .forms imp... | 0.270962 | 0.06666 |
import time
import json
import requests
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
IP = '10.149.9.41'
USER = 'admin'
PASSWORD = '<PASSWORD>!'
session = requests.Session()
session.auth = (USER, PASSWORD)
session.verify = False ... | code/lesson04_crud.py | import time
import json
import requests
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
IP = '10.149.9.41'
USER = 'admin'
PASSWORD = '<PASSWORD>!'
session = requests.Session()
session.auth = (USER, PASSWORD)
session.verify = False ... | 0.088446 | 0.057971 |
from __future__ import annotations
from PySide6 import QtWidgets
from PySide6.QtCore import Qt, QSize, Slot
from PySide6.QtGui import QStandardItemModel, QStandardItem, QIcon
from nyaadesktop.scraper.nyaa import Details
from nyaadesktop.tabs.tab_signals import TabSignals
class FilesTabItem(QStandardItem):
def __... | nyaadesktop/tabs/files_tab.py | from __future__ import annotations
from PySide6 import QtWidgets
from PySide6.QtCore import Qt, QSize, Slot
from PySide6.QtGui import QStandardItemModel, QStandardItem, QIcon
from nyaadesktop.scraper.nyaa import Details
from nyaadesktop.tabs.tab_signals import TabSignals
class FilesTabItem(QStandardItem):
def __... | 0.593727 | 0.151247 |
import os
from aiida.parsers.parser import Parser
from aiida.common import NotExistent, OutputParsingError
from aiida.engine import ExitCode
from aiida.plugins import CalculationFactory
from aiida_ddec.utils import xyz2cif
DdecCalculation = CalculationFactory('ddec') # pylint: disable=invalid-name
class DdecParser(... | aiida_ddec/parsers/__init__.py | import os
from aiida.parsers.parser import Parser
from aiida.common import NotExistent, OutputParsingError
from aiida.engine import ExitCode
from aiida.plugins import CalculationFactory
from aiida_ddec.utils import xyz2cif
DdecCalculation = CalculationFactory('ddec') # pylint: disable=invalid-name
class DdecParser(... | 0.593609 | 0.142262 |
from __future__ import division # For Python 2.x compatibility
import random
from mesa import Model, Agent
from mesa.time import RandomActivation
from mesa.space import SingleGrid
from mesa.datacollection import DataCollector
from mesa.visualization.TextVisualization import (TextData, TextGrid,
TextVisualizatio... | examples/Schelling/Schelling.py | from __future__ import division # For Python 2.x compatibility
import random
from mesa import Model, Agent
from mesa.time import RandomActivation
from mesa.space import SingleGrid
from mesa.datacollection import DataCollector
from mesa.visualization.TextVisualization import (TextData, TextGrid,
TextVisualizatio... | 0.773259 | 0.473414 |
import argparse
from gscripts.qtools import Submitter
class CommandLine(object):
def __init__(self, inOpts=None):
self.parser = parser = argparse.ArgumentParser(
description='Submit a job to the cluster which concatenates your '
'miso summary files together and creates... | gscripts/miso/submit_concatenate_miso.py | import argparse
from gscripts.qtools import Submitter
class CommandLine(object):
def __init__(self, inOpts=None):
self.parser = parser = argparse.ArgumentParser(
description='Submit a job to the cluster which concatenates your '
'miso summary files together and creates... | 0.499023 | 0.103749 |
import re
import requests
'''
Usage:
moon.py -u zabbix http://x.x.x.x:xx
zabbix的 profileIdx2 参数存在问题,存在sql注入。
影响范围,3.0.3 成功, 3.2.6 失败。
禁用guest账户,升级版本
'''
def attack(URL):
print('[+]开始检测-zabbix_sql-CVE-2016-10134。[+]')
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (... | zabbix_vuln/zabbix_sql_CVE_2016_10134.py | import re
import requests
'''
Usage:
moon.py -u zabbix http://x.x.x.x:xx
zabbix的 profileIdx2 参数存在问题,存在sql注入。
影响范围,3.0.3 成功, 3.2.6 失败。
禁用guest账户,升级版本
'''
def attack(URL):
print('[+]开始检测-zabbix_sql-CVE-2016-10134。[+]')
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (... | 0.063135 | 0.119639 |
import sys
from time import sleep
import pytest
from hecate.hecate import Runner
def test_minesweeper_quit(runner):
runner.await_text("MiNeSwEePeR")
runner.write(":q")
runner.await_text("quit")
runner.press("Enter")
runner.await_exit()
def test_minesweeper_movement_and_flag_cell_invincible(runn... | tests/test_minesweeper.py | import sys
from time import sleep
import pytest
from hecate.hecate import Runner
def test_minesweeper_quit(runner):
runner.await_text("MiNeSwEePeR")
runner.write(":q")
runner.await_text("quit")
runner.press("Enter")
runner.await_exit()
def test_minesweeper_movement_and_flag_cell_invincible(runn... | 0.271928 | 0.365627 |
import zipfile, os, re, shutil
from uuid import uuid4 as hasher
from datetime import date
import logging
def dessem_source(fn, open_results=False, pmo_date=None):
if os.path.isdir(fn):
return DessemDir(fn, open_results, pmo_date)
if zipfile.is_zipfile(fn):
return DessemZipped(fn, open_... | deckparser/dessemsource.py | import zipfile, os, re, shutil
from uuid import uuid4 as hasher
from datetime import date
import logging
def dessem_source(fn, open_results=False, pmo_date=None):
if os.path.isdir(fn):
return DessemDir(fn, open_results, pmo_date)
if zipfile.is_zipfile(fn):
return DessemZipped(fn, open_... | 0.246352 | 0.104386 |
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel
from camd.agent.base import... | camd/agent/generic.py | import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel
from camd.agent.base import... | 0.857679 | 0.589066 |
import json
import pandas as pd
from IPython.display import display, Javascript, Markdown
from ._config import JS_LIBS_ONE, JS_LIBS_TWO, JS_SAVE
from .scripts import JS_JSON_PARSE
class GlobalOptions:
"""
Used to pass global options to Highcharts object
API: https://api.highcharts.com/highcharts
De... | ezhc/_global_options.py | {} | 0.305283 | 0.166777 |
import re
from sitelog.sections import (
SubSection,
SectionList,
)
from sitelog import _format_string
from datetime import datetime as dt
class CollocationInstrument(SubSection):
def __init__(
self, instrumentation_type="", status="", effective_dates="", notes=""
):
super().__init__(... | sitelog/collocation.py | import re
from sitelog.sections import (
SubSection,
SectionList,
)
from sitelog import _format_string
from datetime import datetime as dt
class CollocationInstrument(SubSection):
def __init__(
self, instrumentation_type="", status="", effective_dates="", notes=""
):
super().__init__(... | 0.488527 | 0.202838 |
from jeugdfonds.controllers.components.Deelgemeente import Deelgemeente
from jeugdfonds.models.ApplicantsModel import ApplicantsModel
import datetime
from flask import request
class ApplicantsController:
minAge = 4
maxAge = 18
gender = "%%" #gender
def GetAllApplicants(self):
a = ApplicantsMo... | Project/jeugdfonds/controllers/ApplicantsController.py | from jeugdfonds.controllers.components.Deelgemeente import Deelgemeente
from jeugdfonds.models.ApplicantsModel import ApplicantsModel
import datetime
from flask import request
class ApplicantsController:
minAge = 4
maxAge = 18
gender = "%%" #gender
def GetAllApplicants(self):
a = ApplicantsMo... | 0.264263 | 0.276025 |
import os
import cv2
import numpy as np
import util.io
from torch.utils.data import Dataset
class KITTIDataset(Dataset):
def __init__(self, img_dir, depth_dir, filenames_file, transform):
self.img_dir = img_dir
self.depth_dir = depth_dir
with open(filenames_file) as f:
image_pa... | KITTIDataset.py | import os
import cv2
import numpy as np
import util.io
from torch.utils.data import Dataset
class KITTIDataset(Dataset):
def __init__(self, img_dir, depth_dir, filenames_file, transform):
self.img_dir = img_dir
self.depth_dir = depth_dir
with open(filenames_file) as f:
image_pa... | 0.560253 | 0.197212 |
import os
import jieba
import jieba.posseg as ps
class_list = {'财经': 'Economics', '房产': 'House', '社会': 'Society', '时尚': 'Fashion', '教育': 'Education',
'科技': 'Technology', '时政': 'Politics', '体育': 'PE', '游戏': 'Game', '娱乐': 'Entertainment'}
with open('stop_words_ch.txt', 'r') as file:
stop_words = [i.s... | Preprocessing.py | import os
import jieba
import jieba.posseg as ps
class_list = {'财经': 'Economics', '房产': 'House', '社会': 'Society', '时尚': 'Fashion', '教育': 'Education',
'科技': 'Technology', '时政': 'Politics', '体育': 'PE', '游戏': 'Game', '娱乐': 'Entertainment'}
with open('stop_words_ch.txt', 'r') as file:
stop_words = [i.s... | 0.046389 | 0.099952 |
from Axon.Ipc import producerFinished
import Kamaelia.Testing.KamTestCase as KamTestCase
import Kamaelia.Testing.KamExpectMatcher as KamExpectMatcher
from Kamaelia.Util.OneShot import OneShot
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Protocol.HTTP.HTTPClient import SimpleHTTPClient
import FakeHttp... | Sketches/PO/KamPlanet/test/test_SimpleHTTPClient.py |
from Axon.Ipc import producerFinished
import Kamaelia.Testing.KamTestCase as KamTestCase
import Kamaelia.Testing.KamExpectMatcher as KamExpectMatcher
from Kamaelia.Util.OneShot import OneShot
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Protocol.HTTP.HTTPClient import SimpleHTTPClient
import FakeHttp... | 0.33764 | 0.206044 |
__author__ = 'yetone'
import sys
import inspect
from collections import OrderedDict
PY2 = sys.version_info[0] == 2
if not PY2:
text_type = str
izip = zip
def iteritems(dict):
return iter(dict.items())
else:
text_type = unicode
from itertools import izip
def iteritems(dict):
... | script_manager/compat/__init__.py | __author__ = 'yetone'
import sys
import inspect
from collections import OrderedDict
PY2 = sys.version_info[0] == 2
if not PY2:
text_type = str
izip = zip
def iteritems(dict):
return iter(dict.items())
else:
text_type = unicode
from itertools import izip
def iteritems(dict):
... | 0.224055 | 0.096408 |
results = { 1 :
[
[u"... is as sweet as can be. Perhaps sweeter than the cookies or ice cream.Here's the lowdown: Giant ice cream cookie <b>sandwiches</b> for super cheap. The flavor permutations are basically endless. I had snickerdoodle with cookies and cream ice ..."],
[u"... best BBQ Chicken pizza I have ever h... | test/wrapper/system_tests/highlight/expectedResultsAnalyzer.py | results = { 1 :
[
[u"... is as sweet as can be. Perhaps sweeter than the cookies or ice cream.Here's the lowdown: Giant ice cream cookie <b>sandwiches</b> for super cheap. The flavor permutations are basically endless. I had snickerdoodle with cookies and cream ice ..."],
[u"... best BBQ Chicken pizza I have ever h... | 0.201342 | 0.673944 |
import pandas as pd
import numpy as np
import os
def consolidate_data(file_root):
data_folder = os.path.join(os.getcwd(), 'data')
files = pd.Series(os.listdir(data_folder), name='Document')
file_filter = files.str.contains(file_root)
data = [pd.read_excel(os.path.join(data_folder, f))
... | ReportGen/prep.py | import pandas as pd
import numpy as np
import os
def consolidate_data(file_root):
data_folder = os.path.join(os.getcwd(), 'data')
files = pd.Series(os.listdir(data_folder), name='Document')
file_filter = files.str.contains(file_root)
data = [pd.read_excel(os.path.join(data_folder, f))
... | 0.2359 | 0.271659 |
# In[2]:
import pandas as pd
import requests
import numpy as np
from datetime import datetime
from urllib.request import urlopen
from lxml import etree
import io
from alphacast import Alphacast
from dotenv import dotenv_values
# In[3]:
#Obtengo la url del file a través de su xpath
url = "https://www.bcu.gub.uy/E... | 0640.Inflation-Uruguay-BCU-Inflation_Expectations.py |
# In[2]:
import pandas as pd
import requests
import numpy as np
from datetime import datetime
from urllib.request import urlopen
from lxml import etree
import io
from alphacast import Alphacast
from dotenv import dotenv_values
# In[3]:
#Obtengo la url del file a través de su xpath
url = "https://www.bcu.gub.uy/E... | 0.340705 | 0.287493 |
import os.path
from PIL import Image
import cv2
import numpy as np
from glob import glob
# Torch files
import torch
import torch.utils.data
import torchvision.transforms as transforms
# ███ ███ ███ ██ ██ ███████ ████████
# ████ ████ ████ ██ ██ ██ ██
# ██ ████ ██ ██ ██ ██ ██ ███████ ██
# ... | datasets.py | import os.path
from PIL import Image
import cv2
import numpy as np
from glob import glob
# Torch files
import torch
import torch.utils.data
import torchvision.transforms as transforms
# ███ ███ ███ ██ ██ ███████ ████████
# ████ ████ ████ ██ ██ ██ ██
# ██ ████ ██ ██ ██ ██ ██ ███████ ██
# ... | 0.575707 | 0.273059 |
import ujson
from flask import current_app
from flask_classy import request, route, Response
from vlab_inf_common.views import TaskView
from vlab_inf_common.vmware import vCenter, vim
from vlab_api_common import describe, get_logger, requires, validate_input
from vlab_router_api.lib import const
logger = get_logger... | vlab_router_api/lib/views/router.py | import ujson
from flask import current_app
from flask_classy import request, route, Response
from vlab_inf_common.views import TaskView
from vlab_inf_common.vmware import vCenter, vim
from vlab_api_common import describe, get_logger, requires, validate_input
from vlab_router_api.lib import const
logger = get_logger... | 0.426202 | 0.120361 |
from paver.easy import *
from shutil import rmtree, copytree, copyfile
from subprocess import call
import os
import getpass
@task
def clean():
print '************************************'
print '* Cleaning *'
print '************************************'
rmtree('static', True)
try:
os... | python/pavement.py |
from paver.easy import *
from shutil import rmtree, copytree, copyfile
from subprocess import call
import os
import getpass
@task
def clean():
print '************************************'
print '* Cleaning *'
print '************************************'
rmtree('static', True)
try:
os... | 0.194024 | 0.056862 |
import copy
import itertools
from typing import List, Union
import numpy as np
from qutip import (Qobj, basis, gate_expand_1toN, qeye,
sigmax, sigmay, sigmaz, snot, tensor, rx, ry, rz, cnot)
from qiskit import IBMQ, Aer, execute, QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua im... | estimators.py | import copy
import itertools
from typing import List, Union
import numpy as np
from qutip import (Qobj, basis, gate_expand_1toN, qeye,
sigmax, sigmay, sigmaz, snot, tensor, rx, ry, rz, cnot)
from qiskit import IBMQ, Aer, execute, QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua im... | 0.841793 | 0.416441 |
import argparse
from torch.utils.data import DataLoader
from os import path
import pandas as pd
import torch
import os
from structures.classification_utils import unsupervised_test, load_model, read_json
from structures.data_utils import MRIDataset, Normalization, load_data
parser = argparse.ArgumentParser(descriptio... | src/deep/test_evaluation.py | import argparse
from torch.utils.data import DataLoader
from os import path
import pandas as pd
import torch
import os
from structures.classification_utils import unsupervised_test, load_model, read_json
from structures.data_utils import MRIDataset, Normalization, load_data
parser = argparse.ArgumentParser(descriptio... | 0.551091 | 0.292027 |
import itertools
import gpuscheduler
import argparse
import os
import uuid
from itertools import product
parser = argparse.ArgumentParser(description='Compute script.')
parser.add_argument('--dry', action='store_true')
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()
cmd = 'OMP_NUM_THR... | scripts/probe/probe_grid.py | import itertools
import gpuscheduler
import argparse
import os
import uuid
from itertools import product
parser = argparse.ArgumentParser(description='Compute script.')
parser.add_argument('--dry', action='store_true')
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()
cmd = 'OMP_NUM_THR... | 0.186465 | 0.127544 |
import argparse
import random
import bot_classes
import time
import math
from Server_comms import *
def heading_to(x, y):
heading = float(math.atan2((y - us.tank_Y), (x - us.tank_X))) # returns heading in radians
heading = float(math.degrees(heading))
heading = math.fabs(heading - 360) % 360
return ... | code/pyTankBot/Main.py | import argparse
import random
import bot_classes
import time
import math
from Server_comms import *
def heading_to(x, y):
heading = float(math.atan2((y - us.tank_Y), (x - us.tank_X))) # returns heading in radians
heading = float(math.degrees(heading))
heading = math.fabs(heading - 360) % 360
return ... | 0.222362 | 0.292153 |
# imports
import os
import sys
# website definitions
def _shopee(word_l):
return 'https://shopee.sg/search?keyword=' + '%20'.join(word_l) + '&page=0&sortBy=sales'
def _carousell(word_l):
return 'https://sg.carousell.com/search/' + '%20'.join(word_l) + '?'
def _lazada(word_l):
return 'https://www.lazada.sg... | shopsearch.py | # imports
import os
import sys
# website definitions
def _shopee(word_l):
return 'https://shopee.sg/search?keyword=' + '%20'.join(word_l) + '&page=0&sortBy=sales'
def _carousell(word_l):
return 'https://sg.carousell.com/search/' + '%20'.join(word_l) + '?'
def _lazada(word_l):
return 'https://www.lazada.sg... | 0.2522 | 0.286556 |
import sys
import copy
import numpy as np
from typing import Sequence, Union
from bioslds.markov import SemiMarkov
from bioslds.utils import rle_encode
class SwitchingSnippetSignal:
""" A signal generated from switching snippets.
Attributes
==========
y : np.ndarray
The signal.
usage_s... | bioslds/snippet_dataset.py | import sys
import copy
import numpy as np
from typing import Sequence, Union
from bioslds.markov import SemiMarkov
from bioslds.utils import rle_encode
class SwitchingSnippetSignal:
""" A signal generated from switching snippets.
Attributes
==========
y : np.ndarray
The signal.
usage_s... | 0.777469 | 0.566318 |
import os
import sys
import json
import time
import boto3
from botocore.exceptions import ClientError
_endpoint_name = os.environ.get('EndpointName', 'no-endpoint-name')
_statemachine_arn = os.environ.get('StateMachineArn', 'no-statemachine-arn')
_bucket_key_for_input = os.environ.get('BucketKeyForInput', 'no-bucket... | codes/lambda/mlops-trigger-statemachine/src/handler.py | import os
import sys
import json
import time
import boto3
from botocore.exceptions import ClientError
_endpoint_name = os.environ.get('EndpointName', 'no-endpoint-name')
_statemachine_arn = os.environ.get('StateMachineArn', 'no-statemachine-arn')
_bucket_key_for_input = os.environ.get('BucketKeyForInput', 'no-bucket... | 0.120737 | 0.0771 |
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
from flask_login import UserMixin
from libgravatar import Gravatar
from Mess_Management_System import db
class User(UserMixin, db.Model):
"""User database class
Args:
UserMixin : Flask-Login Mixin
db : Database Model Base Cl... | Mess_Management_System/model/models.py | from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
from flask_login import UserMixin
from libgravatar import Gravatar
from Mess_Management_System import db
class User(UserMixin, db.Model):
"""User database class
Args:
UserMixin : Flask-Login Mixin
db : Database Model Base Cl... | 0.789518 | 0.060446 |
import numpy as np
def eval_func(distmat, q_pids, g_pids, q_camids, g_camids, q_paths, g_paths, max_rank=50):
"""Evaluation with market1501 metric
Key: for each query identity, its gallery images from the same camera view are discarded.
"""
num_q, num_g = distmat.shape
if num_g < max_rank:... | data/datasets/eval_reid.py | import numpy as np
def eval_func(distmat, q_pids, g_pids, q_camids, g_camids, q_paths, g_paths, max_rank=50):
"""Evaluation with market1501 metric
Key: for each query identity, its gallery images from the same camera view are discarded.
"""
num_q, num_g = distmat.shape
if num_g < max_rank:... | 0.536556 | 0.389953 |
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from os import listdir, remove, rmdir, walk
from os.path import isdir, join
from shutil import rmtree
from typing import Any
def remove_objects(*, objects: tuple = ()) -> None:
"""
Removes files or folders.
>>> from... | snakypy/helpers/os/removals.py | from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from os import listdir, remove, rmdir, walk
from os.path import isdir, join
from shutil import rmtree
from typing import Any
def remove_objects(*, objects: tuple = ()) -> None:
"""
Removes files or folders.
>>> from... | 0.638835 | 0.254044 |
# dcf
# ---
# A Python library for generating discounted cashflows.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.4, copyright Saturday, 10 October 2020
# Website: https://github.com/sonntagsgesicht/dcf
# License: Apache License 2.0 (see LICENSE file)
from math import ... | test/unittests/interpolation_tests.py |
# dcf
# ---
# A Python library for generating discounted cashflows.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.4, copyright Saturday, 10 October 2020
# Website: https://github.com/sonntagsgesicht/dcf
# License: Apache License 2.0 (see LICENSE file)
from math import ... | 0.708616 | 0.67324 |
import enum
FALLBACK_TERMINAL_WIDTH = 80
ENOENT = "lss: cannot access '%s': No such file or directory"
ENOTDIR = "lss: '%s' is not a directory"
STOPITER = "'%s': broken reparse point encountered, iteration stopped"
class Category(enum.IntEnum):
BROKEN_LINK = enum.auto()
DIRECTORY = enum.auto()
SYMLINK =... | lss/constants.py | import enum
FALLBACK_TERMINAL_WIDTH = 80
ENOENT = "lss: cannot access '%s': No such file or directory"
ENOTDIR = "lss: '%s' is not a directory"
STOPITER = "'%s': broken reparse point encountered, iteration stopped"
class Category(enum.IntEnum):
BROKEN_LINK = enum.auto()
DIRECTORY = enum.auto()
SYMLINK =... | 0.421314 | 0.136666 |
class DictMapper:
def __init__(self, mappings: dict, fields_to_add: dict = None):
"""
Initializes a DictMapper instance.
:param dict[str, str] mappings: The source > target key mapping
:param dict[str, Any]|None fields_to_add: Which key: value pairs to add
... | solr_tasks/lib/mapper.py |
class DictMapper:
def __init__(self, mappings: dict, fields_to_add: dict = None):
"""
Initializes a DictMapper instance.
:param dict[str, str] mappings: The source > target key mapping
:param dict[str, Any]|None fields_to_add: Which key: value pairs to add
... | 0.90881 | 0.494202 |
import json
import os.path
import pathlib
import urllib.request
import time
from . import helper
from . import udisks2
from . import sudo
_IMAGINGUTILITY_URL = 'https://downloads.raspberrypi.org/os_list_imagingutility_v2.json'
def flatten(tree):
result = []
for i in tree:
if 'subitems' in i:
... | src/bake_a_py/imaging_utility.py | import json
import os.path
import pathlib
import urllib.request
import time
from . import helper
from . import udisks2
from . import sudo
_IMAGINGUTILITY_URL = 'https://downloads.raspberrypi.org/os_list_imagingutility_v2.json'
def flatten(tree):
result = []
for i in tree:
if 'subitems' in i:
... | 0.549157 | 0.181953 |
import discord
import asyncio
import platform
import colorsys
import youtube_dl
import os
import time
import datetime
import random
from discord.ext import commands
from discord.ext.commands import Bot
from discord.utils import find
from discord import Game, Embed, Color, Status, ChannelType
cc = 0xC72323
bot = comman... | audio.py | import discord
import asyncio
import platform
import colorsys
import youtube_dl
import os
import time
import datetime
import random
from discord.ext import commands
from discord.ext.commands import Bot
from discord.utils import find
from discord import Game, Embed, Color, Status, ChannelType
cc = 0xC72323
bot = comman... | 0.158077 | 0.083928 |
r"""Downloads and converts cifar10/100 data to TFRecords of TF-Example protos.
This module downloads the cifar data, uncompresses it, reads the files that
make up the cifar data and creates two TFRecord datasets: one for train and one
for test. Each TFRecord dataset is comprised of a set of TF-Example protocol
buffers... | slim/datasets/download_and_convert_cifar.py | r"""Downloads and converts cifar10/100 data to TFRecords of TF-Example protos.
This module downloads the cifar data, uncompresses it, reads the files that
make up the cifar data and creates two TFRecord datasets: one for train and one
for test. Each TFRecord dataset is comprised of a set of TF-Example protocol
buffers... | 0.71413 | 0.524151 |
import numpy
from scipy.signal import convolve2d
from nicos.core import Attach, DeviceAlias, Measurable, Moveable, Override, \
Param, Value, listof, oneof, status, tupleof
from nicos.devices.generic.detector import PostprocessPassiveChannel
class DetSwitcher(Moveable):
"""Switches the channel alias device b... | nicos_mlz/kws3/devices/daq.py |
import numpy
from scipy.signal import convolve2d
from nicos.core import Attach, DeviceAlias, Measurable, Moveable, Override, \
Param, Value, listof, oneof, status, tupleof
from nicos.devices.generic.detector import PostprocessPassiveChannel
class DetSwitcher(Moveable):
"""Switches the channel alias device b... | 0.745028 | 0.400691 |
from __future__ import unicode_literals, absolute_import
import argparse, sys, os
import re
from RecipeReader import RecipeReader
def read_script(filename):
top_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
script_file = os.path.join(top_dir, filename)
with open(script_file, "r") as f:... | ci/recipe/recipe_to_bash.py | from __future__ import unicode_literals, absolute_import
import argparse, sys, os
import re
from RecipeReader import RecipeReader
def read_script(filename):
top_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
script_file = os.path.join(top_dir, filename)
with open(script_file, "r") as f:... | 0.291989 | 0.060308 |
import discord
from urllib.parse import quote
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
from discord_slash.utils.manage_commands import create_option
class Lyrics(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_slash(name="lyrics", description... | cogs/lyrics.py | import discord
from urllib.parse import quote
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
from discord_slash.utils.manage_commands import create_option
class Lyrics(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_slash(name="lyrics", description... | 0.356111 | 0.09343 |
import sys
import re
from pprint import pprint
import logging
from ckan.lib.cli import CkanCommand
from ckan.lib.helpers import json
from ckanext.spatial.lib import save_package_extent
log = logging.getLogger(__name__)
class Spatial(CkanCommand):
'''Performs spatially related operations.
Usage:
spati... | ckanext/spatial/commands/spatial.py | import sys
import re
from pprint import pprint
import logging
from ckan.lib.cli import CkanCommand
from ckan.lib.helpers import json
from ckanext.spatial.lib import save_package_extent
log = logging.getLogger(__name__)
class Spatial(CkanCommand):
'''Performs spatially related operations.
Usage:
spati... | 0.249539 | 0.194808 |
import pandas as pd
from graphpanda.graphpanda import Node, Domain, form_node_domain, form_edges, exact_match
def test_node_uniqueness():
'''
Nodes should be unique.
'''
n1 = Node("Test",{})
n2 = Node("Test",{})
result = set()
result.add(n1)
result.add(n2)
assert result == {n1}
... | tests/test_cypherphy.py | import pandas as pd
from graphpanda.graphpanda import Node, Domain, form_node_domain, form_edges, exact_match
def test_node_uniqueness():
'''
Nodes should be unique.
'''
n1 = Node("Test",{})
n2 = Node("Test",{})
result = set()
result.add(n1)
result.add(n2)
assert result == {n1}
... | 0.55929 | 0.574514 |
import sys
import os
import glob
import pandas as pd
import argparse
import plotly.express as px
input_db_filename = sys.argv[1]
library_results_filename = sys.argv[2]
output_results_filename = sys.argv[3]
input_db_df = pd.read_csv(input_db_filename, sep=',')
original_results_df = pd.read_csv(library_results_filename... | workflow/bin/template_script.py | import sys
import os
import glob
import pandas as pd
import argparse
import plotly.express as px
input_db_filename = sys.argv[1]
library_results_filename = sys.argv[2]
output_results_filename = sys.argv[3]
input_db_df = pd.read_csv(input_db_filename, sep=',')
original_results_df = pd.read_csv(library_results_filename... | 0.306527 | 0.146362 |
from simplegp.Nodes.BaseNode import Node
import numpy as np
class AddNode(Node):
def __init__(self):
super(AddNode, self).__init__()
self.arity = 2
def __repr__(self):
return '+'
def _GetHumanExpressionSpecificNode(self, args):
return '( ' + args[0] + ' + ' + args[1] + ' )'
def _GetPytorchExpressionSpe... | simplegp/Nodes/LossFunctionEvoNodes.py | from simplegp.Nodes.BaseNode import Node
import numpy as np
class AddNode(Node):
def __init__(self):
super(AddNode, self).__init__()
self.arity = 2
def __repr__(self):
return '+'
def _GetHumanExpressionSpecificNode(self, args):
return '( ' + args[0] + ' + ' + args[1] + ' )'
def _GetPytorchExpressionSpe... | 0.35869 | 0.335432 |
import unittest
import logging
from pymongo.connection import Connection
from os.path import dirname
from logging.config import fileConfig, dictConfig
class TestConfig(unittest.TestCase):
def setUp(self):
filename = dirname(__file__) + '/logging-test.config'
fileConfig(filename)
""" Crea... | tests/test_config.py | import unittest
import logging
from pymongo.connection import Connection
from os.path import dirname
from logging.config import fileConfig, dictConfig
class TestConfig(unittest.TestCase):
def setUp(self):
filename = dirname(__file__) + '/logging-test.config'
fileConfig(filename)
""" Crea... | 0.355439 | 0.175768 |
from __future__ import print_function
from make_extended_lexicon import (getHomophones, readLexiconEntries,
addOOVs, addTruncations, writeHomophones, writeLexicon, writeTruncations,
getFilteredLexicon)
ENCODING="utf8"
IMPORTANT_WORDS = set([])
WORDPOS_SEPARATOR = "@"
def uniquefyPrompt(prompt, lexicondict):
... | kaldi-scripts/make_utt_specific_lexicon.py | from __future__ import print_function
from make_extended_lexicon import (getHomophones, readLexiconEntries,
addOOVs, addTruncations, writeHomophones, writeLexicon, writeTruncations,
getFilteredLexicon)
ENCODING="utf8"
IMPORTANT_WORDS = set([])
WORDPOS_SEPARATOR = "@"
def uniquefyPrompt(prompt, lexicondict):
... | 0.606848 | 0.088662 |
"""Server of zenref to handle Github Webhook"""
from __future__ import print_function, division, unicode_literals
import sys
import collections
import toml
from tornado import web
from tornado import httpserver
from tornado import ioloop
from tornado import log
from asyncat.client import AsyncGithubClient
from . i... | hindsight/app.py | """Server of zenref to handle Github Webhook"""
from __future__ import print_function, division, unicode_literals
import sys
import collections
import toml
from tornado import web
from tornado import httpserver
from tornado import ioloop
from tornado import log
from asyncat.client import AsyncGithubClient
from . i... | 0.384681 | 0.219693 |
import itertools
from flask import Blueprint, make_response
from modules.database import get_db_conn
from server_error import server_error
route_lessons = Blueprint('route_lessons', __name__)
# --------------------------
# Return lessons list
# --------------------------
@route_lessons.route('/lessons', methods=['... | server/routes/lessons.py | import itertools
from flask import Blueprint, make_response
from modules.database import get_db_conn
from server_error import server_error
route_lessons = Blueprint('route_lessons', __name__)
# --------------------------
# Return lessons list
# --------------------------
@route_lessons.route('/lessons', methods=['... | 0.342901 | 0.147801 |
import pytest
import requests
import re
def t_expected_output(url: str, text: str, expect: str):
text = text.strip()
response = requests.post(f"{url}/autocomplete", json={
"text": text
})
if response.status_code > 200:
assert False, "http request should success"
return
resu... | test/test_baseline.py | import pytest
import requests
import re
def t_expected_output(url: str, text: str, expect: str):
text = text.strip()
response = requests.post(f"{url}/autocomplete", json={
"text": text
})
if response.status_code > 200:
assert False, "http request should success"
return
resu... | 0.595845 | 0.529081 |
import Utils as Utils
class Graph:
""" Graph class for converting from py2neo graphs into a json format that the front-end can eat.
Base class must implement _init_node_attributes and _init_edge_attributes. These attribute lists provide
a mapping from neo4j attributes to something appropriate for... | connectivity_matrix_neo/Graph.py | import Utils as Utils
class Graph:
""" Graph class for converting from py2neo graphs into a json format that the front-end can eat.
Base class must implement _init_node_attributes and _init_edge_attributes. These attribute lists provide
a mapping from neo4j attributes to something appropriate for... | 0.61231 | 0.450057 |
from database.utils.connector import BasicDatabaseConnector
class VMServerDBConnector(BasicDatabaseConnector):
'''
Esta clase permite gestionar las diferentes características de las imágenes
accesibles en el servidor de máquinas virtuales actual.
'''
def __init__(self, sqlUser, sqlPass, ... | src/web/CygnusCloud/modules/database/vmServer/vmServerDB.py | from database.utils.connector import BasicDatabaseConnector
class VMServerDBConnector(BasicDatabaseConnector):
'''
Esta clase permite gestionar las diferentes características de las imágenes
accesibles en el servidor de máquinas virtuales actual.
'''
def __init__(self, sqlUser, sqlPass, ... | 0.337749 | 0.158109 |
def test_mongo_insert():
from coeusfactory import ConnectorFactory
cf = ConnectorFactory(
"mongo",
db="test",
)
cf.handler.initialize()
cf.handler.connect()
Users = cf.get_model("users")
user = Users.add({"name": "<NAME>"})
assert Users.get_by_id(user.inserted_id) != Non... | tests/test_mongo_repository.py | def test_mongo_insert():
from coeusfactory import ConnectorFactory
cf = ConnectorFactory(
"mongo",
db="test",
)
cf.handler.initialize()
cf.handler.connect()
Users = cf.get_model("users")
user = Users.add({"name": "<NAME>"})
assert Users.get_by_id(user.inserted_id) != Non... | 0.416559 | 0.218253 |
from handy import *
lines = read(23)
#lines = read_test(23)
rooms = {'a':(11,12),'b':(13,14),'c':(15,16),'d':(17,18)}
hallway = list(range(0,11))
bottoms = [12, 14, 16, 18]
tops = [11, 13, 15, 17]
entries = {'a':2, 'b':4, 'c':6, 'd':8}
exits = {11: 2, 13:4, 15:6, 17:8}
energies = {'a':1,'b':10,'c':100,'d':1000}
enter... | 2021/23.py | from handy import *
lines = read(23)
#lines = read_test(23)
rooms = {'a':(11,12),'b':(13,14),'c':(15,16),'d':(17,18)}
hallway = list(range(0,11))
bottoms = [12, 14, 16, 18]
tops = [11, 13, 15, 17]
entries = {'a':2, 'b':4, 'c':6, 'd':8}
exits = {11: 2, 13:4, 15:6, 17:8}
energies = {'a':1,'b':10,'c':100,'d':1000}
enter... | 0.254509 | 0.362433 |
from abc import ABC
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import jsons
from bohr.collection.artifacts import artifact_map
from bohr.collection.dataloaders.from_csv import CsvDatasetLoader
from bohr.collection.datamappers import default_mappers
f... | bohr/datamodel/dataset.py | from abc import ABC
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import jsons
from bohr.collection.artifacts import artifact_map
from bohr.collection.dataloaders.from_csv import CsvDatasetLoader
from bohr.collection.datamappers import default_mappers
f... | 0.81626 | 0.268618 |
from greww.data.json.json_utils import (make_json,
feed_json,
count_json,
unfeed_json,
read_json,
search_json,
... | greww/data/tests/tests_json.py | from greww.data.json.json_utils import (make_json,
feed_json,
count_json,
unfeed_json,
read_json,
search_json,
... | 0.38943 | 0.26462 |
class GlyphTypeface(object,ITypefaceMetrics,ISupportInitialize):
"""
Specifies a physical font face that corresponds to a font file on the disk.
GlyphTypeface()
GlyphTypeface(typefaceSource: Uri)
GlyphTypeface(typefaceSource: Uri,styleSimulations: StyleSimulations)
"""
def ComputeSubset(self,glyphs... | stubs.min/System/Windows/Media/__init___parts/GlyphTypeface.py | class GlyphTypeface(object,ITypefaceMetrics,ISupportInitialize):
"""
Specifies a physical font face that corresponds to a font file on the disk.
GlyphTypeface()
GlyphTypeface(typefaceSource: Uri)
GlyphTypeface(typefaceSource: Uri,styleSimulations: StyleSimulations)
"""
def ComputeSubset(self,glyphs... | 0.831554 | 0.225438 |
"""A simple command-line utility to process streams of compressed files."""
# Inspired by mediawiki-utilities by halfak et al.
# See:
# https://github.com/mediawiki-utilities/python-mediawiki-utilities/
import sys
import csv
import argparse
import pathlib
from .functions import open_file, file
########## helpers
d... | compressed_stream/__main__.py | """A simple command-line utility to process streams of compressed files."""
# Inspired by mediawiki-utilities by halfak et al.
# See:
# https://github.com/mediawiki-utilities/python-mediawiki-utilities/
import sys
import csv
import argparse
import pathlib
from .functions import open_file, file
########## helpers
d... | 0.611962 | 0.278907 |
from styx_msgs.msg import TrafficLight
import cv2
import time
import datetime
import random
import img_proc
from classifier.yolo import YOLO
import rospy
import yaml
import os
import numpy as np
class TLClassifier(object):
yolo = None
def __init__(self):
traffic_light_config = rospy.get_param("/traffic... | ros/src/tl_detector/light_classification/tl_classifier.py | from styx_msgs.msg import TrafficLight
import cv2
import time
import datetime
import random
import img_proc
from classifier.yolo import YOLO
import rospy
import yaml
import os
import numpy as np
class TLClassifier(object):
yolo = None
def __init__(self):
traffic_light_config = rospy.get_param("/traffic... | 0.669205 | 0.180215 |
# Lint as: python3
"""Main methods for Learner process of Falken service.."""
import traceback
import uuid
from learner import assignment_processor
from learner import file_system
from learner import storage
from learner.brains import brain_cache
from log import falken_logging
# pylint: disable=g-bad-import-order
i... | service/learner/learner.py |
# Lint as: python3
"""Main methods for Learner process of Falken service.."""
import traceback
import uuid
from learner import assignment_processor
from learner import file_system
from learner import storage
from learner.brains import brain_cache
from log import falken_logging
# pylint: disable=g-bad-import-order
i... | 0.720762 | 0.284365 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('preferences', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_... | users/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('preferences', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_... | 0.519765 | 0.151498 |
import os
import json
import peewee
import hashlib
import peewee_async
from core.model import base_model
from core.components import exceptions
from core.components import rasp_result
from core.components.logger import Logger
class ConfigModel(base_model.BaseModel):
def __init__(self, *args, **kwargs):
... | openrasp_iast/core/model/config_model.py | import os
import json
import peewee
import hashlib
import peewee_async
from core.model import base_model
from core.components import exceptions
from core.components import rasp_result
from core.components.logger import Logger
class ConfigModel(base_model.BaseModel):
def __init__(self, *args, **kwargs):
... | 0.404037 | 0.102036 |
import maya.mel as mm
ctl_root = '''
createNode transform -n "ctlGp";
createNode transform -n "facialRig_Gp" -p "ctlGp";
'''
teeth_upper_ctl = '''
createNode transform -n "teethUpper_ctlGp" -p "facialRig_Gp";
setAttr ".t" -type "double3" 0.0051069147026953114 184.54078924201585 5.2829795741889614 ;
... | etc/riggingMisc.py | import maya.mel as mm
ctl_root = '''
createNode transform -n "ctlGp";
createNode transform -n "facialRig_Gp" -p "ctlGp";
'''
teeth_upper_ctl = '''
createNode transform -n "teethUpper_ctlGp" -p "facialRig_Gp";
setAttr ".t" -type "double3" 0.0051069147026953114 184.54078924201585 5.2829795741889614 ;
... | 0.149283 | 0.186058 |
import gym
import re
import glob
import numpy as np
import matplotlib.pyplot as plt
from helpers.DataFiles import DataFiles
# sort helping
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.co... | helpers/Agent.py | import gym
import re
import glob
import numpy as np
import matplotlib.pyplot as plt
from helpers.DataFiles import DataFiles
# sort helping
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.co... | 0.27513 | 0.292987 |
import os
import requests
from requests.auth import HTTPBasicAuth
import json
from pprint import pprint
import yaml
def import_variables_from_file():
my_variables_file=open('variables.yml', 'r')
my_variables_in_string=my_variables_file.read()
my_variables_in_yaml=yaml.load(my_variables_in_string)
my_va... | generate_vars_for_jinja_from_netbox.py | import os
import requests
from requests.auth import HTTPBasicAuth
import json
from pprint import pprint
import yaml
def import_variables_from_file():
my_variables_file=open('variables.yml', 'r')
my_variables_in_string=my_variables_file.read()
my_variables_in_yaml=yaml.load(my_variables_in_string)
my_va... | 0.176033 | 0.042068 |
import collections
import pytest
from random import sample
from pymtl import *
from pclib.test import run_test_vector_sim, mk_test_case_table
from RegIncrNstage import RegIncrNstage
#-------------------------------------------------------------------------
# mk_test_vector_table
#-----------------... | asic/designs/examples/regincr/RegIncrNstage_test.py |
import collections
import pytest
from random import sample
from pymtl import *
from pclib.test import run_test_vector_sim, mk_test_case_table
from RegIncrNstage import RegIncrNstage
#-------------------------------------------------------------------------
# mk_test_vector_table
#-----------------... | 0.242026 | 0.468304 |
from __future__ import unicode_literals
import autoslug.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import resources.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(se... | resources/migrations/0001_initial.py | from __future__ import unicode_literals
import autoslug.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import resources.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(se... | 0.535341 | 0.160792 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.excep... | Update Trash/Interpark + telegram.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.excep... | 0.17614 | 0.107813 |
from __future__ import print_function, division
import numpy as np
from PyAstronomy.pyaC import pyaErrors as PE
from .keplerOrbit import KeplerEllipse
from .astroTimeLegacy import helio_jd, daycnv
from . import observatory as pyaobs
from . import eq2hor
from . import sunpos
from . import twilight
from .moonpos import m... | src/pyasl/asl/inTransit.py | from __future__ import print_function, division
import numpy as np
from PyAstronomy.pyaC import pyaErrors as PE
from .keplerOrbit import KeplerEllipse
from .astroTimeLegacy import helio_jd, daycnv
from . import observatory as pyaobs
from . import eq2hor
from . import sunpos
from . import twilight
from .moonpos import m... | 0.923951 | 0.536738 |
import sys
assert sys.version_info >= (3, 5)
import numpy as np
import pathlib
import os
import shutil
import glob
import JSONHelper
import CSVHelper
import csv
import quaternion
from plyfile import (PlyData, PlyElement, make2d, PlyParseError, PlyProperty)
import pywavefront
import argparse
# params
parser = argparse... | referit3d/external_tools/Scan2CAD/Routines/Script/Alignment2Mesh.py | import sys
assert sys.version_info >= (3, 5)
import numpy as np
import pathlib
import os
import shutil
import glob
import JSONHelper
import CSVHelper
import csv
import quaternion
from plyfile import (PlyData, PlyElement, make2d, PlyParseError, PlyProperty)
import pywavefront
import argparse
# params
parser = argparse... | 0.131396 | 0.338323 |
import wikipedia
# python to docx
from docx import Document
def wiki(keyword, lang = "th"):
wikipedia.set_lang(lang)
# summary เอาแค่สรุปบทความ
data = wikipedia.summary(keyword)
# page + content เอาเนื้อหาทั้งหน้าบทความ
data2 = wikipedia.page(keyword)
data2 = data2.content
... | 02_GUIWiki.py | import wikipedia
# python to docx
from docx import Document
def wiki(keyword, lang = "th"):
wikipedia.set_lang(lang)
# summary เอาแค่สรุปบทความ
data = wikipedia.summary(keyword)
# page + content เอาเนื้อหาทั้งหน้าบทความ
data2 = wikipedia.page(keyword)
data2 = data2.content
... | 0.134747 | 0.159479 |
import jsonschema
import logging
import requests
from django.conf import settings
from openldap import schemas
from openldap.decorators import OpenLDAPException
from openldap.util import decode_response
logger = logging.getLogger('openldap')
@OpenLDAPException(logger)
def list_users():
"""
List all users.
... | openldap/user_api.py | import jsonschema
import logging
import requests
from django.conf import settings
from openldap import schemas
from openldap.decorators import OpenLDAPException
from openldap.util import decode_response
logger = logging.getLogger('openldap')
@OpenLDAPException(logger)
def list_users():
"""
List all users.
... | 0.633183 | 0.068195 |
from abc import ABC, abstractmethod
from bs4 import BeautifulSoup as bs
import FinanceDataReader as fdr
import finnhub
import pandas as pd
import pyqtgraph as pg
import requests
import yaml
from pyqt.date import get_timestamp
from pyqt.date import get_n_days_ago
from pyqt.util import resource_path
class Stock(ABC):
... | pyqt/stock.py | from abc import ABC, abstractmethod
from bs4 import BeautifulSoup as bs
import FinanceDataReader as fdr
import finnhub
import pandas as pd
import pyqtgraph as pg
import requests
import yaml
from pyqt.date import get_timestamp
from pyqt.date import get_n_days_ago
from pyqt.util import resource_path
class Stock(ABC):
... | 0.576304 | 0.162115 |
import os
import io
import sqlite3
import random
import datetime
import names # gera nomes randomicos
import rstr # gera strings randomicas
from decimal import Decimal
from gen_random_values import gen_doc, gen_ncm, gen_phone, gen_decimal, gen_ipi, gen_timestamp
qcustomers = 60
qsellers = 20
qproducts = 1645 #... | fixtures/manager_db.py | import os
import io
import sqlite3
import random
import datetime
import names # gera nomes randomicos
import rstr # gera strings randomicas
from decimal import Decimal
from gen_random_values import gen_doc, gen_ncm, gen_phone, gen_decimal, gen_ipi, gen_timestamp
qcustomers = 60
qsellers = 20
qproducts = 1645 #... | 0.277767 | 0.089375 |
from . import constraint
from typing import List
class CartesianProduct(constraint.Constraint):
def __init__(self, segments: List[int], constraints: List[constraint.Constraint]):
"""
Construct a Cartesian product of constraints by providing a list of sets
and their dimensions as follows: ... | open-codegen/opengen/constraints/cartesian.py | from . import constraint
from typing import List
class CartesianProduct(constraint.Constraint):
def __init__(self, segments: List[int], constraints: List[constraint.Constraint]):
"""
Construct a Cartesian product of constraints by providing a list of sets
and their dimensions as follows: ... | 0.934028 | 0.812533 |
from openpyxl.worksheet.worksheet import Worksheet
from typing import Any, Dict, List, Optional
from dapodik import Dapodik, __semester__
from dapodik.peserta_didik import PesertaDidik, PesertaDidikLongitudinal
from . import ALL_DATA_INDIVIDU, DATA_LONGITUDINAL
from dapodix.utils import get_workbook, snake_to_title
... | dapodix/peserta_didik/eksport.py | from openpyxl.worksheet.worksheet import Worksheet
from typing import Any, Dict, List, Optional
from dapodik import Dapodik, __semester__
from dapodik.peserta_didik import PesertaDidik, PesertaDidikLongitudinal
from . import ALL_DATA_INDIVIDU, DATA_LONGITUDINAL
from dapodix.utils import get_workbook, snake_to_title
... | 0.640186 | 0.170473 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
class plainArch(nn.Module):
def __init__(self):
super(plainArch, self).__init__()
self.conv01 = nn.Conv2d(3, 16, 3, bias=False, padding=1)
self.batch01 = nn.BatchNorm2d(num_features=... | pyTorchChitra/cnnModels/vanillaCNN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
class plainArch(nn.Module):
def __init__(self):
super(plainArch, self).__init__()
self.conv01 = nn.Conv2d(3, 16, 3, bias=False, padding=1)
self.batch01 = nn.BatchNorm2d(num_features=... | 0.932507 | 0.52007 |
import os, cv2, torch
import numpy as np
from data_loader import transforms
mean = np.array([0.485, 0.456, 0.406])[None,None,:]
std = np.array([0.229, 0.224, 0.225])[None,None,:]
def preprocessing(image, expected_size=320, pad_value=0):
image, pad_up, pad_left, h_new, w_new = transforms.resize_image(image, expected_... | utils/utils.py | import os, cv2, torch
import numpy as np
from data_loader import transforms
mean = np.array([0.485, 0.456, 0.406])[None,None,:]
std = np.array([0.229, 0.224, 0.225])[None,None,:]
def preprocessing(image, expected_size=320, pad_value=0):
image, pad_up, pad_left, h_new, w_new = transforms.resize_image(image, expected_... | 0.708414 | 0.536131 |
import logging
import os
import pickle
import json
import re
from nltk.util import ngrams
from nltk.corpus import stopwords
from collections import Counter
from tqdm import tqdm
import spacy
from wiktionary.ckbc_triple_scorer import CkbcTripleScorer
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(_... | wiktionary/triple_pos_tag_analyzer.py | import logging
import os
import pickle
import json
import re
from nltk.util import ngrams
from nltk.corpus import stopwords
from collections import Counter
from tqdm import tqdm
import spacy
from wiktionary.ckbc_triple_scorer import CkbcTripleScorer
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(_... | 0.414662 | 0.154823 |
import sys
import xml.etree.ElementTree as ET
from copy import deepcopy
def print_comment(s, multiline=False):
if not multiline:
print('/*', s.strip(), '*/')
return
print('/*')
for line in s.splitlines():
print(' *', line.strip())
print(' */')
def objc_case(name, first_capital... | gen.py |
import sys
import xml.etree.ElementTree as ET
from copy import deepcopy
def print_comment(s, multiline=False):
if not multiline:
print('/*', s.strip(), '*/')
return
print('/*')
for line in s.splitlines():
print(' *', line.strip())
print(' */')
def objc_case(name, first_capital... | 0.282196 | 0.156105 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import os
import hashlib
import datetime
from binascii import hexlify, unhexlify
try:
ModuleNotFoundError
except:
ModuleNotFoundError = ImportError
try:
from .hexhashes import *
from .base58 import *
from .miscfuncs im... | simplebitcoinfuncs/electrum1.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import os
import hashlib
import datetime
from binascii import hexlify, unhexlify
try:
ModuleNotFoundError
except:
ModuleNotFoundError = ImportError
try:
from .hexhashes import *
from .base58 import *
from .miscfuncs im... | 0.296349 | 0.196017 |
import copy
import torch
import torch.nn as nn
import torchvision.models as pytorch_models
import sys
import os
sys.path.append('/home/cnris/tailpose/sg/sg2im/vqa/external/pretrainedmodels')
import vqa.external.pretrainedmodels as torch7_models
pytorch_resnet_names = sorted(name for name in pytorch_models.__dict__
... | vqa/models/convnets.py | import copy
import torch
import torch.nn as nn
import torchvision.models as pytorch_models
import sys
import os
sys.path.append('/home/cnris/tailpose/sg/sg2im/vqa/external/pretrainedmodels')
import vqa.external.pretrainedmodels as torch7_models
pytorch_resnet_names = sorted(name for name in pytorch_models.__dict__
... | 0.670285 | 0.306787 |
import collections.abc
from types import SimpleNamespace, MappingProxyType
class _BaseSimpleNamespace(SimpleNamespace):
# Common methods for record and namespace
__slots__ = ()
_meta = property(lambda self: Meta(self))
def __repr__(self):
items = sorted(self.__dict__.items(), key=lambda x: x... | sidekick-types/sidekick/types/anonymous_record.py | import collections.abc
from types import SimpleNamespace, MappingProxyType
class _BaseSimpleNamespace(SimpleNamespace):
# Common methods for record and namespace
__slots__ = ()
_meta = property(lambda self: Meta(self))
def __repr__(self):
items = sorted(self.__dict__.items(), key=lambda x: x... | 0.703651 | 0.147126 |
import os
import re
import json
import yaml
import phiera
from pterradactyl.config import Config
from pterradactyl.util import merge_dict, lookup
# XXX - this class is too "clever" for its own good. it's hard to follow.
class TerraformConfig(object):
alias_syntax = re.compile(r'(\S+) as (\S+)')
properties =... | pterradactyl/terraform/config.py | import os
import re
import json
import yaml
import phiera
from pterradactyl.config import Config
from pterradactyl.util import merge_dict, lookup
# XXX - this class is too "clever" for its own good. it's hard to follow.
class TerraformConfig(object):
alias_syntax = re.compile(r'(\S+) as (\S+)')
properties =... | 0.245356 | 0.13969 |
import argparse
import torch
from omegaconf import OmegaConf
import copy
from typing import Union
# TODO: Fix the import to be more clean !
import sys
import os
path = os.path.realpath(os.path.join(os.getcwd(), ".."))
sys.path.append(path)
from online_attacks.classifiers.dataset import DatasetType
from online_attack... | online_attacks/scripts/train_classifiers.py |
import argparse
import torch
from omegaconf import OmegaConf
import copy
from typing import Union
# TODO: Fix the import to be more clean !
import sys
import os
path = os.path.realpath(os.path.join(os.getcwd(), ".."))
sys.path.append(path)
from online_attacks.classifiers.dataset import DatasetType
from online_attack... | 0.42179 | 0.218899 |
"""Non-maximum suppression operator"""
import tvm
from tvm import api
def nms_ir(data, sort_result, valid_count, out, nms_threshold, force_suppress, nms_topk):
"""Low level IR routing for transform location in multibox_detection operator.
Parameters
----------
data: Buffer
Buffer of output bo... | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/python/topi/vision/nms.py | """Non-maximum suppression operator"""
import tvm
from tvm import api
def nms_ir(data, sort_result, valid_count, out, nms_threshold, force_suppress, nms_topk):
"""Low level IR routing for transform location in multibox_detection operator.
Parameters
----------
data: Buffer
Buffer of output bo... | 0.90921 | 0.430327 |
import shutil
import tempfile
try:
from cStringIO import StringIO as IOStream
except ModuleNotFoundError:
from io import BytesIO as IOStream
from django.test import TestCase
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test.client import Client
fr... | spotseeker_server/test/item/image_thumbnail.py |
import shutil
import tempfile
try:
from cStringIO import StringIO as IOStream
except ModuleNotFoundError:
from io import BytesIO as IOStream
from django.test import TestCase
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test.client import Client
fr... | 0.55929 | 0.166675 |