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 |
|---|---|---|---|---|
numeros = {1,2,3,4,5,6,7,8,9,10}
numeros.update([11])
#print(numeros)
#lista com numeros repetidos, pode ser usado o set para retirar numeros repetidos
# numbers = [1,1,2,3,4,2,3,4,5,6,7,8,9]
# print(numbers)
# numbers = set(numbers)
# print(numbers)
# numbers = list(numbers)
# print(numbers)
a1 = {1,2,3,4}
a2 = {3,... | secao03/set.py | numeros = {1,2,3,4,5,6,7,8,9,10}
numeros.update([11])
#print(numeros)
#lista com numeros repetidos, pode ser usado o set para retirar numeros repetidos
# numbers = [1,1,2,3,4,2,3,4,5,6,7,8,9]
# print(numbers)
# numbers = set(numbers)
# print(numbers)
# numbers = list(numbers)
# print(numbers)
a1 = {1,2,3,4}
a2 = {3,... | 0.149562 | 0.405566 |
import ipywidgets as widgets
import pandas
import logging
import ipyaggrid
from Bio import SeqIO
from io import StringIO
import re
import json
from IPython.display import IFrame, clear_output, Image
from GenDBScraper.PseudomonasDotComScraper import PseudomonasDotComScraper, pdc_query
from GenDBScraper.StringDBScrape... | GenDBScraper/Utilities/nb_utilities.py | import ipywidgets as widgets
import pandas
import logging
import ipyaggrid
from Bio import SeqIO
from io import StringIO
import re
import json
from IPython.display import IFrame, clear_output, Image
from GenDBScraper.PseudomonasDotComScraper import PseudomonasDotComScraper, pdc_query
from GenDBScraper.StringDBScrape... | 0.344664 | 0.172294 |
import numpy as np
from numba import njit, guvectorize
@guvectorize(['void(float64[:], float64[:], float64[:], float64[:])'], '(n),(nq),(n)->(nq)')
def interpolate_y(x, xq, y, yq):
"""Efficient linear interpolation exploiting monotonicity.
Complexity O(n+nq), so most efficient when x and xq have comparable n... | src/sequence_jacobian/utilities/interpolate.py | import numpy as np
from numba import njit, guvectorize
@guvectorize(['void(float64[:], float64[:], float64[:], float64[:])'], '(n),(nq),(n)->(nq)')
def interpolate_y(x, xq, y, yq):
"""Efficient linear interpolation exploiting monotonicity.
Complexity O(n+nq), so most efficient when x and xq have comparable n... | 0.871324 | 0.79049 |
import asyncio, traceback
import anyio
from typing import Dict
from ircstates.server import ServerDisconnectedException
from .server import ConnectionParams, Server
from .transport import TCPTransport
from .interface import IBot, IServer, ITCPTransport
class Bot(IBot):
def __init__(self):
self.servers... | ircrobots/bot.py | import asyncio, traceback
import anyio
from typing import Dict
from ircstates.server import ServerDisconnectedException
from .server import ConnectionParams, Server
from .transport import TCPTransport
from .interface import IBot, IServer, ITCPTransport
class Bot(IBot):
def __init__(self):
self.servers... | 0.433382 | 0.06832 |
import os
import yaml
import boto3
import tempfile
import subprocess
from subprocess import check_call
from matplotlib.cm import get_cmap
from os.path import join as pjoin, basename
"""
S3 related code: https://alexwlchan.net/2019/07/listing-s3-keys/
"""
def get_matching_s3_objects(bucket, prefix="", suffix=""):
... | planet/convert_cog.py | import os
import yaml
import boto3
import tempfile
import subprocess
from subprocess import check_call
from matplotlib.cm import get_cmap
from os.path import join as pjoin, basename
"""
S3 related code: https://alexwlchan.net/2019/07/listing-s3-keys/
"""
def get_matching_s3_objects(bucket, prefix="", suffix=""):
... | 0.554953 | 0.249939 |
from __future__ import print_function
import datetime
import json
import os
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.web import static
from twisted.web.resource import Resource, ErrorPage
from twisted.web.server import NOT_DONE_YET, Site
from genshi.template import... | spinoff/contrib/monitoring/http.py | from __future__ import print_function
import datetime
import json
import os
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.web import static
from twisted.web.resource import Resource, ErrorPage
from twisted.web.server import NOT_DONE_YET, Site
from genshi.template import... | 0.526586 | 0.060197 |
import imaplib
import os
import ssl
import sys
VALID_OPTIONS = ["--use-config-file", "--save-messages"]
CONFIG_FILE_NAME = "config.txt"
IMAP_SERVER = "imap.gmail.com"
PORT = "993"
def search(email_address, password, search_str, mailbox="inbox"):
imap4ssl = setup(email_address, password, mailbox)
message_ids =... | gmail_search.py | import imaplib
import os
import ssl
import sys
VALID_OPTIONS = ["--use-config-file", "--save-messages"]
CONFIG_FILE_NAME = "config.txt"
IMAP_SERVER = "imap.gmail.com"
PORT = "993"
def search(email_address, password, search_str, mailbox="inbox"):
imap4ssl = setup(email_address, password, mailbox)
message_ids =... | 0.097037 | 0.074131 |
import numpy
def createDictionary(n):
dict = {}
parole = getWords()
for i in range(len(parole)): #ciclo su tutte le parole del lessico
for j in range(len(parole[i]) - n + 1): #ciclo per spezzettare le parole in trigrammi
current = parole[i][j:j + n]
if dict.get(curre... | backend/crnn.pytorch-master/editDistance.py | import numpy
def createDictionary(n):
dict = {}
parole = getWords()
for i in range(len(parole)): #ciclo su tutte le parole del lessico
for j in range(len(parole[i]) - n + 1): #ciclo per spezzettare le parole in trigrammi
current = parole[i][j:j + n]
if dict.get(curre... | 0.036917 | 0.311885 |
from django.conf.urls import url, re_path
from django.urls import path, include
from rest_framework import routers
from rest_framework.routers import SimpleRouter, DefaultRouter, Route, DynamicRoute
from odata.views import ProductViewSet, CustomerViewSet, CategoryViewSet, ShipperViewSet
from odata.views import OrderVi... | odata/urls.py | from django.conf.urls import url, re_path
from django.urls import path, include
from rest_framework import routers
from rest_framework.routers import SimpleRouter, DefaultRouter, Route, DynamicRoute
from odata.views import ProductViewSet, CustomerViewSet, CategoryViewSet, ShipperViewSet
from odata.views import OrderVi... | 0.336113 | 0.133868 |
from datetime import datetime
import numpy as np
from algorithm.base import Algorithm
class Dynamic(Algorithm):
def __init__(self, knapsack):
assert type(knapsack) == dict
self.profits = knapsack['profits']
self.weights = knapsack['weights']
self.n_items = len(knapsack['weights']... | algorithm/dynamic.py | from datetime import datetime
import numpy as np
from algorithm.base import Algorithm
class Dynamic(Algorithm):
def __init__(self, knapsack):
assert type(knapsack) == dict
self.profits = knapsack['profits']
self.weights = knapsack['weights']
self.n_items = len(knapsack['weights']... | 0.763131 | 0.387401 |
import torch, os
import numpy as np
def randint(max_val, num_samples):
rand_vals = {}
_num_samples = min(max_val, num_samples)
while True:
_rand_vals = np.random.randint(0, max_val, num_samples)
for r in _rand_vals:
rand_vals[r] = r
if len(rand_vals) >= _num_samples... | vqa_experiments/data_utils.py | import torch, os
import numpy as np
def randint(max_val, num_samples):
rand_vals = {}
_num_samples = min(max_val, num_samples)
while True:
_rand_vals = np.random.randint(0, max_val, num_samples)
for r in _rand_vals:
rand_vals[r] = r
if len(rand_vals) >= _num_samples... | 0.623606 | 0.53437 |
import os
from automechanic_old import pchemkin
PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(PATH, 'data')
def test__reactions():
""" test pchemkin.reactions
"""
mech_fpath = os.path.join(DATA_PATH, 'heptane_mechanism.txt')
mech_str = open(mech_fpath).read()
reacs =... | tests/test_automechanic_old/test_pchemkin.py | import os
from automechanic_old import pchemkin
PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(PATH, 'data')
def test__reactions():
""" test pchemkin.reactions
"""
mech_fpath = os.path.join(DATA_PATH, 'heptane_mechanism.txt')
mech_str = open(mech_fpath).read()
reacs =... | 0.33764 | 0.32705 |
import os
import json
import unittest
# compatible python3
import sys
from urllib.parse import parse_qsl
from poaurk import PlurkAPI, PlurkOAuth
class Test0ConsumerTokenSecret(unittest.TestCase):
def setUp(self):
pass
def teardown(self):
pass
def test_no_consumer_key(self):
with... | tests/api_test.py | import os
import json
import unittest
# compatible python3
import sys
from urllib.parse import parse_qsl
from poaurk import PlurkAPI, PlurkOAuth
class Test0ConsumerTokenSecret(unittest.TestCase):
def setUp(self):
pass
def teardown(self):
pass
def test_no_consumer_key(self):
with... | 0.363986 | 0.127761 |
from __future__ import division
from builtins import range
import numpy as np
from numpy.testing import TestCase, assert_almost_equal, run_module_suite
from scikits.fitting import (Spline1DFit, Spline2DScatterFit, Spline2DGridFit,
NotFittedError)
class TestSpline1DFit(TestCase):
"""... | scikits/fitting/tests/test_spline.py | from __future__ import division
from builtins import range
import numpy as np
from numpy.testing import TestCase, assert_almost_equal, run_module_suite
from scikits.fitting import (Spline1DFit, Spline2DScatterFit, Spline2DGridFit,
NotFittedError)
class TestSpline1DFit(TestCase):
"""... | 0.883009 | 0.702243 |
def find_index(nodes, x, y):
for index, item in enumerate(nodes):
if item["coord"][0] == x and item["coord"][1] == y:
return index
return -1
def tile_input(risk_nodes, x=5, y=5):
tiled = tile_x(risk_nodes, x)
tiled = tile_x([list(x) for x in zip(*tiled)], y)
return [list(x) for... | 15/script2.py | def find_index(nodes, x, y):
for index, item in enumerate(nodes):
if item["coord"][0] == x and item["coord"][1] == y:
return index
return -1
def tile_input(risk_nodes, x=5, y=5):
tiled = tile_x(risk_nodes, x)
tiled = tile_x([list(x) for x in zip(*tiled)], y)
return [list(x) for... | 0.188997 | 0.625981 |
from __future__ import unicode_literals
import requests
from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from solo.models import SingletonModel
from django_datajsonar.models import AbstractTask
class Query(models.Model):
"""Registro de queries exit... | series_tiempo_ar_api/apps/analytics/models.py | from __future__ import unicode_literals
import requests
from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from solo.models import SingletonModel
from django_datajsonar.models import AbstractTask
class Query(models.Model):
"""Registro de queries exit... | 0.602763 | 0.101991 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['OutputSynapseArgs', 'OutputSynapse']
@pulumi.input_type
class OutputSynapseArgs:
def __init__(__self__, *,
database: pulumi.Input[str],
... | sdk/python/pulumi_azure/streamanalytics/output_synapse.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['OutputSynapseArgs', 'OutputSynapse']
@pulumi.input_type
class OutputSynapseArgs:
def __init__(__self__, *,
database: pulumi.Input[str],
... | 0.868116 | 0.069415 |
import glob
import os
import random
import PIL
import numpy as np
from PIL import Image
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
from AttackAlgorithms.AttackModels import AttackModels
from Batch.BatchItem import BatchItem
class Batcher():
_pathToOtherClas... | Batch/BatchManager.py | import glob
import os
import random
import PIL
import numpy as np
from PIL import Image
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
from AttackAlgorithms.AttackModels import AttackModels
from Batch.BatchItem import BatchItem
class Batcher():
_pathToOtherClas... | 0.676727 | 0.132346 |
import os
import sys
import time
import requests
import json
import gzip
import shutil
import math
# Invoke the data_exports API to request an asset export.
def request_asset_exports(api_key, base_url):
url = base_url + "/data_exports"
headers = {'Accept': 'application/json',
'Content-Type': 'a... | python/vulns_per_assets/export_asset_vulns.py |
import os
import sys
import time
import requests
import json
import gzip
import shutil
import math
# Invoke the data_exports API to request an asset export.
def request_asset_exports(api_key, base_url):
url = base_url + "/data_exports"
headers = {'Accept': 'application/json',
'Content-Type': 'a... | 0.323487 | 0.124505 |
import logging
import collections
try:
import collections.abc
Mapping = collections.abc.Mapping
except ImportError:
Mapping = collections.Mapping
from ..pair_tabulation import DLPoly_PairTabulation, LAMMPS_PairTabulation, GULP_PairTabulation, Excel_PairTabulation
from ..eam_tabulation import SetFL_EAMTabulati... | atsim/potentials/config/_tabulation_factories.py | import logging
import collections
try:
import collections.abc
Mapping = collections.abc.Mapping
except ImportError:
Mapping = collections.Mapping
from ..pair_tabulation import DLPoly_PairTabulation, LAMMPS_PairTabulation, GULP_PairTabulation, Excel_PairTabulation
from ..eam_tabulation import SetFL_EAMTabulati... | 0.766818 | 0.315413 |
import json
import os
from copy import deepcopy
import pytest
from rios.core.validation.assessment import Assessment, ValidationError
from utils import *
GOOD_ASSESSMENT_FILES = os.path.join(EXAMPLE_FILES, 'assessments/good')
@pytest.mark.parametrize('filename', get_example_files(GOOD_ASSESSMENT_FILES))
def tes... | tests/test_assessment_validation.py |
import json
import os
from copy import deepcopy
import pytest
from rios.core.validation.assessment import Assessment, ValidationError
from utils import *
GOOD_ASSESSMENT_FILES = os.path.join(EXAMPLE_FILES, 'assessments/good')
@pytest.mark.parametrize('filename', get_example_files(GOOD_ASSESSMENT_FILES))
def tes... | 0.297266 | 0.342462 |
from __future__ import print_function
import itertools as it, operator as op, functools as ft
import struct
from unified2._format import pkt_header, pkt_types, pkt_tails
class Parser(object):
def __init__(self):
self.data_fmts = dict(header=self.struct(pkt_header))
self.data_fmts.update((k, map(self.struct, v... | unified2/parser.py | from __future__ import print_function
import itertools as it, operator as op, functools as ft
import struct
from unified2._format import pkt_header, pkt_types, pkt_tails
class Parser(object):
def __init__(self):
self.data_fmts = dict(header=self.struct(pkt_header))
self.data_fmts.update((k, map(self.struct, v... | 0.36693 | 0.181372 |
import sys
import os
from pathlib import Path
from bookworm import typehints as t
from bookworm import app
from bookworm.i18n import LocaleInfo
from bookworm.paths import data_path
from bookworm.ocr_engines import OcrRequest, OcrResult, BaseOcrEngine
from bookworm.logger import logger
from . import pytesseract
log =... | bookworm/ocr_engines/tesseract_ocr_engine/__init__.py |
import sys
import os
from pathlib import Path
from bookworm import typehints as t
from bookworm import app
from bookworm.i18n import LocaleInfo
from bookworm.paths import data_path
from bookworm.ocr_engines import OcrRequest, OcrResult, BaseOcrEngine
from bookworm.logger import logger
from . import pytesseract
log =... | 0.331661 | 0.180107 |
from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from .base import BaseTask
from ..encryption import EncryptionService
from ..exception import CryptographyKeysAlreadyCreated
class CryptographyKeysSetupTask(BaseTask):
"""Generates OpenGPG keys required for encryption.
Takes Bac... | bahub/bahub/tasks/cryptsetup.py | from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from .base import BaseTask
from ..encryption import EncryptionService
from ..exception import CryptographyKeysAlreadyCreated
class CryptographyKeysSetupTask(BaseTask):
"""Generates OpenGPG keys required for encryption.
Takes Bac... | 0.647798 | 0.191026 |
import os
import re
import logging
import pickle
import dotenv
import praw
# Relevant directories
SRC_DIR = os.path.dirname(__file__)
RESOURCES_DIR = os.path.join(SRC_DIR, "resources.d")
PROJECT_DIR = os.path.realpath(os.path.join(SRC_DIR, ".."))
# Logging
LOGFILE_PATH = os.path.join(PROJECT_DIR, "nbviewerbot.log")... | nbviewerbot/resources.py |
import os
import re
import logging
import pickle
import dotenv
import praw
# Relevant directories
SRC_DIR = os.path.dirname(__file__)
RESOURCES_DIR = os.path.join(SRC_DIR, "resources.d")
PROJECT_DIR = os.path.realpath(os.path.join(SRC_DIR, ".."))
# Logging
LOGFILE_PATH = os.path.join(PROJECT_DIR, "nbviewerbot.log")... | 0.29798 | 0.10732 |
from apgl.io.GraphReader import GraphReader
from apgl.graph.VertexList import VertexList
from apgl.graph.SparseGraph import SparseGraph
import logging
class SimpleGraphReader(GraphReader):
'''
A class to read SimpleGraph files.
'''
def __init__(self):
pass
def read... | apgl/io/SimpleGraphReader.py | from apgl.io.GraphReader import GraphReader
from apgl.graph.VertexList import VertexList
from apgl.graph.SparseGraph import SparseGraph
import logging
class SimpleGraphReader(GraphReader):
'''
A class to read SimpleGraph files.
'''
def __init__(self):
pass
def read... | 0.449876 | 0.277439 |
import os, sys, os.path
from collections import defaultdict
from pixelterm.xtermcolors import xterm_colors
from PIL import Image, PngImagePlugin
try:
import re2 as re
except:
import re
def parse_escape_sequence(seq):
codes = list(map(int, seq[2:-1].split(';')))
fg, bg = None, None
i = 0
while i<len(codes):
if... | pixelterm/unpixelterm.py |
import os, sys, os.path
from collections import defaultdict
from pixelterm.xtermcolors import xterm_colors
from PIL import Image, PngImagePlugin
try:
import re2 as re
except:
import re
def parse_escape_sequence(seq):
codes = list(map(int, seq[2:-1].split(';')))
fg, bg = None, None
i = 0
while i<len(codes):
if... | 0.102462 | 0.186947 |
import base64
import os
import json
import time
import cv2
import matplotlib.patches as patches
from matplotlib import pyplot as plt
import requests
class FaceCompareSimulator(object):
def __init__(self, face_compare_pairs_root_dir):
self._face_compare_url = "https://facecomp.gaowexu.solutions.aws.a2z.org... | source/simulate/face_compare.py | import base64
import os
import json
import time
import cv2
import matplotlib.patches as patches
from matplotlib import pyplot as plt
import requests
class FaceCompareSimulator(object):
def __init__(self, face_compare_pairs_root_dir):
self._face_compare_url = "https://facecomp.gaowexu.solutions.aws.a2z.org... | 0.531209 | 0.288031 |
import torch.nn as nn
import torch
from functools import partial
import losses
from math import ceil
import math
import numpy as np
def optimize(net, optimizer, batch, add_repulsive_constraint=False, **kwargs):
criterion = nn.CrossEntropyLoss()
if add_repulsive_constraint:
criterion_repulsive = losse... | classification/tools.py | import torch.nn as nn
import torch
from functools import partial
import losses
from math import ceil
import math
import numpy as np
def optimize(net, optimizer, batch, add_repulsive_constraint=False, **kwargs):
criterion = nn.CrossEntropyLoss()
if add_repulsive_constraint:
criterion_repulsive = losse... | 0.794943 | 0.286784 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import outputs
__all__ = [
'GetMonitorResult',
'AwaitableGetMonitorResult',
'get_monitor',
'get_monitor_output',
]
@pulumi.output_type
class GetMoni... | sdk/python/pulumi_datadog/get_monitor.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import outputs
__all__ = [
'GetMonitorResult',
'AwaitableGetMonitorResult',
'get_monitor',
'get_monitor_output',
]
@pulumi.output_type
class GetMoni... | 0.790166 | 0.07267 |
from .resource import Resource
class ManagedHostingEnvironment(Resource):
"""Description of a managed hosting environment.
:param id: Resource Id
:type id: str
:param name: Resource Name
:type name: str
:param kind: Kind of resource
:type kind: str
:param location: Resource Location
... | azure-mgmt-web/azure/mgmt/web/models/managed_hosting_environment.py |
from .resource import Resource
class ManagedHostingEnvironment(Resource):
"""Description of a managed hosting environment.
:param id: Resource Id
:type id: str
:param name: Resource Name
:type name: str
:param kind: Kind of resource
:type kind: str
:param location: Resource Location
... | 0.851845 | 0.338446 |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from ..TLineBu.ABuTLine import AbuTLine
from ..CoreBu.ABuPdHelper import pd_rolling_std, pd_ewm_mean, pd_ewm_std, pd_resample
from ..UtilB... | abupy/TLineBu/ABuTLWave.py | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from ..TLineBu.ABuTLine import AbuTLine
from ..CoreBu.ABuPdHelper import pd_rolling_std, pd_ewm_mean, pd_ewm_std, pd_resample
from ..UtilB... | 0.277375 | 0.247953 |
# Imports
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Python:
from string import Template
from typing import Match, List, Callable
from json import dumps
from datetime import datetime
import re
# 3rd party:
# Internal:
from .exceptions import InvalidStructureParameter,... | lookup_api_v1/engine/structure.py | # Imports
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Python:
from string import Template
from typing import Match, List, Callable
from json import dumps
from datetime import datetime
import re
# 3rd party:
# Internal:
from .exceptions import InvalidStructureParameter,... | 0.863909 | 0.239116 |
import os
import pickle
import random
import itertools
import numpy as np
import networkx as nx
def load_data(dataset):
'''
dataset: name of dataset
test_proportion: ratio of test train split
seed: random seed for random splitting of dataset
'''
print('loading data')
g_list = ... | load_graph.py | import os
import pickle
import random
import itertools
import numpy as np
import networkx as nx
def load_data(dataset):
'''
dataset: name of dataset
test_proportion: ratio of test train split
seed: random seed for random splitting of dataset
'''
print('loading data')
g_list = ... | 0.142381 | 0.305626 |
from datetime import datetime
from flexmock import flexmock
from mock import PropertyMock
from pyquery import PyQuery as pq
from sportsreference import utils
from sportsreference.constants import (AWAY,
CONFERENCE_TOURNAMENT,
HOME,
... | tests/unit/test_ncaab_schedule.py | from datetime import datetime
from flexmock import flexmock
from mock import PropertyMock
from pyquery import PyQuery as pq
from sportsreference import utils
from sportsreference.constants import (AWAY,
CONFERENCE_TOURNAMENT,
HOME,
... | 0.824179 | 0.318373 |
"""Configuration dataloader module."""
from collections import OrderedDict
from typing import Any, Dict, Optional
from lpot.ux.utils.exceptions import ClientErrorException
from lpot.ux.utils.json_serializer import JsonSerializer
class Dataset(JsonSerializer):
"""Configuration Dataset class."""
def __init__... | lpot/ux/utils/workload/dataloader.py | """Configuration dataloader module."""
from collections import OrderedDict
from typing import Any, Dict, Optional
from lpot.ux.utils.exceptions import ClientErrorException
from lpot.ux.utils.json_serializer import JsonSerializer
class Dataset(JsonSerializer):
"""Configuration Dataset class."""
def __init__... | 0.952959 | 0.300268 |
intent='x'
if intent=='for_loop':
to_send = """for(int x=a;x<b;x++) {
<code>;
}"""
elif intent=='print':
to_send = """cout<<'Enter your string here !<<endl;' """
elif intent=='nested_for':
to_send = """for(int x=a;x<b;x++) {
for(int y=c;y,d;y++) {
... | akshat.py | intent='x'
if intent=='for_loop':
to_send = """for(int x=a;x<b;x++) {
<code>;
}"""
elif intent=='print':
to_send = """cout<<'Enter your string here !<<endl;' """
elif intent=='nested_for':
to_send = """for(int x=a;x<b;x++) {
for(int y=c;y,d;y++) {
... | 0.097562 | 0.093761 |
from __future__ import print_function
import numpy as np
from keras.models import Sequential
from keras.layers.recurrent import LSTM
from keras.layers.core import *
from keras.layers.normalization import *
from keras.callbacks import EarlyStopping, History
from keras.layers import TimeDistributed
from keras.models imp... | MusicGeneration/train.py |
from __future__ import print_function
import numpy as np
from keras.models import Sequential
from keras.layers.recurrent import LSTM
from keras.layers.core import *
from keras.layers.normalization import *
from keras.callbacks import EarlyStopping, History
from keras.layers import TimeDistributed
from keras.models imp... | 0.583915 | 0.198122 |
import random
import json
import asyncio
from datetime import datetime
import sqlite3
from contextlib import closing
import re
import discord
from discord.ext import commands, tasks
from discord.utils import get
intents = discord.Intents.default()
intents.members = True
with open("token.0", "r", encoding="utf-8") a... | bot.py | import random
import json
import asyncio
from datetime import datetime
import sqlite3
from contextlib import closing
import re
import discord
from discord.ext import commands, tasks
from discord.utils import get
intents = discord.Intents.default()
intents.members = True
with open("token.0", "r", encoding="utf-8") a... | 0.369543 | 0.348396 |
import os
import unittest
import copy
import warnings
from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor, ExtTestCase
from mlstatpy.graph.graph_distance import GraphDistance
from mlstatpy.graph.graphviz_helper import draw_graph_graphviz
class TestGraphDistance(ExtTestCase):
def test_graph_lo... | _unittests/ut_graph/test_graph_distance.py | import os
import unittest
import copy
import warnings
from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor, ExtTestCase
from mlstatpy.graph.graph_distance import GraphDistance
from mlstatpy.graph.graphviz_helper import draw_graph_graphviz
class TestGraphDistance(ExtTestCase):
def test_graph_lo... | 0.443118 | 0.572125 |
import logging
import os.path
from datetime import timedelta
from os import walk
from random import random
from re import search
from string import letters
from yaml import safe_load
from coyote.utils.scheduler import schedule
# steal celery's log format, but change name for distinction in messages
logging.basicCon... | coyote/utils/conf_builder.py | import logging
import os.path
from datetime import timedelta
from os import walk
from random import random
from re import search
from string import letters
from yaml import safe_load
from coyote.utils.scheduler import schedule
# steal celery's log format, but change name for distinction in messages
logging.basicCon... | 0.302391 | 0.095307 |
from azure.cli.core.commands import CliCommandType
def load_command_table(self, _):
from azext_resource_mover.generated._client_factory import cf_move_collection
resource_mover_move_collection = CliCommandType(
operations_tmpl='azext_resource_mover.vendored_sdks.resourcemover.operations._move_collec... | src/resource-mover/azext_resource_mover/generated/commands.py |
from azure.cli.core.commands import CliCommandType
def load_command_table(self, _):
from azext_resource_mover.generated._client_factory import cf_move_collection
resource_mover_move_collection = CliCommandType(
operations_tmpl='azext_resource_mover.vendored_sdks.resourcemover.operations._move_collec... | 0.472927 | 0.056392 |
import pytest
import pandabase as pb
from pandabase.helpers import *
import pytz
UTC = pytz.utc
LA_TZ = pytz.timezone('America/Los_Angeles') # test timezone
bad_df = pd.DataFrame(index=[2, 2], data=['x', 'y'])
bad_df.index.name = 'bad_index'
bad_df2 = pd.DataFrame(index=[1, None], columns=['a'], data=['x', 'y'])
... | tests/test_pandabase_util.py | import pytest
import pandabase as pb
from pandabase.helpers import *
import pytz
UTC = pytz.utc
LA_TZ = pytz.timezone('America/Los_Angeles') # test timezone
bad_df = pd.DataFrame(index=[2, 2], data=['x', 'y'])
bad_df.index.name = 'bad_index'
bad_df2 = pd.DataFrame(index=[1, None], columns=['a'], data=['x', 'y'])
... | 0.444806 | 0.502625 |
import mircx_pipeline as mrx
import argparse
import glob
import os
from astropy.io import fits as fits
from mircx_pipeline import log;
# Describe the script
description = \
"""
description:
Modify the value a KEYWORD in the FITS main header of MIRCX files. It works
both with compressed (*.fits.fz) and uncompres... | bin/mircx_modify_keyword.py |
import mircx_pipeline as mrx
import argparse
import glob
import os
from astropy.io import fits as fits
from mircx_pipeline import log;
# Describe the script
description = \
"""
description:
Modify the value a KEYWORD in the FITS main header of MIRCX files. It works
both with compressed (*.fits.fz) and uncompres... | 0.460532 | 0.225193 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import User, Category, Item, Base
engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
User1 = User(name = "<NAME>", email = "<EMAIL>... | catalog/lotsofcategories.py | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import User, Category, Item, Base
engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
User1 = User(name = "<NAME>", email = "<EMAIL>... | 0.379838 | 0.179369 |
import subprocess
import math
# This file should be in the MYSTUFF subfolder of Torch-RNN
# The resulting checkpoints will be placed in the checkpoint_name
# subfolder of Torch-RNN folder
# It will run for a while...
# 50 epochs did 106500 iterations
# 1 epoch does 2130 iterations
# 1 iteration is 0.000469483568 epoc... | MYSTUFF/create_checkpoints.py | import subprocess
import math
# This file should be in the MYSTUFF subfolder of Torch-RNN
# The resulting checkpoints will be placed in the checkpoint_name
# subfolder of Torch-RNN folder
# It will run for a while...
# 50 epochs did 106500 iterations
# 1 epoch does 2130 iterations
# 1 iteration is 0.000469483568 epoc... | 0.314471 | 0.224757 |
import tensorflow as tf
class HardNegativeMining(tf.keras.layers.Layer):
"""Hard Negative Mining to keep balanced positive and negative samples.
This layer will keep a balanced positive and negative samples and return
the summed results.
# Attributes:
negative_positive_ratio: An int to repre... | kerascv/layers/losses/hard_neg_miner.py | import tensorflow as tf
class HardNegativeMining(tf.keras.layers.Layer):
"""Hard Negative Mining to keep balanced positive and negative samples.
This layer will keep a balanced positive and negative samples and return
the summed results.
# Attributes:
negative_positive_ratio: An int to repre... | 0.933764 | 0.853303 |
import os
import torch
from torch.utils.tensorboard import SummaryWriter
from models.transition_model import TransitionModel
from data import DataScheduler
def train_model(
config, model: TransitionModel,
scheduler: DataScheduler,
writer: SummaryWriter,
resume_step: int = 0
):
saved_model_path = os.path.join... | train.py | import os
import torch
from torch.utils.tensorboard import SummaryWriter
from models.transition_model import TransitionModel
from data import DataScheduler
def train_model(
config, model: TransitionModel,
scheduler: DataScheduler,
writer: SummaryWriter,
resume_step: int = 0
):
saved_model_path = os.path.join... | 0.469763 | 0.2547 |
import logging
from vnc_api.exceptions import BadRequest
from vnc_api.exceptions import OverQuota
from vnc_api.gen.resource_client import HostBasedService
from vnc_api.gen.resource_client import Project
from vnc_api.gen.resource_client import VirtualNetwork
from vnc_api.gen.resource_xsd import QuotaType
from vnc_api.g... | src/config/api-server/vnc_cfg_api_server/tests/resources/test_host_based_service.py | import logging
from vnc_api.exceptions import BadRequest
from vnc_api.exceptions import OverQuota
from vnc_api.gen.resource_client import HostBasedService
from vnc_api.gen.resource_client import Project
from vnc_api.gen.resource_client import VirtualNetwork
from vnc_api.gen.resource_xsd import QuotaType
from vnc_api.g... | 0.540924 | 0.130175 |
import ui
class UI:
def __init__(self, title, rows=10, cols=10):
self.view = ui.View(frame=(0, 0, 300, 300))
self.view.name = title
self.view.background_color = "white"
self.rows = rows
self.cols = cols
self.w = self.view.frame[2] / cols
self.h = self.view.... | vm/nga-python/UIDevice.py |
import ui
class UI:
def __init__(self, title, rows=10, cols=10):
self.view = ui.View(frame=(0, 0, 300, 300))
self.view.name = title
self.view.background_color = "white"
self.rows = rows
self.cols = cols
self.w = self.view.frame[2] / cols
self.h = self.view.... | 0.480235 | 0.14143 |
import numpy as np
import torch
import torch.nn as nn
from torch import bmm, cat, randn, zeros
from torch.autograd import Variable
import os
from util import load_from_txt
LEN_WAVEFORM = 22050 * 20
local_config = {
'batch_size': 1,
'eps': 1e-5,
'sample_rate': 22050,
'load_size': 22050 * 20,
'name_scope': 'SoundN... | soundnet.py | import numpy as np
import torch
import torch.nn as nn
from torch import bmm, cat, randn, zeros
from torch.autograd import Variable
import os
from util import load_from_txt
LEN_WAVEFORM = 22050 * 20
local_config = {
'batch_size': 1,
'eps': 1e-5,
'sample_rate': 22050,
'load_size': 22050 * 20,
'name_scope': 'SoundN... | 0.92968 | 0.443781 |
import os
from agent import Agent
from config import Config
import random
from replay_buffer import ReplayBuffer
import torch
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
print(torch.__version__)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(torch.cuda.is_available())
clas... | maddpg_agent.py | import os
from agent import Agent
from config import Config
import random
from replay_buffer import ReplayBuffer
import torch
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
print(torch.__version__)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(torch.cuda.is_available())
clas... | 0.425367 | 0.114591 |
try:
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
except ImportError:
raise ImportError("Please install DALI from https://www.github.com/NVIDIA/DALI to run this example.")
# Data Transform class for dali
# this mirrors the whole Albumentation... | data_pipeline/lightning_pipeline.py | try:
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
except ImportError:
raise ImportError("Please install DALI from https://www.github.com/NVIDIA/DALI to run this example.")
# Data Transform class for dali
# this mirrors the whole Albumentation... | 0.54698 | 0.352007 |
from __future__ import annotations
from typing import *
from edb import errors
from edb.edgeql import ast as qlast
from edb.edgeql import compiler as qlcompiler
from edb.edgeql import qltypes
from . import annos as s_anno
from . import delta as sd
from . import expr as s_expr
from . import objects as so
from . imp... | edb/schema/globals.py |
from __future__ import annotations
from typing import *
from edb import errors
from edb.edgeql import ast as qlast
from edb.edgeql import compiler as qlcompiler
from edb.edgeql import qltypes
from . import annos as s_anno
from . import delta as sd
from . import expr as s_expr
from . import objects as so
from . imp... | 0.776284 | 0.211051 |
import torch
from torch import einsum
from torch.nn import Unfold
from torch.nn.functional import conv1d, conv2d, conv3d
from backpack.utils.ein import eingroup
def unfold_func(module):
return Unfold(
kernel_size=module.kernel_size,
dilation=module.dilation,
padding=module.padding,
... | backpack/utils/conv.py | import torch
from torch import einsum
from torch.nn import Unfold
from torch.nn.functional import conv1d, conv2d, conv3d
from backpack.utils.ein import eingroup
def unfold_func(module):
return Unfold(
kernel_size=module.kernel_size,
dilation=module.dilation,
padding=module.padding,
... | 0.882187 | 0.439807 |
import string
import re
import random
import views
READ="r"
WRITE="w"
COMMIT="c"
ABORT="a"
class HistoryItem:
def __init__(self, transaction, operation, data="", index=-1):
self.transaction = transaction
self.operation = operation
self.data=data
self.index=index
def toString(self, html=True):
if self.da... | DBtransactions.py |
import string
import re
import random
import views
READ="r"
WRITE="w"
COMMIT="c"
ABORT="a"
class HistoryItem:
def __init__(self, transaction, operation, data="", index=-1):
self.transaction = transaction
self.operation = operation
self.data=data
self.index=index
def toString(self, html=True):
if self.da... | 0.139367 | 0.141964 |
from __future__ import annotations
from typing import Any, Union
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPExc... | main.py | from __future__ import annotations
from typing import Any, Union
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPExc... | 0.675336 | 0.058078 |
import json
import logging
import socket
import sys
from bs4 import BeautifulSoup
from datetime import date, timedelta
def tag_to_dict(tag_string):
soup = BeautifulSoup(tag_string, "html.parser")
tag = soup.find()
(tag_name, *_) = tag_string.split(maxsplit=1)
tag_name = tag_name[1:]
data = dict()... | util.py | import json
import logging
import socket
import sys
from bs4 import BeautifulSoup
from datetime import date, timedelta
def tag_to_dict(tag_string):
soup = BeautifulSoup(tag_string, "html.parser")
tag = soup.find()
(tag_name, *_) = tag_string.split(maxsplit=1)
tag_name = tag_name[1:]
data = dict()... | 0.289372 | 0.153803 |
import os
import cv2
# 帧转化为对应时间
import config
from app.controller import FileUtil
def frames_to_timecode(framerate, frames):
"""
视频 通过视频帧转换成时间
:param framerate: 视频帧率
:param frames: 当前视频帧数
:return:时间(00:00:01:01)
"""
return '{0:02d}:{1:02d}:{2:02d}:{3:02d}'.format(int(frames / (3600 * fra... | app/controller/algorithms/frequencyKeyFrame.py | import os
import cv2
# 帧转化为对应时间
import config
from app.controller import FileUtil
def frames_to_timecode(framerate, frames):
"""
视频 通过视频帧转换成时间
:param framerate: 视频帧率
:param frames: 当前视频帧数
:return:时间(00:00:01:01)
"""
return '{0:02d}:{1:02d}:{2:02d}:{3:02d}'.format(int(frames / (3600 * fra... | 0.215268 | 0.220605 |
import discord
import logging
import management
import message_util
import os
from datetime import datetime, time, timedelta
from dateutil import tz
from dotenv import load_dotenv
# Set up the environment from `.env`
load_dotenv()
if "DISCORD_BOT_TOKEN" not in os.environ:
raise RuntimeError("DISCORD_BOT_TOKEN mu... | app.py | import discord
import logging
import management
import message_util
import os
from datetime import datetime, time, timedelta
from dateutil import tz
from dotenv import load_dotenv
# Set up the environment from `.env`
load_dotenv()
if "DISCORD_BOT_TOKEN" not in os.environ:
raise RuntimeError("DISCORD_BOT_TOKEN mu... | 0.494141 | 0.076546 |
from faq_bert import FAQ_BERT
from searcher import Searcher
from history_searcher import History_Searcher
class FAQ_BERT_Ranker(object):
""" Class to generate top-k ranked results for a given input query string
:param es: Elasticsearch instance
:param index: Elasticsearch index name
:param top_k:... | faq_bert_ranker.py | from faq_bert import FAQ_BERT
from searcher import Searcher
from history_searcher import History_Searcher
class FAQ_BERT_Ranker(object):
""" Class to generate top-k ranked results for a given input query string
:param es: Elasticsearch instance
:param index: Elasticsearch index name
:param top_k:... | 0.790449 | 0.268099 |
import logging
from pathlib import Path
import numpy as np
from keras import backend as K
from keras.callbacks import Callback, EarlyStopping, CSVLogger, ModelCheckpoint, TensorBoard, LearningRateScheduler
from sklearn.metrics import f1_score, precision_score, recall_score, classification_report, confusion_matrix
imp... | src/commons/callbacks.py | import logging
from pathlib import Path
import numpy as np
from keras import backend as K
from keras.callbacks import Callback, EarlyStopping, CSVLogger, ModelCheckpoint, TensorBoard, LearningRateScheduler
from sklearn.metrics import f1_score, precision_score, recall_score, classification_report, confusion_matrix
imp... | 0.847527 | 0.212293 |
import numpy as np
from tcn import TCN
import tensorflow as tf
import os
def load_inputs(lookback=20,
batch_size=32,
nb_filters=32,
kernel_size=3,
nb_stacks=1,
n_layers=4,
total_epochs=10,
tv=-1,
... | deep_energy_model.py | import numpy as np
from tcn import TCN
import tensorflow as tf
import os
def load_inputs(lookback=20,
batch_size=32,
nb_filters=32,
kernel_size=3,
nb_stacks=1,
n_layers=4,
total_epochs=10,
tv=-1,
... | 0.770724 | 0.246828 |
import numpy as np
from numpy.linalg import inv, norm
from scipy.linalg import solve_discrete_are,lstsq
from numpy.random import randn
from filterpy.common import pretty_str
from filterpy.kalman import KalmanFilter
class UnstableData(object):
'''Implement... | fdia_simulation/attackers/mo_attacker.py | import numpy as np
from numpy.linalg import inv, norm
from scipy.linalg import solve_discrete_are,lstsq
from numpy.random import randn
from filterpy.common import pretty_str
from filterpy.kalman import KalmanFilter
class UnstableData(object):
'''Implement... | 0.824002 | 0.670836 |
num_dep = 0
class States:
UNRESOLVED = 'unresolved'
GUESSING = 'guessing'
RESOLVED = 'resolved'
class Resolutions:
FAILS = 'fails'
SUCCEEDS = 'succeeds'
def adjudicate():
pass
def backup_rule():
pass
def resolve(order):
dep_list = []
# If order is already resolved, just re... | adjudicator/algo.py | num_dep = 0
class States:
UNRESOLVED = 'unresolved'
GUESSING = 'guessing'
RESOLVED = 'resolved'
class Resolutions:
FAILS = 'fails'
SUCCEEDS = 'succeeds'
def adjudicate():
pass
def backup_rule():
pass
def resolve(order):
dep_list = []
# If order is already resolved, just re... | 0.487063 | 0.303732 |
import logging
import multiprocessing
import os
import random
import numpy as np
from nuart.preprocessing import vat
import config
from run import run_commands, make_parser
__author__ = "<NAME>"
logger = logging.getLogger(__name__)
description = "Reorder and save dataset files based on random seeds and VAT"
def ... | src/processing/reorder_datasets.py | import logging
import multiprocessing
import os
import random
import numpy as np
from nuart.preprocessing import vat
import config
from run import run_commands, make_parser
__author__ = "<NAME>"
logger = logging.getLogger(__name__)
description = "Reorder and save dataset files based on random seeds and VAT"
def ... | 0.358578 | 0.2227 |
import click
from docx import Document
from docx.opc.exceptions import PackageNotFoundError
from TexSoup import TexSoup
from jacowvalidator import app
from jacowvalidator.docutils.page import (check_tracking_on, TrackingOnError)
from jacowvalidator.docutils.doc import create_upload_variables, create_spms_variables, cre... | src/jacowvalidator/spms_cli.py | import click
from docx import Document
from docx.opc.exceptions import PackageNotFoundError
from TexSoup import TexSoup
from jacowvalidator import app
from jacowvalidator.docutils.page import (check_tracking_on, TrackingOnError)
from jacowvalidator.docutils.doc import create_upload_variables, create_spms_variables, cre... | 0.356335 | 0.075551 |
import os
import csv
import platform
def verifyFolders(path, list):
file = open(list, 'r')
ctd = 0;
for line in file:
line = line.replace('\n', '')
if len(line) == 0:
continue
ctd = ctd + 1
if "vNonPorn" in line:
searchDir = path + 'vNonPornDifficult... | data/create_npdi_lists.py | import os
import csv
import platform
def verifyFolders(path, list):
file = open(list, 'r')
ctd = 0;
for line in file:
line = line.replace('\n', '')
if len(line) == 0:
continue
ctd = ctd + 1
if "vNonPorn" in line:
searchDir = path + 'vNonPornDifficult... | 0.048305 | 0.051344 |
import logging
from typing import Any, MutableMapping, Optional
import re
from ruamel import yaml
from cloudformation_cli_python_lib import (
Action,
OperationStatus,
ProgressEvent,
Resource,
SessionProxy,
exceptions,
)
from .models import ResourceHandlerRequest, ResourceModel
from .utils impo... | apply/src/awsqs_kubernetes_resource/handlers.py | import logging
from typing import Any, MutableMapping, Optional
import re
from ruamel import yaml
from cloudformation_cli_python_lib import (
Action,
OperationStatus,
ProgressEvent,
Resource,
SessionProxy,
exceptions,
)
from .models import ResourceHandlerRequest, ResourceModel
from .utils impo... | 0.627267 | 0.046249 |
from .message_define import MyMessage
from ....core.distributed.communication.message import Message
from ....core.distributed.server.server_manager import ServerManager
class GuestManager(ServerManager):
def __init__(self, args, comm, rank, size, guest_trainer):
super().__init__(args, comm, rank, size)
... | python/fedml/simulation/mpi/classical_vertical_fl/guest_manager.py | from .message_define import MyMessage
from ....core.distributed.communication.message import Message
from ....core.distributed.server.server_manager import ServerManager
class GuestManager(ServerManager):
def __init__(self, args, comm, rank, size, guest_trainer):
super().__init__(args, comm, rank, size)
... | 0.336767 | 0.049199 |
import subprocess
from pathlib import Path
import os
import sys
import shutil
import re
# Here we perform SVF analysis
# As an input it takes:
# - a path to a folder with .cpp source files
# - a path to a temp folder for .bc files
# - a path to a folder where resulting file SVF-out.txt will be generated
def run_... | scripts/src/SVF/__main__.py | import subprocess
from pathlib import Path
import os
import sys
import shutil
import re
# Here we perform SVF analysis
# As an input it takes:
# - a path to a folder with .cpp source files
# - a path to a temp folder for .bc files
# - a path to a folder where resulting file SVF-out.txt will be generated
def run_... | 0.265024 | 0.199698 |
from __future__ import with_statement
import os
from fabric.api import *
from fabric.operations import *
from fabric.contrib import *
from fabric.context_managers import cd
from tempfile import NamedTemporaryFile
from distutils.version import LooseVersion
# your configuration
control_node = ['localhost']
compute_nod... | fabfile.py | from __future__ import with_statement
import os
from fabric.api import *
from fabric.operations import *
from fabric.contrib import *
from fabric.context_managers import cd
from tempfile import NamedTemporaryFile
from distutils.version import LooseVersion
# your configuration
control_node = ['localhost']
compute_nod... | 0.219087 | 0.096238 |
import inspect
import tensorflow as tf
from . import object_selection
# Collect all selector layers defined in object selection
all_selectors = {
name: layer
for name, layer in inspect.getmembers(object_selection)
if inspect.isclass(layer) and name.endswith("ObjectSelection")
}
def attention_entropy(att... | components/test_object_selection.py | import inspect
import tensorflow as tf
from . import object_selection
# Collect all selector layers defined in object selection
all_selectors = {
name: layer
for name, layer in inspect.getmembers(object_selection)
if inspect.isclass(layer) and name.endswith("ObjectSelection")
}
def attention_entropy(att... | 0.84137 | 0.369031 |
import zlib, tempfile, io, unicodedata
from ._binarystream import _BinaryStream
from collections import OrderedDict
class InvalidD2IFile(Exception):
def __init__(self, message):
super(InvalidD2IFile, self).__init__(message)
self.message = message
class D2I:
def __init__(self, stream):
... | PyDofus-master/pydofus/d2i.py |
import zlib, tempfile, io, unicodedata
from ._binarystream import _BinaryStream
from collections import OrderedDict
class InvalidD2IFile(Exception):
def __init__(self, message):
super(InvalidD2IFile, self).__init__(message)
self.message = message
class D2I:
def __init__(self, stream):
... | 0.439507 | 0.158793 |
from a10sdk.common.A10BaseClass import A10BaseClass
class GeolocList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param tomask: {"type": "string", "format": "string"}
:param hits: {"type": "number", "format": "number"}
:param from: {"type": "string", "format"... | a10sdk/core/gslb/gslb_geoloc_oper.py | from a10sdk.common.A10BaseClass import A10BaseClass
class GeolocList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param tomask: {"type": "string", "format": "string"}
:param hits: {"type": "number", "format": "number"}
:param from: {"type": "string", "format"... | 0.806586 | 0.414543 |
import argparse
import os
import pickle
import time
from parser import Parser
from processor import postprocess, Processor
__author__ = '<NAME>'
argparser = argparse.ArgumentParser("PA4 Argparser")
# paths
argparser.add_argument(
'--data_dir', default='./data', help='path to data directory')
argparser.add_argume... | starter_code/main.py | import argparse
import os
import pickle
import time
from parser import Parser
from processor import postprocess, Processor
__author__ = '<NAME>'
argparser = argparse.ArgumentParser("PA4 Argparser")
# paths
argparser.add_argument(
'--data_dir', default='./data', help='path to data directory')
argparser.add_argume... | 0.432063 | 0.097777 |
from alembic import context
from sqlalchemy.orm import sessionmaker
from limonero.migration_utils import (get_enable_disable_fk_command,
upgrade_actions, downgrade_actions, get_psql_enum_alter_commands,
is_mysql, is_psql)
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '05a62... | migrations/versions/32053847c4db_add_new_types.py | from alembic import context
from sqlalchemy.orm import sessionmaker
from limonero.migration_utils import (get_enable_disable_fk_command,
upgrade_actions, downgrade_actions, get_psql_enum_alter_commands,
is_mysql, is_psql)
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '05a62... | 0.371137 | 0.079603 |
__author__ = "<NAME>"
__copyright__ = "Copyright (C) 2020 <NAME>"
__license__ = "MIT"
__credits__ = []
__version__ = "0.2.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = (["Prototype", "Development", "Production"])[2]
from typing import Union
class SimpleLine:
""" A single line of th... | Dados/SimpleLine/SimpleLine.py | __author__ = "<NAME>"
__copyright__ = "Copyright (C) 2020 <NAME>"
__license__ = "MIT"
__credits__ = []
__version__ = "0.2.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = (["Prototype", "Development", "Production"])[2]
from typing import Union
class SimpleLine:
""" A single line of th... | 0.685529 | 0.153613 |
import enum
import struct
@enum.unique
class CameraFlip(enum.IntEnum):
"""Represents the camera orientation. 'up' is default, 'down' is flipped
vertically, and 'mirror' is flipped horizontally."""
up = 0,
up_mirror = 1,
down_mirror = 2,
down = 3
@enum.unique
class CommandType(enum.IntEnum):
... | pylwdrone/command.py | import enum
import struct
@enum.unique
class CameraFlip(enum.IntEnum):
"""Represents the camera orientation. 'up' is default, 'down' is flipped
vertically, and 'mirror' is flipped horizontally."""
up = 0,
up_mirror = 1,
down_mirror = 2,
down = 3
@enum.unique
class CommandType(enum.IntEnum):
... | 0.689096 | 0.190103 |
import re
from json import dumps
from tornado import escape
from decimal import Decimal
from datetime import datetime
try:
import timestring
except: # pragma: no cover
timestring = None
def json_defaults(obj):
if isinstance(obj, Decimal):
return float(obj)
elif isinstance(obj, datetime):
... | tornwrap/tornwrap/helpers.py | import re
from json import dumps
from tornado import escape
from decimal import Decimal
from datetime import datetime
try:
import timestring
except: # pragma: no cover
timestring = None
def json_defaults(obj):
if isinstance(obj, Decimal):
return float(obj)
elif isinstance(obj, datetime):
... | 0.318909 | 0.16175 |
from PropertyTree import PropertyNode
import commands
ident_node = PropertyNode('/config/identity')
specs_node = PropertyNode('/config/specs')
tecs_config_node = PropertyNode('/config/autopilot/TECS')
requests_pending = True
def gen_requests():
global requests_pending
if not requests_pending:
# we h... | tools/auralink/requests.py |
from PropertyTree import PropertyNode
import commands
ident_node = PropertyNode('/config/identity')
specs_node = PropertyNode('/config/specs')
tecs_config_node = PropertyNode('/config/autopilot/TECS')
requests_pending = True
def gen_requests():
global requests_pending
if not requests_pending:
# we h... | 0.275032 | 0.048903 |
import torch
import torch.nn.functional as F
from ..builder import PIXEL_SAMPLERS
from .base_pixel_sampler import BasePixelSampler
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
"""Online Hard Example Mining Sampler for segmentation.
Args:
thresh (float): The threshold f... | mmseg/core/seg/sampler/ohem_pixel_sampler.py | import torch
import torch.nn.functional as F
from ..builder import PIXEL_SAMPLERS
from .base_pixel_sampler import BasePixelSampler
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
"""Online Hard Example Mining Sampler for segmentation.
Args:
thresh (float): The threshold f... | 0.837653 | 0.617022 |
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
"""
hit -> it, ht, hi
hot -> ot, ht, ho
dot -> ot, dt, do
dog -> og, dg, do
... | 127-word-ladder/127-word-ladder.py | class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
"""
hit -> it, ht, hi
hot -> ot, ht, ho
dot -> ot, dt, do
dog -> og, dg, do
... | 0.516839 | 0.411525 |
import importlib
import inspect
from types import FunctionType
from app.config.routes import routes
from app.controllers import controllers_list
def _set_route(app, route_name, pattern, controller, action, **kwargs):
app.add_url_rule(pattern, view_func=controller.as_view(route_name, action), **kwargs)
_routed_met... | system/init/routes.py | import importlib
import inspect
from types import FunctionType
from app.config.routes import routes
from app.controllers import controllers_list
def _set_route(app, route_name, pattern, controller, action, **kwargs):
app.add_url_rule(pattern, view_func=controller.as_view(route_name, action), **kwargs)
_routed_met... | 0.279435 | 0.053453 |
import torch
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import os
# -----------------ready the dataset--------------------------
def default_loader(path):
return Image.open(path)
class MyDataset(Dataset):
def ... | My_data_set.py | import torch
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import os
# -----------------ready the dataset--------------------------
def default_loader(path):
return Image.open(path)
class MyDataset(Dataset):
def ... | 0.622574 | 0.330066 |
from db import db
from flask import session
from werkzeug.security import check_password_hash, generate_password_hash
def create_campaign(title, password):
hash_value = generate_password_hash(password)
creator_id = session.get("user_id", 0)
sql = """INSERT INTO campaigns (title, creator_id, created_at,
... | campaigns.py | from db import db
from flask import session
from werkzeug.security import check_password_hash, generate_password_hash
def create_campaign(title, password):
hash_value = generate_password_hash(password)
creator_id = session.get("user_id", 0)
sql = """INSERT INTO campaigns (title, creator_id, created_at,
... | 0.168515 | 0.089256 |
import cStringIO
import matplotlib
# Execute matplotlib.use('Agg') if using image_server
# http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from threading import Lock
from threading import Thread
import rospy
import time
import ar... | scripts/contour_node.py |
import cStringIO
import matplotlib
# Execute matplotlib.use('Agg') if using image_server
# http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from threading import Lock
from threading import Thread
import rospy
import time
import ar... | 0.61451 | 0.209106 |
import json
import socket
import signal
import time
import schedule
import _thread
from flask import Flask, request, jsonify
from cheroot.wsgi import Server as WSGIServer
from loguru import logger
from datetime import datetime
from typing import Callable
from dataclasses import dataclass
from enum import Enum, auto
... | pyngsi/scheduler.py |
import json
import socket
import signal
import time
import schedule
import _thread
from flask import Flask, request, jsonify
from cheroot.wsgi import Server as WSGIServer
from loguru import logger
from datetime import datetime
from typing import Callable
from dataclasses import dataclass
from enum import Enum, auto
... | 0.518302 | 0.116437 |
from peachpy.x86_64 import *
from peachpy import *
from peachpy.c.types import *
# =================================================
# ADDITION
# =================================================
sse_vector_add_map = {
Yep8s : PADDB,
Yep8u : PADDB,
Yep16s: PADDW,
Yep16u: PADDW,
Yep32s: PADDD,
Y... | library/sources/core/instruction_maps/sse_instruction_maps.py | from peachpy.x86_64 import *
from peachpy import *
from peachpy.c.types import *
# =================================================
# ADDITION
# =================================================
sse_vector_add_map = {
Yep8s : PADDB,
Yep8u : PADDB,
Yep16s: PADDW,
Yep16u: PADDW,
Yep32s: PADDD,
Y... | 0.327668 | 0.16398 |
# Copyright (c) 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import os
from dataclasses import dataclass, field
from typing import Dict
from ads.common.serializer import DataClassSerializable, SideEffect
from ads.model.run... | ads/model/runtime/runtime_info.py |
# Copyright (c) 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import os
from dataclasses import dataclass, field
from typing import Dict
from ads.common.serializer import DataClassSerializable, SideEffect
from ads.model.run... | 0.933937 | 0.21213 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
import random
import time
from utils import AverageMeter, accuracy, dir_path, SensorDataSet, normalise_data
device = torch.device('cuda' if... | FER/em_network/train_baseline.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
import random
import time
from utils import AverageMeter, accuracy, dir_path, SensorDataSet, normalise_data
device = torch.device('cuda' if... | 0.888554 | 0.471223 |
import os
import sys
sys.path.append("../../common")
from env_indigo import *
indigo = Indigo()
print("****** Arom/Dearom ********")
m = indigo.loadMolecule("[As]1C=N[AsH]S=1C")
origin_smiles = m.smiles()
print(origin_smiles)
m.aromatize()
print(m.smiles())
m.dearomatize()
restored_smiles = m.smiles()
print(restored... | api/tests/integration/tests/arom/basic.py | import os
import sys
sys.path.append("../../common")
from env_indigo import *
indigo = Indigo()
print("****** Arom/Dearom ********")
m = indigo.loadMolecule("[As]1C=N[AsH]S=1C")
origin_smiles = m.smiles()
print(origin_smiles)
m.aromatize()
print(m.smiles())
m.dearomatize()
restored_smiles = m.smiles()
print(restored... | 0.078442 | 0.139602 |
from djongo import models
class ListCards(models.Model):
card_name = models.CharField(max_length=10, primary_key=True)
value_atout = models.IntegerField()
value_non_atout = models.IntegerField()
idc = models.CharField(max_length=2)
objects = models.DjongoManager()
class Rules(models.Model):
ty... | django_cards/coinche/models.py | from djongo import models
class ListCards(models.Model):
card_name = models.CharField(max_length=10, primary_key=True)
value_atout = models.IntegerField()
value_non_atout = models.IntegerField()
idc = models.CharField(max_length=2)
objects = models.DjongoManager()
class Rules(models.Model):
ty... | 0.460046 | 0.218388 |
import re
r0 = re.compile('^([a-z]+) \((\d+)\)(?: -> ([a-z, ]+))?')
# Part 1
allprogs = set()
hasparent = set()
with open("07.txt") as f:
for line in f:
if m := r0.match(line):
allprogs.add(m[1])
if m[3] is not None:
a = set(m[3].split(", "))
allprogs... | 07.py | import re
r0 = re.compile('^([a-z]+) \((\d+)\)(?: -> ([a-z, ]+))?')
# Part 1
allprogs = set()
hasparent = set()
with open("07.txt") as f:
for line in f:
if m := r0.match(line):
allprogs.add(m[1])
if m[3] is not None:
a = set(m[3].split(", "))
allprogs... | 0.281208 | 0.221351 |
import base64
from typing import Iterable, Callable
from fetchai.ledger.api import ApiEndpoint
from fetchai.ledger.api.common import TransactionFactory, ApiError
from fetchai.ledger.bitvector import BitVector
from fetchai.ledger.crypto import Address, Entity, Identity
GOVERNANCE_API_PREFIX = 'fetch.governance'
GovT... | fetchai/ledger/api/governance.py |
import base64
from typing import Iterable, Callable
from fetchai.ledger.api import ApiEndpoint
from fetchai.ledger.api.common import TransactionFactory, ApiError
from fetchai.ledger.bitvector import BitVector
from fetchai.ledger.crypto import Address, Entity, Identity
GOVERNANCE_API_PREFIX = 'fetch.governance'
GovT... | 0.90736 | 0.355188 |
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection._search import BaseSearchCV
from sklearn.base import is_regressor, is_classifier
from sklearn.utils.multiclass import type_of_target
import time
import logging
logger = log... | rate/mimic.py | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection._search import BaseSearchCV
from sklearn.base import is_regressor, is_classifier
from sklearn.utils.multiclass import type_of_target
import time
import logging
logger = log... | 0.649912 | 0.744331 |
from datetime import datetime, timedelta
from dateutil.parser import parse
from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase
class JiraTestCase(SourceCollectorTestCase):
"""Base class for Jira unit tests."""
METRIC_TYPE = "Subclass responsibility"
def setUp(self):
... | components/collector/tests/source_collectors/api_source_collectors/test_jira.py |
from datetime import datetime, timedelta
from dateutil.parser import parse
from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase
class JiraTestCase(SourceCollectorTestCase):
"""Base class for Jira unit tests."""
METRIC_TYPE = "Subclass responsibility"
def setUp(self):
... | 0.858837 | 0.494751 |
from pathlib import Path
import logging
import numpy as np
import h5py
from matplotlib.pyplot import show
from gridaurora.calcemissions import calcemissions
from gridaurora.filterload import getSystemT
from gridaurora.plots import writeplots, plotspectra, showIncrVER
# github.com/scivision/transcarread
import transcar... | PlotEmissionProfiles.py | from pathlib import Path
import logging
import numpy as np
import h5py
from matplotlib.pyplot import show
from gridaurora.calcemissions import calcemissions
from gridaurora.filterload import getSystemT
from gridaurora.plots import writeplots, plotspectra, showIncrVER
# github.com/scivision/transcarread
import transcar... | 0.63409 | 0.385433 |
from sklearn import metrics
import numpy as np
def compute_cohen_kappa(confusion_matrix):
prob_expectedA = np.empty(len(confusion_matrix))
prob_expectedB = np.empty(len(confusion_matrix))
prob_observed = 0
mean_acc = np.empty(len(confusion_matrix))
for n in range(0, len(confusion_matrix)):
... | references/ecg_classification/python/_aux/testing_kappa.py | from sklearn import metrics
import numpy as np
def compute_cohen_kappa(confusion_matrix):
prob_expectedA = np.empty(len(confusion_matrix))
prob_expectedB = np.empty(len(confusion_matrix))
prob_observed = 0
mean_acc = np.empty(len(confusion_matrix))
for n in range(0, len(confusion_matrix)):
... | 0.589362 | 0.504394 |
import base64
import json
import platform
import re
import sys
import zlib
from textwrap import wrap
from urllib.parse import urlencode, urlsplit, urlunsplit
import ipywidgets as ipw
from aiidalab.utils import find_installed_packages
from ansi2html import Ansi2HTMLConverter
def get_environment_fingerprint(encoding="... | aiidalab_widgets_base/bug_report.py | 0.096376 | 0.21388 |