code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import argparse
import logging
import socket
from oslo_config import cfg
from stevedore import driver
from oslo_messaging._drivers import impl_zmq
from oslo_messaging._drivers.zmq_driver.proxy.central import zmq_central_proxy
from oslo_messaging._drivers.zmq_driver.proxy.local import zmq_local_proxy
from oslo_messag... | oslo_messaging/_drivers/zmq_driver/proxy/zmq_proxy.py |
import argparse
import logging
import socket
from oslo_config import cfg
from stevedore import driver
from oslo_messaging._drivers import impl_zmq
from oslo_messaging._drivers.zmq_driver.proxy.central import zmq_central_proxy
from oslo_messaging._drivers.zmq_driver.proxy.local import zmq_local_proxy
from oslo_messag... | 0.515376 | 0.051225 |
import sys
import os
import time
import numpy as np
import torch
import torch.nn as nn
import importlib.util
import simple_spearmint
from torch.utils.data import DataLoader
from torch.cuda import is_available as cuda_available
from utils import accounting, train_utils
from utils import torch_model_construction_utils
... | src/pytorch_train_spearmint.py | import sys
import os
import time
import numpy as np
import torch
import torch.nn as nn
import importlib.util
import simple_spearmint
from torch.utils.data import DataLoader
from torch.cuda import is_available as cuda_available
from utils import accounting, train_utils
from utils import torch_model_construction_utils
... | 0.468791 | 0.346348 |
from collections import namedtuple
from nose.tools import assert_equals
import shutil
import tempfile
from numpy import array, allclose
from test_utils import PySparkTestCase
from thunder.rdds.series import Series
from thunder.rdds.keys import _subToIndConverter, _indToSubConverter
class SeriesKeysTestCase(PySparkTes... | python/test/test_series_keys.py | from collections import namedtuple
from nose.tools import assert_equals
import shutil
import tempfile
from numpy import array, allclose
from test_utils import PySparkTestCase
from thunder.rdds.series import Series
from thunder.rdds.keys import _subToIndConverter, _indToSubConverter
class SeriesKeysTestCase(PySparkTes... | 0.655667 | 0.745769 |
import getpass
import json
import os
import sys
from datetime import datetime
import pytz
import api
_BRICKSET_DIRECTORY = '.brickset'
_CONFIG_FILENAME = 'config'
_CACHE_FILENAME = 'cache'
def _config_directory():
return os.path.expanduser('~') + os.sep + _BRICKSET_DIRECTORY + os.sep
def get_config():
co... | bin/config.py | import getpass
import json
import os
import sys
from datetime import datetime
import pytz
import api
_BRICKSET_DIRECTORY = '.brickset'
_CONFIG_FILENAME = 'config'
_CACHE_FILENAME = 'cache'
def _config_directory():
return os.path.expanduser('~') + os.sep + _BRICKSET_DIRECTORY + os.sep
def get_config():
co... | 0.13966 | 0.044598 |
from django.shortcuts import render, reverse
from django.http import HttpResponseRedirect
from django.views import View, generic
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
from .models import BlogPost, Comment
from django.contrib.auth.model... | blog/views.py | from django.shortcuts import render, reverse
from django.http import HttpResponseRedirect
from django.views import View, generic
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
from .models import BlogPost, Comment
from django.contrib.auth.model... | 0.474631 | 0.071884 |
import signal
import sys
import logging
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent,
)
def mysql_stream(conf, mongo, queue_out):
logger = logging.getLogger(__name__)
# server_id is your slave identi... | mymongolib/mysql.py | import signal
import sys
import logging
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent,
)
def mysql_stream(conf, mongo, queue_out):
logger = logging.getLogger(__name__)
# server_id is your slave identi... | 0.196363 | 0.151843 |
__author__ = "<NAME>, <NAME>"
from DyDPP import DyDPP, DataDyDPP
from copy import deepcopy
import numpy as np
import os
import sys
import pickle
import time
import itertools
def shift_data(dataArray, minItems=1):
"""
The music data is a list of vectors each of which
has elements of integer in the range... | src/tasks/dydpp/experiment.py | __author__ = "<NAME>, <NAME>"
from DyDPP import DyDPP, DataDyDPP
from copy import deepcopy
import numpy as np
import os
import sys
import pickle
import time
import itertools
def shift_data(dataArray, minItems=1):
"""
The music data is a list of vectors each of which
has elements of integer in the range... | 0.38885 | 0.482307 |
from __future__ import absolute_import, division, print_function, unicode_literals
import time
try:
#uwsgi is loaded at runtime by uwsgi app.
import uwsgi
except ImportError:
def missing_uwsgi_dependencies(*args, **kwargs): #pylint: disable=unused-argument
"""Only complain for missing deps if the... | splitio/storage/adapters/uwsgi_cache.py |
from __future__ import absolute_import, division, print_function, unicode_literals
import time
try:
#uwsgi is loaded at runtime by uwsgi app.
import uwsgi
except ImportError:
def missing_uwsgi_dependencies(*args, **kwargs): #pylint: disable=unused-argument
"""Only complain for missing deps if the... | 0.804291 | 0.115611 |
import requests
import json
def get_header(token, accept=False, content=False):
header = {
"Authorization": "Bearer {}".format(token),
"Accept": "application/json",
"Content-Type": "application/json",
}
fields = (
["Authorization"]
+ (["Accept"] if accept else [])
... | asana/api.py | import requests
import json
def get_header(token, accept=False, content=False):
header = {
"Authorization": "Bearer {}".format(token),
"Accept": "application/json",
"Content-Type": "application/json",
}
fields = (
["Authorization"]
+ (["Accept"] if accept else [])
... | 0.461502 | 0.221719 |
from typing import List, Callable, Type, Optional
from sklearn import model_selection
import functools
from lpot.pipelines.pipeline import Pipeline, ClassificationPipeline, RegressionPipeline
from lpot.pipelines.layers import layer
import random
import math
class EvolutionManager:
n_layers: int
transformer_... | lpot/evolution/evolution_manager.py | from typing import List, Callable, Type, Optional
from sklearn import model_selection
import functools
from lpot.pipelines.pipeline import Pipeline, ClassificationPipeline, RegressionPipeline
from lpot.pipelines.layers import layer
import random
import math
class EvolutionManager:
n_layers: int
transformer_... | 0.909037 | 0.555857 |
C_NL = '\n'
C_DOT = '.'
C_TAB = '\t'
C_PIPE = '|'
C_SPACE = ' '
C_QMARK = '?'
C_HYPHEN = '-'
C_ESCAPE = '\\'
C_LPAREN = '('
C_RPAREN = ')'
C_LCURLY = '{'
C_RCURLY = '}'
C_LBRACE = '['
C_RBRACE = ']'
C_ATSIGN = '@'
C_ASTERISK = '*'
C_DOLLARSIGN = '$'
C_UNDERSCORE = '_'
SOT = { # Start-of-token chars.
"#": "tkCMT"... | src/parser/python/lexer.py |
C_NL = '\n'
C_DOT = '.'
C_TAB = '\t'
C_PIPE = '|'
C_SPACE = ' '
C_QMARK = '?'
C_HYPHEN = '-'
C_ESCAPE = '\\'
C_LPAREN = '('
C_RPAREN = ')'
C_LCURLY = '{'
C_RCURLY = '}'
C_LBRACE = '['
C_RBRACE = ']'
C_ATSIGN = '@'
C_ASTERISK = '*'
C_DOLLARSIGN = '$'
C_UNDERSCORE = '_'
SOT = { # Start-of-token chars.
"#": "tkCMT"... | 0.401336 | 0.105902 |
from unittest import TestCase
from unittest import skip, SkipTest
from ebu_tt_live.bindings import ebuttdt
from pyxb import SimpleTypeValueError, SimpleFacetValueError
class TestPixelFontSizeType(TestCase):
_test_string_1 = '10px'
_test_string_2 = '10px 20px'
_type_class = ebuttdt.PixelFontSizeType
... | ebu_tt_live/bindings/test/test_sizing.py | from unittest import TestCase
from unittest import skip, SkipTest
from ebu_tt_live.bindings import ebuttdt
from pyxb import SimpleTypeValueError, SimpleFacetValueError
class TestPixelFontSizeType(TestCase):
_test_string_1 = '10px'
_test_string_2 = '10px 20px'
_type_class = ebuttdt.PixelFontSizeType
... | 0.760384 | 0.776538 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class Attribute(object):
"""
Attribute
"""
#: A constant which can be used with the maximum_len property o... | src/oci/log_analytics/models/attribute.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class Attribute(object):
"""
Attribute
"""
#: A constant which can be used with the maximum_len property o... | 0.835852 | 0.175556 |
import argparse
import logging
import re
import sys
import endpoint
from dask import compute, delayed
import dask.multiprocessing
import picluster
import remoterunner
class RemoteHelper:
def __init__(self):
self.cluster_address = endpoint.url
self.cluster = picluster.PiBoardTable(self.cluster_a... | PiDataCenter/remote.py | import argparse
import logging
import re
import sys
import endpoint
from dask import compute, delayed
import dask.multiprocessing
import picluster
import remoterunner
class RemoteHelper:
def __init__(self):
self.cluster_address = endpoint.url
self.cluster = picluster.PiBoardTable(self.cluster_a... | 0.276886 | 0.089574 |
import unittest
class DecisionTreeNode:
def __init__( self ):
self.probability = None
self.feature = None
self.leftTree = self.rightTree = None
def setProbability( self, probability ):
assert self.probability is None
self.probability = probability
def setFeature( self, feature ):
assert self.feature i... | GoogleCodeJam/DecisionTree_2009_R1/DecisionTree.py | import unittest
class DecisionTreeNode:
def __init__( self ):
self.probability = None
self.feature = None
self.leftTree = self.rightTree = None
def setProbability( self, probability ):
assert self.probability is None
self.probability = probability
def setFeature( self, feature ):
assert self.feature i... | 0.457621 | 0.672977 |
import LinearAlgebraPurePython as la
import MachineLearningPurePy as ml
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
import sys
# Section 1: Fake data p... | LeastSquaresPolyPractice_3b.py | import LinearAlgebraPurePython as la
import MachineLearningPurePy as ml
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
import sys
# Section 1: Fake data p... | 0.461502 | 0.69936 |
from argparse import Namespace
from pathlib import Path
from typing import Dict, Union
from _pytest.monkeypatch import MonkeyPatch
from flask import Flask
from genpei.app import create_app, handle_default_params, parse_args
from genpei.const import DEFAULT_HOST, DEFAULT_PORT
base_dir: Path = Path(__file__).parent.pa... | tests/test_startup_params.py | from argparse import Namespace
from pathlib import Path
from typing import Dict, Union
from _pytest.monkeypatch import MonkeyPatch
from flask import Flask
from genpei.app import create_app, handle_default_params, parse_args
from genpei.const import DEFAULT_HOST, DEFAULT_PORT
base_dir: Path = Path(__file__).parent.pa... | 0.720467 | 0.235608 |
from misc import dp
from .general import menu
from states import AddPassword
from misc import COMMANDS as CMDS
from models import User, Password
from keyboards import get_add_password_kb
from keyboards import main_kb, back_kb, generate_password_kb, generated_password_kb
import string
from random import choice
from aio... | src/handlers/add_password.py | from misc import dp
from .general import menu
from states import AddPassword
from misc import COMMANDS as CMDS
from models import User, Password
from keyboards import get_add_password_kb
from keyboards import main_kb, back_kb, generate_password_kb, generated_password_kb
import string
from random import choice
from aio... | 0.267217 | 0.173078 |
import utime
from machine import I2C, Pin, deepsleep
import ubinascii
import ujson
import bme280_float as bme280
import ssd1306
from ulora import TTN, uLoRa
# Heltec ESP32 LoRa V2 development board SPI pins
LORA_CS = const(18)
LORA_SCK = const(5)
LORA_MOSI = const(27)
LORA_MISO = const(19)
LORA_IRQ = const(26)
LORA_R... | examples/heltec-wiresless-stick.py |
import utime
from machine import I2C, Pin, deepsleep
import ubinascii
import ujson
import bme280_float as bme280
import ssd1306
from ulora import TTN, uLoRa
# Heltec ESP32 LoRa V2 development board SPI pins
LORA_CS = const(18)
LORA_SCK = const(5)
LORA_MOSI = const(27)
LORA_MISO = const(19)
LORA_IRQ = const(26)
LORA_R... | 0.340266 | 0.226441 |
from __future__ import absolute_import
import numpy as np
import pandas as pd
from pandas import DataFrame
from lxml import objectify
from fitparse import FitFile
try:
from . import tcxtools,gpxtools
from .utils import totimestamp, geo_distance
except (ValueError,ImportError): # pragma: no cover
import tcxt... | rowingdata/otherparsers.py | from __future__ import absolute_import
import numpy as np
import pandas as pd
from pandas import DataFrame
from lxml import objectify
from fitparse import FitFile
try:
from . import tcxtools,gpxtools
from .utils import totimestamp, geo_distance
except (ValueError,ImportError): # pragma: no cover
import tcxt... | 0.240953 | 0.138812 |
from CIM100.IEC61968.Common.Document import Document
class ProcedureDataSet(Document):
"""A data set recorded each time a procedure is executed. Observed results are captured in associated measurement values and/or values for properties relevant to the type of procedure performed.A data set recorded each time a p... | CIM100/IEC61970/Informative/InfAssets/ProcedureDataSet.py |
from CIM100.IEC61968.Common.Document import Document
class ProcedureDataSet(Document):
"""A data set recorded each time a procedure is executed. Observed results are captured in associated measurement values and/or values for properties relevant to the type of procedure performed.A data set recorded each time a p... | 0.880592 | 0.546436 |
# TODO: Create query function that maps query-result strings with functions
def query_func(question, default=False):
"""
Ask a string question
No input defaults to "no" which results in False
"""
valid = {"yes": True, "y": True, "no": False, "n": False}
if default is True:
pr... | in4073/dfu_serial/util.py |
# TODO: Create query function that maps query-result strings with functions
def query_func(question, default=False):
"""
Ask a string question
No input defaults to "no" which results in False
"""
valid = {"yes": True, "y": True, "no": False, "n": False}
if default is True:
pr... | 0.274157 | 0.49884 |
from subprocess import call, check_output, STDOUT
from shutil import copyfile, copytree
import sys
import os
import tempfile
import time
sys.path.insert(1, os.path.realpath(os.path.pardir))
import stack_build
INSTALLER_WIX = "Product.wxs"
INSTALLER_WIXOBJ = "Product.wixobj"
class OsNotWIndows(Exception):
pass
cl... | da-assistant/testing/run-windows-tests.py |
from subprocess import call, check_output, STDOUT
from shutil import copyfile, copytree
import sys
import os
import tempfile
import time
sys.path.insert(1, os.path.realpath(os.path.pardir))
import stack_build
INSTALLER_WIX = "Product.wxs"
INSTALLER_WIXOBJ = "Product.wixobj"
class OsNotWIndows(Exception):
pass
cl... | 0.147893 | 0.063773 |
and contains functions to help apply it during the course of INDRA assembly."""
import logging
import requests
from urllib.parse import urljoin
from indra.ontology.standardize \
import standardize_agent_name
from indra.config import get_config, has_config
from indra.pipeline import register_pipeline
from .adeft imp... | indra/preassembler/grounding_mapper/gilda.py | and contains functions to help apply it during the course of INDRA assembly."""
import logging
import requests
from urllib.parse import urljoin
from indra.ontology.standardize \
import standardize_agent_name
from indra.config import get_config, has_config
from indra.pipeline import register_pipeline
from .adeft imp... | 0.835416 | 0.397909 |
import os
import pygame
import pygame.gfxdraw
import time
import pathlib, os
#variables de sinonimia -------------------->>
true = True
false = False
none = None
null = None
#protocolo de pygame -------------------->>
pygame.init() #protocolo de inicializacion para pygame
os.environ['SDL_VIDEO_CENTERED'] = '1' #hace... | games/game4/game4MB/graphics.py | import os
import pygame
import pygame.gfxdraw
import time
import pathlib, os
#variables de sinonimia -------------------->>
true = True
false = False
none = None
null = None
#protocolo de pygame -------------------->>
pygame.init() #protocolo de inicializacion para pygame
os.environ['SDL_VIDEO_CENTERED'] = '1' #hace... | 0.216094 | 0.296171 |
from math import cos, sin
from window import Window
class Scene2(object):
""" Scene2()
1. Display a window with are information of player
2. Start a animation on the window
3. Hide display
4. Start stars animation
5. On finish, spawn the player """
... | src/scenes/scene_2.py | from math import cos, sin
from window import Window
class Scene2(object):
""" Scene2()
1. Display a window with are information of player
2. Start a animation on the window
3. Hide display
4. Start stars animation
5. On finish, spawn the player """
... | 0.773516 | 0.356083 |
import os
import sys
import pycurl
import json
import argparse
def get_png(output_pointers, name, pwd, dst_output):
from urllib import urlencode
"""
Given base url, username and password,
provides the output file
"""
outfile = open(dst_output, 'w')
base_url = output_pointers['base_url'... | apps/ophidia_client/ophidia_helper.py |
import os
import sys
import pycurl
import json
import argparse
def get_png(output_pointers, name, pwd, dst_output):
from urllib import urlencode
"""
Given base url, username and password,
provides the output file
"""
outfile = open(dst_output, 'w')
base_url = output_pointers['base_url'... | 0.26588 | 0.155271 |
from os import environ
from unittest import mock
import responses
from botocore.stub import ANY
from dateutil import parser
from hyp3_sdk.jobs import Job
import harvest_products
@responses.activate
def test_harvest_image(s3_stubber):
responses.add(responses.GET, 'https://foo.com/file.png', body='image_content')... | tests/test_harvest_products.py | from os import environ
from unittest import mock
import responses
from botocore.stub import ANY
from dateutil import parser
from hyp3_sdk.jobs import Job
import harvest_products
@responses.activate
def test_harvest_image(s3_stubber):
responses.add(responses.GET, 'https://foo.com/file.png', body='image_content')... | 0.52342 | 0.37319 |
import time
import uuid
from threading import Thread
import os
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config
from kivy.lang import Builder
from kivy.logger import Logger
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.gridlayout import Gri... | uwsgi/client.py | import time
import uuid
from threading import Thread
import os
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config
from kivy.lang import Builder
from kivy.logger import Logger
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.gridlayout import Gri... | 0.336222 | 0.070528 |
import re
import math
import os
ngram_fast = lambda text, n: [text[i:i+n] for i in range(0, len(text) - (n-1)) if not " " in text[i:i+n]]
def count_grams(grams):
count = dict()
for gram in grams:
if gram in count:
count[gram] += 1
else:
count[gram] = 1
return count
def create_digram_model(... | main.py | import re
import math
import os
ngram_fast = lambda text, n: [text[i:i+n] for i in range(0, len(text) - (n-1)) if not " " in text[i:i+n]]
def count_grams(grams):
count = dict()
for gram in grams:
if gram in count:
count[gram] += 1
else:
count[gram] = 1
return count
def create_digram_model(... | 0.457379 | 0.233553 |
from siuba.siu import symbolic_dispatch
from pandas.arrays import DatetimeArray, PeriodArray
from pandas import DatetimeIndex, PeriodIndex, Period, Timestamp, Series
from pandas import offsets
from pandas.core.dtypes.common import is_period_dtype, is_datetime64_any_dtype
from abc import ABC
try:
from pandas.tser... | siuba/experimental/datetime.py | from siuba.siu import symbolic_dispatch
from pandas.arrays import DatetimeArray, PeriodArray
from pandas import DatetimeIndex, PeriodIndex, Period, Timestamp, Series
from pandas import offsets
from pandas.core.dtypes.common import is_period_dtype, is_datetime64_any_dtype
from abc import ABC
try:
from pandas.tser... | 0.83901 | 0.446374 |
import numpy as np
from pysketcher import Curve, Point
from pysketcher._line import Line
from pysketcher.composition import Composition
class Spring(Composition):
"""A representation of a spring.
Specify a *vertical* spring, starting at `start` and with `length`
as total vertical length. In the middle o... | pysketcher/_spring.py | import numpy as np
from pysketcher import Curve, Point
from pysketcher._line import Line
from pysketcher.composition import Composition
class Spring(Composition):
"""A representation of a spring.
Specify a *vertical* spring, starting at `start` and with `length`
as total vertical length. In the middle o... | 0.889481 | 0.625266 |
import unittest
from loguru import logger
from probe_ably.core.tasks.utils import ReadInputTask
class PrepareRicoScaTest(unittest.TestCase):
def test_wrong_split_size(self):
TEST_INPUT = "./tests/sample_files/test_input/wrong_split_size.json"
read_input_task = ReadInputTask()
self.assertR... | tests/core/tasks/utils/test_read_input_task.py | import unittest
from loguru import logger
from probe_ably.core.tasks.utils import ReadInputTask
class PrepareRicoScaTest(unittest.TestCase):
def test_wrong_split_size(self):
TEST_INPUT = "./tests/sample_files/test_input/wrong_split_size.json"
read_input_task = ReadInputTask()
self.assertR... | 0.468061 | 0.471223 |
import base64
import cPickle
import json
import time
import urllib
import urllib2
import urlparse
import uuid
import gevent
class Task(object):
def __init__(self, queue_name, content_type, body):
self.queue_name = queue_name
if content_type == 'application/json':
data = json.loads(body... | miyamoto/task.py | import base64
import cPickle
import json
import time
import urllib
import urllib2
import urlparse
import uuid
import gevent
class Task(object):
def __init__(self, queue_name, content_type, body):
self.queue_name = queue_name
if content_type == 'application/json':
data = json.loads(body... | 0.27048 | 0.101947 |
import json
import os
import torch
from torch.nn import functional as F
from transformers import BartTokenizer, BartForConditionalGeneration
from transformers import T5Tokenizer, T5ForConditionalGeneration
from trainer.models.base import SummarizationModel
class ConditionalGenerationSummarizer(SummarizationModel):
... | trainer/models/conditional_generation.py | import json
import os
import torch
from torch.nn import functional as F
from transformers import BartTokenizer, BartForConditionalGeneration
from transformers import T5Tokenizer, T5ForConditionalGeneration
from trainer.models.base import SummarizationModel
class ConditionalGenerationSummarizer(SummarizationModel):
... | 0.784443 | 0.264127 |
import datetime
import random
import authlib.jose.errors as JWTErrors
import pymongo
import requests
from authlib.jose import JsonWebToken, JWTClaims
from modules.common import base58, conf, log
# DB정보 불러오기
connection = pymongo.MongoClient(conf.configs['DataBase']['ConnectString'])
db = connection.hdmeal
utterances_c... | modules/common/security.py |
import datetime
import random
import authlib.jose.errors as JWTErrors
import pymongo
import requests
from authlib.jose import JsonWebToken, JWTClaims
from modules.common import base58, conf, log
# DB정보 불러오기
connection = pymongo.MongoClient(conf.configs['DataBase']['ConnectString'])
db = connection.hdmeal
utterances_c... | 0.28279 | 0.161849 |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from .soed import SOED
from .utils import *
class PGsOED(SOED):
"""
A class for solving sequential optimal experimental design (sOED) problems
using policy gradient (PG) method. This class is based on the SOED class,
an... | sOED/pg_soed.py | import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from .soed import SOED
from .utils import *
class PGsOED(SOED):
"""
A class for solving sequential optimal experimental design (sOED) problems
using policy gradient (PG) method. This class is based on the SOED class,
an... | 0.850593 | 0.76454 |
# This file is part of CbM (https://github.com/ec-jrc/cbm).
# Author : <NAME>
# Credits : GTCAP Team
# Copyright : 2021 European Commission, Joint Research Centre
# License : 3-Clause BSD
import os
import glob
from ipywidgets import (Text, Label, HBox, VBox, Layout, Dropdown,
ToggleBut... | cbm/ipycbm/ipy_foi/foi_panel.py |
# This file is part of CbM (https://github.com/ec-jrc/cbm).
# Author : <NAME>
# Credits : GTCAP Team
# Copyright : 2021 European Commission, Joint Research Centre
# License : 3-Clause BSD
import os
import glob
from ipywidgets import (Text, Label, HBox, VBox, Layout, Dropdown,
ToggleBut... | 0.47658 | 0.196884 |
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('cl_app', '0005_auto_20160630_1741'),
]
operations = [
migrations.AddField(
model_name='city',
name='description',
field=models.TextField(bla... | cl_app/migrations/0006_auto_20220313_2316.py |
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('cl_app', '0005_auto_20160630_1741'),
]
operations = [
migrations.AddField(
model_name='city',
name='description',
field=models.TextField(bla... | 0.597373 | 0.113236 |
import re
from datetime import datetime
from subprocess import Popen, PIPE, TimeoutExpired
from textops import find
import os
import time
from enum import Enum
from termcolor import colored
class LogSeverity(Enum):
SUCCESS = "Success"
WARNING = "Warning"
INFO = "Info"
ERROR = "Error"
FATAL = "Fat... | anadroid/utils/Utils.py | import re
from datetime import datetime
from subprocess import Popen, PIPE, TimeoutExpired
from textops import find
import os
import time
from enum import Enum
from termcolor import colored
class LogSeverity(Enum):
SUCCESS = "Success"
WARNING = "Warning"
INFO = "Info"
ERROR = "Error"
FATAL = "Fat... | 0.264358 | 0.076304 |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .forms import PangeaUserCreationForm, PangeaUserChangeForm
from .models import (
PangeaUser,
Organization,
Project,
S3ApiKey,
S3Bucket,
S3Provider,
S... | pangea/core/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .forms import PangeaUserCreationForm, PangeaUserChangeForm
from .models import (
PangeaUser,
Organization,
Project,
S3ApiKey,
S3Bucket,
S3Provider,
S... | 0.575349 | 0.075041 |
import os
import numpy as np
import pandas as pd
from kgcnn.data.moleculenet import MoleculeNetDataset
from kgcnn.mol.molgraph import MolecularGraphRDKit, OneHotEncoder
from kgcnn.utils.data import save_json_file
import rdkit.Chem as Chem
class ESOLDataset(MoleculeNetDataset):
"""Store and process full ESOL dat... | kgcnn/data/datasets/ESOL.py | import os
import numpy as np
import pandas as pd
from kgcnn.data.moleculenet import MoleculeNetDataset
from kgcnn.mol.molgraph import MolecularGraphRDKit, OneHotEncoder
from kgcnn.utils.data import save_json_file
import rdkit.Chem as Chem
class ESOLDataset(MoleculeNetDataset):
"""Store and process full ESOL dat... | 0.670069 | 0.2205 |
import os
import subprocess
import argparse
from tqdm import tqdm
from iPERCore.services.options.options_setup import setup
from iPERCore.services.options.process_info import ProcessInfo
from iPERCore.services.preprocess import human_estimate, digital_deform
from iPERCore.tools.utils.filesio.persistence import mkdir
... | scripts/train/prepare_iPER_dataset.py | import os
import subprocess
import argparse
from tqdm import tqdm
from iPERCore.services.options.options_setup import setup
from iPERCore.services.options.process_info import ProcessInfo
from iPERCore.services.preprocess import human_estimate, digital_deform
from iPERCore.tools.utils.filesio.persistence import mkdir
... | 0.187207 | 0.072571 |
import datetime
import traceback
from typing import Callable, Union
import nltk
from selenium import webdriver
from selenium.common.exceptions import (
InvalidArgumentException,
InvalidSelectorException,
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
)
from selenium.webdr... | notino_scraper/scraper.py | import datetime
import traceback
from typing import Callable, Union
import nltk
from selenium import webdriver
from selenium.common.exceptions import (
InvalidArgumentException,
InvalidSelectorException,
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
)
from selenium.webdr... | 0.553023 | 0.177704 |
from .resource import Resource
class MediaService(Resource):
"""The properties of a Media Service resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: The id of the resource.
:vartype id: str
:ivar name: The name of the resource.
:v... | azure-mgmt-media/azure/mgmt/media/models/media_service.py |
from .resource import Resource
class MediaService(Resource):
"""The properties of a Media Service resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: The id of the resource.
:vartype id: str
:ivar name: The name of the resource.
:v... | 0.890318 | 0.293348 |
from __future__ import print_function
from numpy import pi, cos, sin, arctan2, sqrt, square, radians
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import math
import time
class PersonFinder():
def __init__(self, steer... | car/wp_parts/personFinder.py | from __future__ import print_function
from numpy import pi, cos, sin, arctan2, sqrt, square, radians
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import math
import time
class PersonFinder():
def __init__(self, steer... | 0.383757 | 0.348742 |
import falcon
import murmurhash
import numpy as np
import scipy.spatial
from corpus_index.base_index import Aggregation
from db.models import Sentence
from resources.base import get_raw_sentences_from_payload, CovidResource
class CovidSimilarityResource(CovidResource):
"""Corpus Semantic Search.
{ '... | src/resources/similarity.py |
import falcon
import murmurhash
import numpy as np
import scipy.spatial
from corpus_index.base_index import Aggregation
from db.models import Sentence
from resources.base import get_raw_sentences_from_payload, CovidResource
class CovidSimilarityResource(CovidResource):
"""Corpus Semantic Search.
{ '... | 0.442155 | 0.254891 |
import argparse
import glob
import re
from netCDF4 import Dataset
try:
from progress.bar import PixelBar
except ImportError:
from .progress.bar import PixelBar
class CustomProgress(PixelBar):
message = 'Adding reprocessing hidory: '
suffix = '%(percent).1f%% eta:%(eta)ds - elapsed:%(elapsed)ds'
de... | add_dqr_rid.py |
import argparse
import glob
import re
from netCDF4 import Dataset
try:
from progress.bar import PixelBar
except ImportError:
from .progress.bar import PixelBar
class CustomProgress(PixelBar):
message = 'Adding reprocessing hidory: '
suffix = '%(percent).1f%% eta:%(eta)ds - elapsed:%(elapsed)ds'
de... | 0.321886 | 0.104569 |
import numpy as np
import torch
import torch.nn as nn
import torchtestcase
import unittest
from survae.transforms.bijections.autoregressive import *
from survae.nn.layers.autoregressive import SpatialMaskedConv2d, MaskedConv2d
from survae.nn.layers import ElementwiseParams, ElementwiseParams2d
from survae.tests.transfo... | survae/tests/transforms/bijections/autoregressive/autoregressive_linear_2d.py | import numpy as np
import torch
import torch.nn as nn
import torchtestcase
import unittest
from survae.transforms.bijections.autoregressive import *
from survae.nn.layers.autoregressive import SpatialMaskedConv2d, MaskedConv2d
from survae.nn.layers import ElementwiseParams, ElementwiseParams2d
from survae.tests.transfo... | 0.8156 | 0.67015 |
from __future__ import division
import os
from os.path import abspath, expanduser, join, dirname, pardir
from yaml import load as load_yaml
from ngs_utils.config import load_yaml_config, fill_dict_from_defaults
from ngs_utils.file_utils import verify_file, verify_module, adjust_path
from ngs_utils.logger import info, ... | vcf_stuff/filtering/ngs_reporting/config.py | from __future__ import division
import os
from os.path import abspath, expanduser, join, dirname, pardir
from yaml import load as load_yaml
from ngs_utils.config import load_yaml_config, fill_dict_from_defaults
from ngs_utils.file_utils import verify_file, verify_module, adjust_path
from ngs_utils.logger import info, ... | 0.487551 | 0.142232 |
import os
import click
import gocardless_pro
import pytz
import csv
from dateutil.parser import parse as parse_datetime
from datetime import date, timedelta
from collections import defaultdict
def parse_date(date_str):
# Not using dateutil here as sometimes it thinks you've got an
# American date format when ... | lhs_accounting_tools/scripts/gocardless_journals.py | import os
import click
import gocardless_pro
import pytz
import csv
from dateutil.parser import parse as parse_datetime
from datetime import date, timedelta
from collections import defaultdict
def parse_date(date_str):
# Not using dateutil here as sometimes it thinks you've got an
# American date format when ... | 0.500977 | 0.231354 |
import os
import sys
from django.conf import settings
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x
)
sandbox = lambda x: location("sandbox/%s" % x)
sys.path.insert(0, location('sandbox'))
from oscar import get_core_apps
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from oscar.de... | conftest.py | import os
import sys
from django.conf import settings
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x
)
sandbox = lambda x: location("sandbox/%s" % x)
sys.path.insert(0, location('sandbox'))
from oscar import get_core_apps
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from oscar.de... | 0.152032 | 0.059537 |
import os
import nibabel as nib
import cv2
import numpy as np
from pathlib import Path
home = str(Path.home())
path_data = input ('Please specify the path for the defaced dataset: \n')
output_path = input ('Please specify the path for the qc report output folder: \n')
if not os.path.isdir(output_path):
os.makedi... | spinegeneric/cli/qc_bids_deface.py |
import os
import nibabel as nib
import cv2
import numpy as np
from pathlib import Path
home = str(Path.home())
path_data = input ('Please specify the path for the defaced dataset: \n')
output_path = input ('Please specify the path for the qc report output folder: \n')
if not os.path.isdir(output_path):
os.makedi... | 0.174656 | 0.155687 |
import numpy as np
from pandas import DataFrame
import utils
import eval_utils
import os
from typing import Dict, List, Tuple
import SpacePair
import exp_unsup
def read_3clusters(filenme:str) -> (List[str], List[str]):
dis_words = []
tech_words = []
with open(filenme, "r") as f:
lines = f.read... | exp_distech.py | import numpy as np
from pandas import DataFrame
import utils
import eval_utils
import os
from typing import Dict, List, Tuple
import SpacePair
import exp_unsup
def read_3clusters(filenme:str) -> (List[str], List[str]):
dis_words = []
tech_words = []
with open(filenme, "r") as f:
lines = f.read... | 0.57069 | 0.423696 |
import pytest
import numpy as np
import os, sys
os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../..')
from tests.embeddings_pipelines.model.test_pipelines import AbstractTestEmbeddingPipeline
sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../../src') )
from embeddings_p... | playground/oliver_ilnicki/embeddings_pipelines/tests/embeddings_pipelines/pipelines/test_three_stages_pipelines.py | import pytest
import numpy as np
import os, sys
os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../..')
from tests.embeddings_pipelines.model.test_pipelines import AbstractTestEmbeddingPipeline
sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../../src') )
from embeddings_p... | 0.372163 | 0.159119 |
morse_alphabets ={
"A" : ".-",
"B" : "-...",
"C" : "-.-.",
"D" : "-..",
"E" : ".",
"F" : "..-.",
"G" : "--.",
"H" : "....",
"I" : "..",
"J" : ".---",
"K" : "-.-",
"L" : ".-..",
"M" : "--",
"N" : "-.",
... | Python/Morse-Encode-Decode/morse_encode_decode.py | morse_alphabets ={
"A" : ".-",
"B" : "-...",
"C" : "-.-.",
"D" : "-..",
"E" : ".",
"F" : "..-.",
"G" : "--.",
"H" : "....",
"I" : "..",
"J" : ".---",
"K" : "-.-",
"L" : ".-..",
"M" : "--",
"N" : "-.",
... | 0.342681 | 0.474205 |
from Jumpscale import j
from .JSWebServer import JSWebServer
JSConfigBase = j.baseclasses.object_config_collection
class JSWebServers(JSConfigBase):
__jslocation__ = "j.servers.flask"
def _init(self, **kwargs):
self.latest = None
def get(self, port):
"""
will return server which... | sandbox/lib/jumpscale/JumpscaleLibsExtra/servers/flaskserver/JSWebServers.py | from Jumpscale import j
from .JSWebServer import JSWebServer
JSConfigBase = j.baseclasses.object_config_collection
class JSWebServers(JSConfigBase):
__jslocation__ = "j.servers.flask"
def _init(self, **kwargs):
self.latest = None
def get(self, port):
"""
will return server which... | 0.453504 | 0.093223 |
import re
import pandas as pd
import numpy as np
class Extract_Commands():
# 提取微博评论的内容
def __init__(self, content):
super(Extract_Commands, self).__init__()
self.content = content
if content == '':
raise Exception('评论内容为空')
def clear_quotation(self):
if self.co... | code/utils.py | import re
import pandas as pd
import numpy as np
class Extract_Commands():
# 提取微博评论的内容
def __init__(self, content):
super(Extract_Commands, self).__init__()
self.content = content
if content == '':
raise Exception('评论内容为空')
def clear_quotation(self):
if self.co... | 0.296349 | 0.244656 |
from io import StringIO
from pathlib import Path
from typing import Iterable, NamedTuple, TextIO
import click
from fasta_reader import FASTAItem, FASTAWriter, read_fasta
from hmmer import HMMER
from hmmer_reader import num_models, open_hmmer
from imm import Alphabet
from nmm import IUPACAminoAlphabet
from tqdm import ... | iseq/_cli/pscan3.py | from io import StringIO
from pathlib import Path
from typing import Iterable, NamedTuple, TextIO
import click
from fasta_reader import FASTAItem, FASTAWriter, read_fasta
from hmmer import HMMER
from hmmer_reader import num_models, open_hmmer
from imm import Alphabet
from nmm import IUPACAminoAlphabet
from tqdm import ... | 0.851506 | 0.243418 |
from datetime import datetime
class Competition:
def __init__(self, initDict):
parsedDict = {k: parse(v) for k, v in initDict.items()}
self.__dict__.update(parsedDict)
self.tags = [Tag(t) for t in self.tags]
def __repr__(self):
return self.ref
class SubmitResult:
def __init__(self,... | kaggle/models/kaggle_models_extended.py | from datetime import datetime
class Competition:
def __init__(self, initDict):
parsedDict = {k: parse(v) for k, v in initDict.items()}
self.__dict__.update(parsedDict)
self.tags = [Tag(t) for t in self.tags]
def __repr__(self):
return self.ref
class SubmitResult:
def __init__(self,... | 0.594669 | 0.225406 |
try:
import ssl
SSL_AVAILABLE = True
except:
SSL_AVAILABLE = False
import sys
import socket
import logging
import uuid
import platform
from functools import wraps
from .authentication import (MySQL41AuthPlugin, PlainAuthPlugin,
Sha256MemoryAuthPlugin)
from .errors import Inte... | external/mysql/mysql-connector-python-8.0.11/lib/mysqlx/connection.py | try:
import ssl
SSL_AVAILABLE = True
except:
SSL_AVAILABLE = False
import sys
import socket
import logging
import uuid
import platform
from functools import wraps
from .authentication import (MySQL41AuthPlugin, PlainAuthPlugin,
Sha256MemoryAuthPlugin)
from .errors import Inte... | 0.643105 | 0.062732 |
import torch.nn.functional as F
import numpy as np
import torch
import torch.nn as nn
layer_configs = [
# Unit1 (2)
(32, 3, True),
(64, 3, True),
# Unit2 (3)
(128, 3, False),
(64, 1, False),
(128, 3, True),
# Unit3 (3)
(256, 3, False),
(128, 1, False),
(256, 3, True),
# ... | yolo/darknet.py | import torch.nn.functional as F
import numpy as np
import torch
import torch.nn as nn
layer_configs = [
# Unit1 (2)
(32, 3, True),
(64, 3, True),
# Unit2 (3)
(128, 3, False),
(64, 1, False),
(128, 3, True),
# Unit3 (3)
(256, 3, False),
(128, 1, False),
(256, 3, True),
# ... | 0.921341 | 0.487124 |
import colorise.nix.cluts
from colorise.attributes import Attr
from colorise.color_tools import closest_color
from colorise.win.win32_functions import (
can_interpret_ansi,
can_redefine_colors,
get_windows_clut,
)
# Character attributes as defined in wincon.h
# We cannot get these through ctypes since they... | src/colorise/win/cluts.py | import colorise.nix.cluts
from colorise.attributes import Attr
from colorise.color_tools import closest_color
from colorise.win.win32_functions import (
can_interpret_ansi,
can_redefine_colors,
get_windows_clut,
)
# Character attributes as defined in wincon.h
# We cannot get these through ctypes since they... | 0.744656 | 0.195153 |
import time
import socket
from contextlib import closing
from threading import Thread
import pssst
import click
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
@click.command()
@click.option('-k', '--public_key', required=True, help="Hex-encoded public key")
@click.option('-K', '--cli... | examples/echo_client.py | import time
import socket
from contextlib import closing
from threading import Thread
import pssst
import click
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
@click.command()
@click.option('-k', '--public_key', required=True, help="Hex-encoded public key")
@click.option('-K', '--cli... | 0.225929 | 0.092155 |
import sys, os, shutil, re, argparse, json
from codecs import open
from itertools import izip
from collections import defaultdict
class Record(object):
def __init__(self):
pass
def add_info(self, line):
m = re.match(r'iter=(\S*): example (\d+)/\d+: (\S+) {', line)
if m:
se... | tables/log-parsers/get-error-analysis.py |
import sys, os, shutil, re, argparse, json
from codecs import open
from itertools import izip
from collections import defaultdict
class Record(object):
def __init__(self):
pass
def add_info(self, line):
m = re.match(r'iter=(\S*): example (\d+)/\d+: (\S+) {', line)
if m:
se... | 0.256739 | 0.109491 |
import os
import ray
import json
import tqdm
import torch
import logging
from typing import List
logger = logging.getLogger(__name__)
@ray.remote
def _process(tokenizer, lines: List[str], rank: int):
"""
Args:
tokenizer: huggingface's style tokenizer
lines: jsonl line. with the key "sents"
... | tests/text_loader/full_doc_loader.py | import os
import ray
import json
import tqdm
import torch
import logging
from typing import List
logger = logging.getLogger(__name__)
@ray.remote
def _process(tokenizer, lines: List[str], rank: int):
"""
Args:
tokenizer: huggingface's style tokenizer
lines: jsonl line. with the key "sents"
... | 0.63023 | 0.144692 |
# Author: <NAME> <<EMAIL>>
# License: BSD 2 clause
from __future__ import division
from __future__ import print_function
import numbers
from warnings import warn
import numpy as np
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from sklearn.metrics import euclidean_distanc... | pyod/models/inne.py | # Author: <NAME> <<EMAIL>>
# License: BSD 2 clause
from __future__ import division
from __future__ import print_function
import numbers
from warnings import warn
import numpy as np
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from sklearn.metrics import euclidean_distanc... | 0.954916 | 0.650634 |
import copy
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_adapt.hooks import ADDAHook, BSPHook, validate_hook
from pytorch_adapt.utils import common_functions as c_f
from .utils import (
Net,
assertRequiresGrad,
get_opts,
post_g_hook_update_keys,
pos... | tests/hooks/test_adda.py | import copy
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_adapt.hooks import ADDAHook, BSPHook, validate_hook
from pytorch_adapt.utils import common_functions as c_f
from .utils import (
Net,
assertRequiresGrad,
get_opts,
post_g_hook_update_keys,
pos... | 0.739986 | 0.512083 |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.ex... | spark_auto_mapper_fhir/backbone_elements/contract_content_definition.py | from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.ex... | 0.905341 | 0.223441 |
import tensorflow as tf
import baselines.common.tf_util as U
def scope_vars(scope, trainable_only=False):
"""
Get variables inside a scope
The scope can be specified as a string
Parameters
----------
scope: str or VariableScope
scope in which the variables reside.
trainable_only: b... | brl_baselines/bqn/util.py | import tensorflow as tf
import baselines.common.tf_util as U
def scope_vars(scope, trainable_only=False):
"""
Get variables inside a scope
The scope can be specified as a string
Parameters
----------
scope: str or VariableScope
scope in which the variables reside.
trainable_only: b... | 0.918092 | 0.465509 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import mesh_tensorflow as mtf
from mesh_tensorflow.transformer import attention
from mesh_tensorflow.transformer import transformer
import tensorflow as tf
class DenseReluDense(transformer.Trans... | mesh_tensorflow/transformer/transformer_layers.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import mesh_tensorflow as mtf
from mesh_tensorflow.transformer import attention
from mesh_tensorflow.transformer import transformer
import tensorflow as tf
class DenseReluDense(transformer.Trans... | 0.955277 | 0.396243 |
import pymysql
import pymysql.cursors
# Establishing connection with the database
try:
connection = pymysql.connect(host='<host>',
user='<userName>',
password='<password>')
cursor = connection.cursor()
except:
print("Connectio... | code-samples/pymysql_sample.py |
import pymysql
import pymysql.cursors
# Establishing connection with the database
try:
connection = pymysql.connect(host='<host>',
user='<userName>',
password='<password>')
cursor = connection.cursor()
except:
print("Connectio... | 0.252292 | 0.19544 |
# Metodo Newton Raphson - Una sola variable.
"""
El método de Newton-Raphson es de mis favoritos.
Es divertido de programar e invloucra un poco
mas de matematica.
Descripcion: Este metodo busca la convergencia rapida de
de algun valor. Para esto, utiliza derivadas
... | Newton-Raphson_una_variable.py |
# Metodo Newton Raphson - Una sola variable.
"""
El método de Newton-Raphson es de mis favoritos.
Es divertido de programar e invloucra un poco
mas de matematica.
Descripcion: Este metodo busca la convergencia rapida de
de algun valor. Para esto, utiliza derivadas
... | 0.589716 | 0.76882 |
from rsapy.util import generate_primes
import sys
import math
import base64
import time
import asn1
class KeyNotFoundError(Exception):
pass
class RSAKey:
"""
@brief parent class for Private and Public Keys.
Not meant to be used directly
"""
def __init__(self, modulus:int, exponent:int):
... | rsapy/encryptor.py | from rsapy.util import generate_primes
import sys
import math
import base64
import time
import asn1
class KeyNotFoundError(Exception):
pass
class RSAKey:
"""
@brief parent class for Private and Public Keys.
Not meant to be used directly
"""
def __init__(self, modulus:int, exponent:int):
... | 0.513425 | 0.239094 |
import logging
import numpy as np
from stable_baselines3.common.vec_env import VecEnvWrapper
from stable_baselines3.common.vec_env.base_vec_env import (
VecEnvObs,
VecEnvStepReturn,
VecEnv,
)
class VecHardGoalSampleWrapper(VecEnvWrapper):
def __init__(self, venv: VecEnv, alpha: float = 0.65):
... | gym_gathering/wrappers/sample_hard_goals.py | import logging
import numpy as np
from stable_baselines3.common.vec_env import VecEnvWrapper
from stable_baselines3.common.vec_env.base_vec_env import (
VecEnvObs,
VecEnvStepReturn,
VecEnv,
)
class VecHardGoalSampleWrapper(VecEnvWrapper):
def __init__(self, venv: VecEnv, alpha: float = 0.65):
... | 0.614857 | 0.209652 |
import logging
import rdflib
from rdflib import URIRef, Graph
from OTLMOW.ModelGenerator.AbstractDatatypeCreator import AbstractDatatypeCreator
from OTLMOW.ModelGenerator.OSLOCollector import OSLOCollector
from OTLMOW.ModelGenerator.OSLOEnumeration import OSLOEnumeration
from OTLMOW.ModelGenerator.StringHelper import ... | src/OTLMOW/ModelGenerator/OTLEnumerationCreator.py | import logging
import rdflib
from rdflib import URIRef, Graph
from OTLMOW.ModelGenerator.AbstractDatatypeCreator import AbstractDatatypeCreator
from OTLMOW.ModelGenerator.OSLOCollector import OSLOCollector
from OTLMOW.ModelGenerator.OSLOEnumeration import OSLOEnumeration
from OTLMOW.ModelGenerator.StringHelper import ... | 0.431704 | 0.12552 |
from __future__ import division, unicode_literals
from builtins import object
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
class DataEncoder(object):
def __init__(self, class_column='class', feature_columns=None):
self.class_column = class_column
self.feature_... | atm/encoder.py | from __future__ import division, unicode_literals
from builtins import object
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
class DataEncoder(object):
def __init__(self, class_column='class', feature_columns=None):
self.class_column = class_column
self.feature_... | 0.868771 | 0.444022 |
def stage(ctx):
return {
"parent": "Build",
"triggers": {
"manual": True,
},
"parameters": [],
"configs": [],
"jobs": [{
"name": "publish",
"timeout": 600,
"steps": [{
"tool": "artifacts",
... | .kraken/publish.py | def stage(ctx):
return {
"parent": "Build",
"triggers": {
"manual": True,
},
"parameters": [],
"configs": [],
"jobs": [{
"name": "publish",
"timeout": 600,
"steps": [{
"tool": "artifacts",
... | 0.363308 | 0.28336 |
import torch
from torch import nn
from torch.nn import functional as F
class AttentionPooling(nn.Module):
def __init__(self, key_size, *query_sizes, attn_size=75, batch_first=False):
super().__init__()
self.key_linear = nn.Linear(key_size, attn_size, bias=False)
self.query_linears = nn.Mod... | modules/attention.py | import torch
from torch import nn
from torch.nn import functional as F
class AttentionPooling(nn.Module):
def __init__(self, key_size, *query_sizes, attn_size=75, batch_first=False):
super().__init__()
self.key_linear = nn.Linear(key_size, attn_size, bias=False)
self.query_linears = nn.Mod... | 0.924688 | 0.382718 |
from collections import namedtuple
from . import builder, cc, msvc
from .. import log
from .common import choose_builder, make_command_converter_pair
from ..languages import known_formats, known_langs
_guessed_info = namedtuple('_guessed_info', ['lang', 'cmd', 'guessed_cmd'])
with known_langs.make('c') as x:
x.v... | bfg9000/tools/c_family.py | from collections import namedtuple
from . import builder, cc, msvc
from .. import log
from .common import choose_builder, make_command_converter_pair
from ..languages import known_formats, known_langs
_guessed_info = namedtuple('_guessed_info', ['lang', 'cmd', 'guessed_cmd'])
with known_langs.make('c') as x:
x.v... | 0.574992 | 0.106041 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Creat... | bdn/messaging/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Creat... | 0.513425 | 0.090977 |
import os
import shutil
from distutils.spawn import find_executable
from conans import ConanFile, tools, VisualStudioBuildEnvironment
from conans.tools import cpu_count
import pkgconf
class QtConan(ConanFile):
name = "Qt"
version = pkgconf.packageVersion
description = "Conan.io package for Qt library."
... | conanfile.py | import os
import shutil
from distutils.spawn import find_executable
from conans import ConanFile, tools, VisualStudioBuildEnvironment
from conans.tools import cpu_count
import pkgconf
class QtConan(ConanFile):
name = "Qt"
version = pkgconf.packageVersion
description = "Conan.io package for Qt library."
... | 0.124959 | 0.118819 |
from __future__ import unicode_literals
from django import forms
from django.db.models.functions import Lower
from django.utils.translation import ugettext_lazy as _
from tracpro.charts import filters
from tracpro.contacts.models import Contact
from tracpro.polls.models import Poll, Question
from .models import Base... | tracpro/baseline/forms.py | from __future__ import unicode_literals
from django import forms
from django.db.models.functions import Lower
from django.utils.translation import ugettext_lazy as _
from tracpro.charts import filters
from tracpro.contacts.models import Contact
from tracpro.polls.models import Poll, Question
from .models import Base... | 0.808861 | 0.112624 |
from __future__ import print_function
import glob, re, os, os.path, shutil, string, sys, argparse, traceback, multiprocessing
from subprocess import check_call, check_output, CalledProcessError
IPHONEOS_DEPLOYMENT_TARGET='9.0' # default, can be changed via command line options or environment variable
def execute(cmd... | platforms/ios/run_tests.py | from __future__ import print_function
import glob, re, os, os.path, shutil, string, sys, argparse, traceback, multiprocessing
from subprocess import check_call, check_output, CalledProcessError
IPHONEOS_DEPLOYMENT_TARGET='9.0' # default, can be changed via command line options or environment variable
def execute(cmd... | 0.297266 | 0.055515 |
from typing import List, Union
from collections import defaultdict
import fitz
from fitz import Page
from fitz.utils import getColor, getColorList
import numpy as np
from indico_toolkit.association import ExtractedTokens
from indico_toolkit.pipelines import FileProcessing
from indico_toolkit.types import Extractions
f... | indico_toolkit/highlighter/highlighter.py | from typing import List, Union
from collections import defaultdict
import fitz
from fitz import Page
from fitz.utils import getColor, getColorList
import numpy as np
from indico_toolkit.association import ExtractedTokens
from indico_toolkit.pipelines import FileProcessing
from indico_toolkit.types import Extractions
f... | 0.674158 | 0.356615 |
from numpy import random
from sequence.entanglement_management.entanglement_protocol import EntanglementProtocol
random.seed(0)
from sequence.kernel.timeline import Timeline
from sequence.topology.node import Node
from sequence.components.memory import Memory
from sequence.components.optical_channel import ClassicalC... | docs/source/tutorial/chapter3/example2.py | from numpy import random
from sequence.entanglement_management.entanglement_protocol import EntanglementProtocol
random.seed(0)
from sequence.kernel.timeline import Timeline
from sequence.topology.node import Node
from sequence.components.memory import Memory
from sequence.components.optical_channel import ClassicalC... | 0.486088 | 0.140572 |
import sys
import pygame
# 游戏地图选择界面
class MapChoiceInterface(pygame.sprite.Sprite):
def __init__(self, WIDTH, HEIGHT):
pygame.sprite.Sprite.__init__(self)
self.imgs = ['./resource/imgs/choice/load_game.png']
self.image = pygame.image.load(self.imgs[0]).convert()
self.rect = self.image.get_rect()
self.rect.... | Game8/interface/CHOICE.py | import sys
import pygame
# 游戏地图选择界面
class MapChoiceInterface(pygame.sprite.Sprite):
def __init__(self, WIDTH, HEIGHT):
pygame.sprite.Sprite.__init__(self)
self.imgs = ['./resource/imgs/choice/load_game.png']
self.image = pygame.image.load(self.imgs[0]).convert()
self.rect = self.image.get_rect()
self.rect.... | 0.052014 | 0.282349 |
import controller
import copy
import test_controller
import time
import json
from flask import Flask
from flask_socketio import SocketIO, send
import sys
import os
import webbrowser
print("Starting up...")
# check if we're in testing mode
testing = False
if len(sys.argv) == 2:
if sys.argv[1] == "test":
pr... | test.py | import controller
import copy
import test_controller
import time
import json
from flask import Flask
from flask_socketio import SocketIO, send
import sys
import os
import webbrowser
print("Starting up...")
# check if we're in testing mode
testing = False
if len(sys.argv) == 2:
if sys.argv[1] == "test":
pr... | 0.220426 | 0.079531 |
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('recipe_features', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operat... | backend/recipe_backend/recipe_features/migrations/0002_initial.py |
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('recipe_features', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operat... | 0.559049 | 0.104249 |
import tensorflow as tf
import numpy as np
import time
from models import VAE
from models_mvtec import VAE as VAE_MVTEC
from utils.plotting import (generate_and_save_images,
generate_and_save_training,
save_training_curves)
from utils.training import print_epo... | architectures/vae.py | import tensorflow as tf
import numpy as np
import time
from models import VAE
from models_mvtec import VAE as VAE_MVTEC
from utils.plotting import (generate_and_save_images,
generate_and_save_training,
save_training_curves)
from utils.training import print_epo... | 0.727879 | 0.389024 |
import time
from random import choice, random
from collections import deque
import pickle
class flappy_agent():
def __init__(self,sample_interval=8):
# agent sample interval (frames)
self.iteration=0
self.game_number=0
self.n_iterations=300 # after which the epsilon is forced to zero
self.n_max_step=100 # l... | flappy_agent_v3_Naive_Qlearn.py | import time
from random import choice, random
from collections import deque
import pickle
class flappy_agent():
def __init__(self,sample_interval=8):
# agent sample interval (frames)
self.iteration=0
self.game_number=0
self.n_iterations=300 # after which the epsilon is forced to zero
self.n_max_step=100 # l... | 0.135032 | 0.146728 |
import sqlite3
from unidecode import unidecode
from preprocessing import process_text, add_new_column
#Feature engineering #1: Count number of authors per publication
def count_number_of_entity(table1, table2, entity):
con = sqlite3.connect('demosaurus.sqlite')
cur = con.cursor()
column_name = add_... | dataprocessing/Nizarsrc/engineer_features.py | import sqlite3
from unidecode import unidecode
from preprocessing import process_text, add_new_column
#Feature engineering #1: Count number of authors per publication
def count_number_of_entity(table1, table2, entity):
con = sqlite3.connect('demosaurus.sqlite')
cur = con.cursor()
column_name = add_... | 0.196055 | 0.116814 |
from empstore import teams
import employee as emp
from empstore import employees
def manage_all_team_menu():
print("\t1.Create team")
print("\t2.Display team")
print("\t3.Manage team(Particular)")
print("\t4.Delete team")
print("\t5.Exit")
def manage_all_teams():
while True:
manage_all_team_menu()
ch = int(i... | teams.py | from empstore import teams
import employee as emp
from empstore import employees
def manage_all_team_menu():
print("\t1.Create team")
print("\t2.Display team")
print("\t3.Manage team(Particular)")
print("\t4.Delete team")
print("\t5.Exit")
def manage_all_teams():
while True:
manage_all_team_menu()
ch = int(i... | 0.041803 | 0.151686 |
import common
import wcodegen
class PerlCodeGenerator(wcodegen.PerlWidgetCodeWriter):
def get_code(self, obj):
id_name, id = self.codegen.generate_code_id(obj)
parent = self.format_widget_access(obj.parent)
init = []
if id_name:
init.append(id_name)
klass = ob... | Libraries/Python/wxGlade/v0.9,5/wxGlade-0.9.5-py3.6.egg/wxglade/widgets/grid/perl_codegen.py | import common
import wcodegen
class PerlCodeGenerator(wcodegen.PerlWidgetCodeWriter):
def get_code(self, obj):
id_name, id = self.codegen.generate_code_id(obj)
parent = self.format_widget_access(obj.parent)
init = []
if id_name:
init.append(id_name)
klass = ob... | 0.158923 | 0.065755 |
import re
import gensim
import os
import itertools
import numpy as np
import argparse
import string
from nltk.corpus import stopwords
import glob
from bs4 import BeautifulSoup
from mycounter import Counter
import math
import pickle
from sklearn.metrics import pairwise
from nltk.stem import WordNetLemmatiz... | data/external/repositories/227799/Allen_AI_Kaggle-master/genlemmas.py | import re
import gensim
import os
import itertools
import numpy as np
import argparse
import string
from nltk.corpus import stopwords
import glob
from bs4 import BeautifulSoup
from mycounter import Counter
import math
import pickle
from sklearn.metrics import pairwise
from nltk.stem import WordNetLemmatiz... | 0.075489 | 0.050635 |
"""Package for node ORM classes."""
import datetime
from functools import cached_property
from logging import Logger
from typing import TYPE_CHECKING, Any, ClassVar, Generic, Iterator, List, Optional, Tuple, Type, TypeVar
from uuid import UUID
from aiida.common import exceptions
from aiida.common.lang import classprop... | aiida/orm/nodes/node.py | """Package for node ORM classes."""
import datetime
from functools import cached_property
from logging import Logger
from typing import TYPE_CHECKING, Any, ClassVar, Generic, Iterator, List, Optional, Tuple, Type, TypeVar
from uuid import UUID
from aiida.common import exceptions
from aiida.common.lang import classprop... | 0.940127 | 0.227276 |
import sys
import spacy
def create_ngrams(list_words, minimum_length=4, maximum_length=10):
ngrams=[]
if len(list_words)>=minimum_length:
for start in range(0, len(list_words)-minimum_length+1):
for length in range(minimum_length, len(list_words)-start+1):
if length>maximum... | extraction.py | import sys
import spacy
def create_ngrams(list_words, minimum_length=4, maximum_length=10):
ngrams=[]
if len(list_words)>=minimum_length:
for start in range(0, len(list_words)-minimum_length+1):
for length in range(minimum_length, len(list_words)-start+1):
if length>maximum... | 0.113028 | 0.149718 |
from metaflow import step, current, FlowSpec, Parameter, card, resources
import os
class NBFlow(FlowSpec):
"""
MLCode is taken from this tutorial: https://keras.io/examples/nlp/text_classification_from_scratch/
"""
@classmethod
def get_tune_data(cls, search_clf):
"""Extract results of hype... | examples/random_forest/flow.py | from metaflow import step, current, FlowSpec, Parameter, card, resources
import os
class NBFlow(FlowSpec):
"""
MLCode is taken from this tutorial: https://keras.io/examples/nlp/text_classification_from_scratch/
"""
@classmethod
def get_tune_data(cls, search_clf):
"""Extract results of hype... | 0.751192 | 0.436442 |
from django.db import models
from ctrack.caf.models import CAF
from ctrack.organisations.models import Person
class CAFAssessment(models.Model):
caf = models.ForeignKey(CAF, on_delete=models.CASCADE)
completer = models.ForeignKey(Person, on_delete=models.CASCADE)
comments = models.TextField(max_length=50... | ctrack/assessments/models.py | from django.db import models
from ctrack.caf.models import CAF
from ctrack.organisations.models import Person
class CAFAssessment(models.Model):
caf = models.ForeignKey(CAF, on_delete=models.CASCADE)
completer = models.ForeignKey(Person, on_delete=models.CASCADE)
comments = models.TextField(max_length=50... | 0.698741 | 0.207355 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
from sp_layers import SPLayer
def fbank_test():
conf = {
"feature_type": "fbank",
"sample_rate": 16000,
"num_mel_bins": 40,
"use_energy": False
}
fn = "file:testdata/100-1... | test/sp_layers_test.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
from sp_layers import SPLayer
def fbank_test():
conf = {
"feature_type": "fbank",
"sample_rate": 16000,
"num_mel_bins": 40,
"use_energy": False
}
fn = "file:testdata/100-1... | 0.494629 | 0.458834 |