code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from __future__ import division
import numpy as np
import fidimag.extensions.common_clib as clib
# Change int he future to common clib:
import fidimag.extensions.clib as atom_clib
import sys
from .minimiser_base import MinimiserBase
class SteepestDescent(MinimiserBase):
"""
This class is the driver to minimi... | fidimag/common/steepest_descent.py | from __future__ import division
import numpy as np
import fidimag.extensions.common_clib as clib
# Change int he future to common clib:
import fidimag.extensions.clib as atom_clib
import sys
from .minimiser_base import MinimiserBase
class SteepestDescent(MinimiserBase):
"""
This class is the driver to minimi... | 0.649023 | 0.41256 |
# In[1]:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
sns.set_theme(style="ticks", color_codes=True)
# In[2]:
#load data
df = pd.read_csv('in-vehicle-coupon-recommendation.csv')... | example.py |
# In[1]:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
sns.set_theme(style="ticks", color_codes=True)
# In[2]:
#load data
df = pd.read_csv('in-vehicle-coupon-recommendation.csv')... | 0.651577 | 0.77343 |
"""用于加载预处理好的数据
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from typing import Tuple
from dialogue.tools import pad_sequences
from dialogue.tools import Tokenizer
def read_data(data_path: str, max_data_size: int, max_sentence: int,
... | dialogue/tools/read_data.py | """用于加载预处理好的数据
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from typing import Tuple
from dialogue.tools import pad_sequences
from dialogue.tools import Tokenizer
def read_data(data_path: str, max_data_size: int, max_sentence: int,
... | 0.606382 | 0.464841 |
import datetime
import json
import responses
from dateutil import tz
from flask import current_app
from server.test.abstract_test import AbstractTest
class TestStats(AbstractTest):
def _assert_datetime_equals(self, milliseconds, date_str):
dt = datetime.datetime.fromtimestamp(milliseconds / 1000, tz=tz... | server/test/api/test_stats.py | import datetime
import json
import responses
from dateutil import tz
from flask import current_app
from server.test.abstract_test import AbstractTest
class TestStats(AbstractTest):
def _assert_datetime_equals(self, milliseconds, date_str):
dt = datetime.datetime.fromtimestamp(milliseconds / 1000, tz=tz... | 0.423577 | 0.364438 |
from pwn import *
conn = remote("on.acictf.com", 34053)
#conn = remote("localhost", 4444) # ssh remote tunnel to socat on rpi
#context.log_level = "debug"
elf = ELF("./armed")
libc = ELF("./libc.so.6")
#libc = ELF("./libc_pi.so.6")
# Test string to use for testing leak
TEST_STR = 0x10cd0 # "This will be used la... | 2018-cyberstakes/armed/solve.py | from pwn import *
conn = remote("on.acictf.com", 34053)
#conn = remote("localhost", 4444) # ssh remote tunnel to socat on rpi
#context.log_level = "debug"
elf = ELF("./armed")
libc = ELF("./libc.so.6")
#libc = ELF("./libc_pi.so.6")
# Test string to use for testing leak
TEST_STR = 0x10cd0 # "This will be used la... | 0.454956 | 0.158793 |
from typing import Tuple
import shutil
import pytest
import torch
from torch import nn, Tensor
from torch.utils.data import DataLoader, Dataset, TensorDataset
from catalyst import dl
from catalyst.core.runner import IRunnerError
from catalyst.dl import Callback, CallbackOrder, SupervisedRunner
class DummyDataset(D... | tests/catalyst/runners/test_runner.py | from typing import Tuple
import shutil
import pytest
import torch
from torch import nn, Tensor
from torch.utils.data import DataLoader, Dataset, TensorDataset
from catalyst import dl
from catalyst.core.runner import IRunnerError
from catalyst.dl import Callback, CallbackOrder, SupervisedRunner
class DummyDataset(D... | 0.901466 | 0.558146 |
import torch
from torch import nn
from src.utils.technical_utils import load_obj
class VentilatorNet(nn.Module):
def __init__(self,
input_dim: int = 4,
dense_dim: int = 128,
nhead: int = 8,
logit_dim: int = 256,
transformer_num_... | src/models/ventilator_model__1.py | import torch
from torch import nn
from src.utils.technical_utils import load_obj
class VentilatorNet(nn.Module):
def __init__(self,
input_dim: int = 4,
dense_dim: int = 128,
nhead: int = 8,
logit_dim: int = 256,
transformer_num_... | 0.874144 | 0.268207 |
import os
import pickle
import MySQLdb
import MySQLdb.cursors
import numpy as np
import pandas as pd
from dotenv import load_dotenv
import statsmodels.api as sm
import matplotlib.pyplot as plt
load_dotenv()
def get_data(sql, filename, output_dir, use_cache):
"""Load data"""
if use_cache:... | src/3_analysis/forecasting.py |
import os
import pickle
import MySQLdb
import MySQLdb.cursors
import numpy as np
import pandas as pd
from dotenv import load_dotenv
import statsmodels.api as sm
import matplotlib.pyplot as plt
load_dotenv()
def get_data(sql, filename, output_dir, use_cache):
"""Load data"""
if use_cache:... | 0.473901 | 0.209046 |
from .bif_forgetter import bifForgetter
class sgmcmcForgetter(bifForgetter):
''' bifForgetter for SGMCMC
Args:
optimizer (torch.optim): sgmcmc optimizer that used to
sample (update) model parameter (i.e., params) for
estimating the expectation terms in I(target... | bayes_forgetters/sgmcmc_forgetter.py | from .bif_forgetter import bifForgetter
class sgmcmcForgetter(bifForgetter):
''' bifForgetter for SGMCMC
Args:
optimizer (torch.optim): sgmcmc optimizer that used to
sample (update) model parameter (i.e., params) for
estimating the expectation terms in I(target... | 0.627951 | 0.306449 |
import adsk.fusion
import unittest
# note: load_tests is required for the "pattern" test filtering functionality in loadTestsFromModule in run()
from fscad.test_utils import FscadTestCase, load_tests
from fscad.fscad import *
class IntersectionTest(FscadTestCase):
def test_basic_intersection(self):
box... | tests/intersection_test.py |
import adsk.fusion
import unittest
# note: load_tests is required for the "pattern" test filtering functionality in loadTestsFromModule in run()
from fscad.test_utils import FscadTestCase, load_tests
from fscad.fscad import *
class IntersectionTest(FscadTestCase):
def test_basic_intersection(self):
box... | 0.612657 | 0.618982 |
from __future__ import print_function
import mock
import unittest
import telneter
import find_IACSE
from telneter import IAC, SB, SE, WILL, WONT, DO, DONT, STATUS
def multi_parse(data):
parses = []
while data:
parses.append(telneter.parse(data))
data = parses[-1][-1]
return parses
class... | test_telneter.py | from __future__ import print_function
import mock
import unittest
import telneter
import find_IACSE
from telneter import IAC, SB, SE, WILL, WONT, DO, DONT, STATUS
def multi_parse(data):
parses = []
while data:
parses.append(telneter.parse(data))
data = parses[-1][-1]
return parses
class... | 0.284079 | 0.151749 |
from json import loads
from subprocess import call
from time import strftime
from interutils import pr
from prettytable import PrettyTable
from requests import get, Response
from termcolor import colored, cprint
API_USAGE_CAP = 10
def _cval(val: float, colorize: bool, suffix: str = '') -> str:
col = None
i... | cryptofetch/fetcher.py | from json import loads
from subprocess import call
from time import strftime
from interutils import pr
from prettytable import PrettyTable
from requests import get, Response
from termcolor import colored, cprint
API_USAGE_CAP = 10
def _cval(val: float, colorize: bool, suffix: str = '') -> str:
col = None
i... | 0.346762 | 0.133641 |
import re
from .propagation import sgp4
from .inout import twoline2rv
from .earth_gravity import EarthGravity, wgs84
from math import pi, sqrt, floor, pow
from numpy import dot, linalg, arange, copy, char
from math import fabs as abs
from .inout import jday
from datetime import datetime
from operator import attrgetter
... | application/poca/util.py | import re
from .propagation import sgp4
from .inout import twoline2rv
from .earth_gravity import EarthGravity, wgs84
from math import pi, sqrt, floor, pow
from numpy import dot, linalg, arange, copy, char
from math import fabs as abs
from .inout import jday
from datetime import datetime
from operator import attrgetter
... | 0.208904 | 0.290572 |
import logging
import os
import tempfile
import dateutil.parser
import dateutil.parser
from RWAPIMicroservicePython import request_to_microservice
from osgeo import gdal
from requests import Request, Session
from requests.exceptions import ConnectTimeout
from nexgddp.errors import SqlFormatError, PeriodNotValid, Tab... | nexgddp/services/query_service.py |
import logging
import os
import tempfile
import dateutil.parser
import dateutil.parser
from RWAPIMicroservicePython import request_to_microservice
from osgeo import gdal
from requests import Request, Session
from requests.exceptions import ConnectTimeout
from nexgddp.errors import SqlFormatError, PeriodNotValid, Tab... | 0.460289 | 0.199874 |
import os
import sys
import tempfile
import datetime
ERRORS_ = [
'''Invalid syntax.\n\nHere is how it works:
If you ARE NOT generating a keypair:
$ rsaencdec OPTIONS input [outputFilePath if OPTIONS has F] key
If you ARE generating a keypair:
$ rsaencdec g publicPath privatePath bits
These are the options:
e: en... | rsaencdec.py |
import os
import sys
import tempfile
import datetime
ERRORS_ = [
'''Invalid syntax.\n\nHere is how it works:
If you ARE NOT generating a keypair:
$ rsaencdec OPTIONS input [outputFilePath if OPTIONS has F] key
If you ARE generating a keypair:
$ rsaencdec g publicPath privatePath bits
These are the options:
e: en... | 0.175044 | 0.128607 |
from nuclear import *
from tests.asserts import MockIO
from tests.parser.actions import *
def test_run_default_single_action():
with MockIO() as mockio:
CliBuilder(run=print_ok).run()
assert mockio.output() == 'ok\n'
def test_default_builder_action_with_redundant_args():
with MockIO('push') ... | tests/parser/test_default_action.py | from nuclear import *
from tests.asserts import MockIO
from tests.parser.actions import *
def test_run_default_single_action():
with MockIO() as mockio:
CliBuilder(run=print_ok).run()
assert mockio.output() == 'ok\n'
def test_default_builder_action_with_redundant_args():
with MockIO('push') ... | 0.615781 | 0.26359 |
import argparse
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
from board import Board
import math
from bot import Node
from bot import Bot, puct
from player import Player
def check_num_of_games(val):
try:
... | src/treenn_vs_tree.py | import argparse
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
from board import Board
import math
from bot import Node
from bot import Bot, puct
from player import Player
def check_num_of_games(val):
try:
... | 0.45181 | 0.393909 |
from unittest import TestCase
from cloudshell.cli.session.connection_params import ConnectionParams
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
class ConnectionParamsTestImpl(ConnectionParams):
pass
class TestConnectionParams(TestCase):
def setUp(self):
se... | tests/cli/session/test_connection_params.py | from unittest import TestCase
from cloudshell.cli.session.connection_params import ConnectionParams
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
class ConnectionParamsTestImpl(ConnectionParams):
pass
class TestConnectionParams(TestCase):
def setUp(self):
se... | 0.674587 | 0.295789 |
from authentication.models import CommuneSatellite
from authentication.models import DeptSatellite
from authentication.models import BeninYield
from django.db.models import Sum, Avg
import folium
from django.utils.translation import gettext
import geojson
from area import area
from math import log10, floor
from celery ... | app/benin_republic.py | from authentication.models import CommuneSatellite
from authentication.models import DeptSatellite
from authentication.models import BeninYield
from django.db.models import Sum, Avg
import folium
from django.utils.translation import gettext
import geojson
from area import area
from math import log10, floor
from celery ... | 0.442877 | 0.157655 |
from __future__ import division
from itertools import chain
from openapi_core.casting.schemas.exceptions import CastError
from openapi_core.deserializing.exceptions import DeserializeError
from openapi_core.exceptions import (
MissingRequiredParameter, MissingParameter, MissingRequestBody,
)
from openapi_core.secu... | openapi_core/validation/request/validators.py | from __future__ import division
from itertools import chain
from openapi_core.casting.schemas.exceptions import CastError
from openapi_core.deserializing.exceptions import DeserializeError
from openapi_core.exceptions import (
MissingRequiredParameter, MissingParameter, MissingRequestBody,
)
from openapi_core.secu... | 0.498779 | 0.095434 |
import torch
import torch.nn as nn
from .util import MonthlyMultiplexer, WeeklyMultiplexer
class BiasCorrectionModel(nn.Module):
def __init__(self):
super().__init__()
self.bias = nn.parameter.Parameter(torch.normal(torch.zeros(2, 121, 240)))
def forward(self, model_parameter):
retur... | crims2s/training/model/bias.py | import torch
import torch.nn as nn
from .util import MonthlyMultiplexer, WeeklyMultiplexer
class BiasCorrectionModel(nn.Module):
def __init__(self):
super().__init__()
self.bias = nn.parameter.Parameter(torch.normal(torch.zeros(2, 121, 240)))
def forward(self, model_parameter):
retur... | 0.947709 | 0.429728 |
import ckeditor.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migra... | blog/migrations/0001_initial.py |
import ckeditor.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migra... | 0.516108 | 0.129046 |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Activador',
fields=[
('id_esta', models.BigIntegerField(serialize=False... | apps/infopy/core/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Activador',
fields=[
('id_esta', models.BigIntegerField(serialize=False... | 0.553988 | 0.149314 |
from django.contrib import messages
from django.shortcuts import render
from django.views import generic
from . import forms, models, tasks
class TicketCreateView(generic.View):
"""
View used to handle /contact/ GET/POST requests.
Views is used to contact with support.
**Context:**
``form``
... | app/support/views.py | from django.contrib import messages
from django.shortcuts import render
from django.views import generic
from . import forms, models, tasks
class TicketCreateView(generic.View):
"""
View used to handle /contact/ GET/POST requests.
Views is used to contact with support.
**Context:**
``form``
... | 0.552781 | 0.102439 |
import logging
import os
import swisseph as swe
import sys
import traceback
from sanskrit_data.schema.common import JsonObject
from sanskrit_data.schema import common
from indic_transliteration import xsanscript as sanscript
from jyotisha.panchangam import spatio_temporal
from jyotisha.panchangam.spatio_temporal imp... | jyotisha/panchangam/spatio_temporal/annual.py | import logging
import os
import swisseph as swe
import sys
import traceback
from sanskrit_data.schema.common import JsonObject
from sanskrit_data.schema import common
from indic_transliteration import xsanscript as sanscript
from jyotisha.panchangam import spatio_temporal
from jyotisha.panchangam.spatio_temporal imp... | 0.387459 | 0.106133 |
class mppool:
def __init__(self):
import Lily.ctao.database as cdb
import Lily.ctao.hostmetadata as chmd
self.this_host = chmd.hostmetadata()
self.log_database = cdb.database(self.this_host.database)
def map(self, your_function, your_datalist, message = 'mpool'):
... | pylily/Lily/blacksmith/mppool.py | class mppool:
def __init__(self):
import Lily.ctao.database as cdb
import Lily.ctao.hostmetadata as chmd
self.this_host = chmd.hostmetadata()
self.log_database = cdb.database(self.this_host.database)
def map(self, your_function, your_datalist, message = 'mpool'):
... | 0.384912 | 0.135804 |
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from colorama import Fore
from clin.models.auth import ReadOnlyAuth
from clin.models.shared import Cleanup, Category, Entity, Kind, Audience, Partitioning
@dataclass
class OutputEventType:
category: Category
ow... | clin/models/sql_query.py | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from colorama import Fore
from clin.models.auth import ReadOnlyAuth
from clin.models.shared import Cleanup, Category, Entity, Kind, Audience, Partitioning
@dataclass
class OutputEventType:
category: Category
ow... | 0.865878 | 0.270513 |
import numpy
import torch
try:
import cupy
@cupy.util.memoize(for_each_device=True)
def cunnex(strFunction):
assert strFunction in globals().keys()
return cupy.cuda.compile_with_cache(globals()[strFunction]).get_function(strFunction)
except ImportError:
print("CUPY cannot initialize, ... | common/cupy.py | import numpy
import torch
try:
import cupy
@cupy.util.memoize(for_each_device=True)
def cunnex(strFunction):
assert strFunction in globals().keys()
return cupy.cuda.compile_with_cache(globals()[strFunction]).get_function(strFunction)
except ImportError:
print("CUPY cannot initialize, ... | 0.560974 | 0.348229 |
from pathlib import Path
from dotenv import load_dotenv
import os
load_dotenv()
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv("SECRET_KEY", default="foo")
DEBUG = int(os.getenv("DEBUG", default=1))
ALLOWED_HOSTS = os.getenv(
"DJANGO_ALLOWED_HOSTS", default="localhost 127.0.0.1 [::1] "... | Plataforma De Cursos/plataforma_cursos/settings.py | from pathlib import Path
from dotenv import load_dotenv
import os
load_dotenv()
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv("SECRET_KEY", default="foo")
DEBUG = int(os.getenv("DEBUG", default=1))
ALLOWED_HOSTS = os.getenv(
"DJANGO_ALLOWED_HOSTS", default="localhost 127.0.0.1 [::1] "... | 0.361277 | 0.127191 |
import logging
import time
from tasks import ceph_manager
from teuthology import misc as teuthology
log = logging.getLogger(__name__)
def check_stuck(manager, num_inactive, num_unclean, num_stale, timeout=10):
"""
Do checks. Make sure get_stuck_pgs return the right amount of information, then
extract h... | qa/tasks/dump_stuck.py | import logging
import time
from tasks import ceph_manager
from teuthology import misc as teuthology
log = logging.getLogger(__name__)
def check_stuck(manager, num_inactive, num_unclean, num_stale, timeout=10):
"""
Do checks. Make sure get_stuck_pgs return the right amount of information, then
extract h... | 0.281109 | 0.403391 |
from datetime import datetime
import discord
def formatString(oldStr):
"""
Format string into separate lines
*NOTE*
The newStr already has new lines and the developer should use the numLines return
to align any other strings to the newStr
Parameters
----------
oldStr: string
... | DiscordBot/Commands/utils.py | from datetime import datetime
import discord
def formatString(oldStr):
"""
Format string into separate lines
*NOTE*
The newStr already has new lines and the developer should use the numLines return
to align any other strings to the newStr
Parameters
----------
oldStr: string
... | 0.772359 | 0.359533 |
from __future__ import unicode_literals
import os
import django
SETTINGS_DIR = os.path.dirname(__file__)
BASE_DIR = os.path.dirname(os.path.dirname(SETTINGS_DIR))
INSTALLED_APPS = [
# 'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
... | tests/settings.py | from __future__ import unicode_literals
import os
import django
SETTINGS_DIR = os.path.dirname(__file__)
BASE_DIR = os.path.dirname(os.path.dirname(SETTINGS_DIR))
INSTALLED_APPS = [
# 'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
... | 0.272702 | 0.054955 |
from pprint import pprint
import asyncio
import sys
import json
from bluzelle import bzapi
from bluzelle.lib.udp.udp_support import *
from bluzelle.lib.udp.test_udp import *
class DB:
def __init__(self, cpp_db):
self.localhost_ip = "127.0.0.1"
self.cpp_db = cpp_db
def load_(self, *args, **kw... | bluzelle/db.py | from pprint import pprint
import asyncio
import sys
import json
from bluzelle import bzapi
from bluzelle.lib.udp.udp_support import *
from bluzelle.lib.udp.test_udp import *
class DB:
def __init__(self, cpp_db):
self.localhost_ip = "127.0.0.1"
self.cpp_db = cpp_db
def load_(self, *args, **kw... | 0.192388 | 0.082217 |
import threading
from json import dumps
import os.path
from app import current_config
from app import util_logger as logger
from app.executable.bundle import Bundle, BundleError
from app.executable.jekyll import Jekyll
from app.filehandling import deploy_error_page, dispatch_static_files
from app.repository import Rep... | app/buildpipeline/buildpipeline.py | import threading
from json import dumps
import os.path
from app import current_config
from app import util_logger as logger
from app.executable.bundle import Bundle, BundleError
from app.executable.jekyll import Jekyll
from app.filehandling import deploy_error_page, dispatch_static_files
from app.repository import Rep... | 0.421076 | 0.117572 |
import wx
import threading
from leginon.gui.wx.Entry import Entry, FloatEntry, EVT_ENTRY
import leginon.gui.wx.Node
import leginon.gui.wx.Settings
import leginon.gui.wx.ToolBar
import leginon.gui.wx.TargetPanel
class Panel(leginon.gui.wx.Node.Panel):
icon = 'fftmaker'
def __init__(self, *args, **kwargs):
leginon... | lib/python2.7/site-packages/leginon/gui/wx/FFTMaker.py |
import wx
import threading
from leginon.gui.wx.Entry import Entry, FloatEntry, EVT_ENTRY
import leginon.gui.wx.Node
import leginon.gui.wx.Settings
import leginon.gui.wx.ToolBar
import leginon.gui.wx.TargetPanel
class Panel(leginon.gui.wx.Node.Panel):
icon = 'fftmaker'
def __init__(self, *args, **kwargs):
leginon... | 0.38122 | 0.062132 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('emgapi', '0011_study_is_public'),
]
operations = [
migrations.CreateModel(
name='SampleGeoCoordinate',
... | emgapi/migrations/0012_auto_20190507_1219.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('emgapi', '0011_study_is_public'),
]
operations = [
migrations.CreateModel(
name='SampleGeoCoordinate',
... | 0.626467 | 0.097305 |
import torch
from torch import nn
from .utils import int_sample, float_sample
from .gcn_module import BasicGraphBlock, ResGraphBlock
from dataset import VIS_CONFIG
def build_pr_net(cfg, num_joints, input_channels=480):
net = PoseRefine(cfg, num_joints, input_channels)
return net
class PoseRefine(nn.Module):... | lib/models/pr.py | import torch
from torch import nn
from .utils import int_sample, float_sample
from .gcn_module import BasicGraphBlock, ResGraphBlock
from dataset import VIS_CONFIG
def build_pr_net(cfg, num_joints, input_channels=480):
net = PoseRefine(cfg, num_joints, input_channels)
return net
class PoseRefine(nn.Module):... | 0.930175 | 0.425068 |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from wann_genetic.individual.torch.ffnn import Network as TorchNetwork
import torch
def node_names(net):
return (
[f"$x_{{{i}}}$" for i in range(net.n_in)] # inputs
+ ["$b$"] # bias
... | src/wann_genetic/postopt/vis/vis_network.py | import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from wann_genetic.individual.torch.ffnn import Network as TorchNetwork
import torch
def node_names(net):
return (
[f"$x_{{{i}}}$" for i in range(net.n_in)] # inputs
+ ["$b$"] # bias
... | 0.594434 | 0.497192 |
import pytest
from returns.primitives.exceptions import UnwrapFailedError
from piri.iso import GetCountryCode, GetCurrencyCode, GetLanguageCode
class TestGetCountryCode(object):
"""Test FetchDataByKeys function.
Norway, NO, NOR, 578
Albania, AL, ALB, 008
"""
_get = GetCountryCode()
def tes... | tests/iso_test.py | import pytest
from returns.primitives.exceptions import UnwrapFailedError
from piri.iso import GetCountryCode, GetCurrencyCode, GetLanguageCode
class TestGetCountryCode(object):
"""Test FetchDataByKeys function.
Norway, NO, NOR, 578
Albania, AL, ALB, 008
"""
_get = GetCountryCode()
def tes... | 0.807423 | 0.605303 |
import os
import pytest
import ska_sdp_config
# pylint: disable=missing-docstring,redefined-outer-name
PREFIX = "/__test_subarray"
# pylint: disable=W0212
@pytest.fixture(scope="session")
def cfg():
host = os.getenv("SDP_TEST_HOST", "127.0.0.1")
with ska_sdp_config.Config(global_prefix=PREFIX, host=host) ... | tests/test_subarray.py |
import os
import pytest
import ska_sdp_config
# pylint: disable=missing-docstring,redefined-outer-name
PREFIX = "/__test_subarray"
# pylint: disable=W0212
@pytest.fixture(scope="session")
def cfg():
host = os.getenv("SDP_TEST_HOST", "127.0.0.1")
with ska_sdp_config.Config(global_prefix=PREFIX, host=host) ... | 0.530236 | 0.313893 |
from enum import Enum
from collections import namedtuple
import tvm
import tvm.te as te
import tvm.tg as tg
import tvm.tir as tir
import numpy as np
def pprint_dict(d):
import json
print(json.dumps(d, indent=2, sort_keys=False))
def get_vector_add(n):
"""TVM expression for vector add"""
A = te.placeholder... | tests/python/tg/test_feature_common.py | from enum import Enum
from collections import namedtuple
import tvm
import tvm.te as te
import tvm.tg as tg
import tvm.tir as tir
import numpy as np
def pprint_dict(d):
import json
print(json.dumps(d, indent=2, sort_keys=False))
def get_vector_add(n):
"""TVM expression for vector add"""
A = te.placeholder... | 0.760917 | 0.555315 |
from pathlib import Path
from typing import List
from matplotlib import pyplot as plt
from paddle.custom_types import AnyPath
from paddle.visualization import plot_particle_size_distributions, save_figure
from utilities.particle_size_distribution_comparison import (
gather_psd_data_for_class,
get_data_sets,
... | studies/PsdComparison/study_psd_comparison.py | from pathlib import Path
from typing import List
from matplotlib import pyplot as plt
from paddle.custom_types import AnyPath
from paddle.visualization import plot_particle_size_distributions, save_figure
from utilities.particle_size_distribution_comparison import (
gather_psd_data_for_class,
get_data_sets,
... | 0.945764 | 0.637073 |
import numpy as np
import gym
from dezero import Model
from dezero import optimizers
import dezero.functions as F
import dezero.layers as L
from common.utils import plot_total_reward
class PolicyNet(Model):
def __init__(self, action_size=2):
super().__init__()
self.l1 = L.Linear(256)
self.... | ch09/actor_critic.py | import numpy as np
import gym
from dezero import Model
from dezero import optimizers
import dezero.functions as F
import dezero.layers as L
from common.utils import plot_total_reward
class PolicyNet(Model):
def __init__(self, action_size=2):
super().__init__()
self.l1 = L.Linear(256)
self.... | 0.827689 | 0.396711 |
import json
import os
from cryptography.fernet import Fernet as fn
def pcAutoActivateDeactivte():
no_of_config = 0
count = 0
loop = 'notexit'
xcount = 0
os.system('cls')
print("\n -------------------------------Auto Backup Solution-----------------------------")
print("\n -------------... | source_code/v1.0.0/autoTools.py | import json
import os
from cryptography.fernet import Fernet as fn
def pcAutoActivateDeactivte():
no_of_config = 0
count = 0
loop = 'notexit'
xcount = 0
os.system('cls')
print("\n -------------------------------Auto Backup Solution-----------------------------")
print("\n -------------... | 0.174903 | 0.076373 |
import datetime
import time
from ht1632cpy import HT1632C
import settings
from lightsensor import getLight
interface = HT1632C(2, 0)
interface.pwm(settings.read('settings', 'matrix', 'default_brightness'))
def dimmer():
dimmer_brightness = settings.read('settings', 'matrix', 'dimmer_brightness')
default_br... | display.py | import datetime
import time
from ht1632cpy import HT1632C
import settings
from lightsensor import getLight
interface = HT1632C(2, 0)
interface.pwm(settings.read('settings', 'matrix', 'default_brightness'))
def dimmer():
dimmer_brightness = settings.read('settings', 'matrix', 'dimmer_brightness')
default_br... | 0.174903 | 0.102619 |
from __future__ import unicode_literals
import json
import logging
from pprint import pformat
import requests
import tornado.web
logger = logging.getLogger(__name__)
SIZE_TABLE = {
'': {
'width': 300,
'height': 300
},
'small': {
'width': 300,
'height': 300
},
'med... | mopidy_moppina/handlers.py | from __future__ import unicode_literals
import json
import logging
from pprint import pformat
import requests
import tornado.web
logger = logging.getLogger(__name__)
SIZE_TABLE = {
'': {
'width': 300,
'height': 300
},
'small': {
'width': 300,
'height': 300
},
'med... | 0.289874 | 0.091544 |
import PySimpleGUI as sg
def make_window(theme):
sg.theme(theme)
menu_def = [['&Application', ['E&xit']],
['&Help', ['&About']] ]
right_click_menu_def = [[], ['Nothing','More Nothing','Exit']]
# Table Data
data = [["John", 10], ["Jen", 5]]
headings = ["Name", "Score"]
defa... | arena_navigation/arena_local_planner/evaluation/scripts/gui/eval_GUI.py | import PySimpleGUI as sg
def make_window(theme):
sg.theme(theme)
menu_def = [['&Application', ['E&xit']],
['&Help', ['&About']] ]
right_click_menu_def = [[], ['Nothing','More Nothing','Exit']]
# Table Data
data = [["John", 10], ["Jen", 5]]
headings = ["Name", "Score"]
defa... | 0.301979 | 0.176707 |
# COMMAND ----------
# MAGIC %md
# MAGIC ## O básico
# MAGIC
# MAGIC ### Executando um Workbook
# MAGIC
# MAGIC Execução efêmera, o conteúdo das variáveis será perdido
# MAGIC ```python
# MAGIC dbutils.notebook.run('/comum/setup_conn_sadatalakevcbr.ipynb',60)
# MAGIC ```
# MAGIC
# MAGIC Execução semelhante a um in... | pyspark_guide.ipynb.py |
# COMMAND ----------
# MAGIC %md
# MAGIC ## O básico
# MAGIC
# MAGIC ### Executando um Workbook
# MAGIC
# MAGIC Execução efêmera, o conteúdo das variáveis será perdido
# MAGIC ```python
# MAGIC dbutils.notebook.run('/comum/setup_conn_sadatalakevcbr.ipynb',60)
# MAGIC ```
# MAGIC
# MAGIC Execução semelhante a um in... | 0.464902 | 0.359111 |
from AI import AI
from AI import PlayerUpdateInstructions
from AI import AIOutput
import vector
from Frameworks.CommonQueryAIFramework import CommonQueryAIFramework
from Frameworks.ActionAIFramework import ActionAIFramework
@AI.Team
class KaliAI1(CommonQueryAIFramework, ActionAIFramework):
def __init__(self):
... | Team/KaliAI1.py | from AI import AI
from AI import PlayerUpdateInstructions
from AI import AIOutput
import vector
from Frameworks.CommonQueryAIFramework import CommonQueryAIFramework
from Frameworks.ActionAIFramework import ActionAIFramework
@AI.Team
class KaliAI1(CommonQueryAIFramework, ActionAIFramework):
def __init__(self):
... | 0.642881 | 0.158956 |
import pandas as pd
import numpy as np
'''
This module contains several normalization methods.
See ReadMe.md for usage example.
'''
def zero_one_normalize(df: pd.DataFrame, excluded_colnames: list = None) -> pd.DataFrame:
"""
Applies the MinMaxScaler from the module sklearn.preprocessing to find
... | mvtsdatatoolkit/normalizing/normalizer.py | import pandas as pd
import numpy as np
'''
This module contains several normalization methods.
See ReadMe.md for usage example.
'''
def zero_one_normalize(df: pd.DataFrame, excluded_colnames: list = None) -> pd.DataFrame:
"""
Applies the MinMaxScaler from the module sklearn.preprocessing to find
... | 0.873188 | 0.731922 |
from __future__ import annotations
words = [
"you",
"i",
"the",
"to",
"a",
"'s",
"it",
"and",
"that",
"'t",
"of",
"is",
"in",
"what",
"we",
"me",
"this",
"he",
"for",
"my",
"on",
"have",
"your",
"do",
"was",
"'m",
... | AnalystBoxBackend/src/AnalystBox/field_parser/corpus.py | from __future__ import annotations
words = [
"you",
"i",
"the",
"to",
"a",
"'s",
"it",
"and",
"that",
"'t",
"of",
"is",
"in",
"what",
"we",
"me",
"this",
"he",
"for",
"my",
"on",
"have",
"your",
"do",
"was",
"'m",
... | 0.351979 | 0.470189 |
import types, socket, operator
from twisted.internet.abstract import isIPAddress # would rather not import "abstract"
from twisted.internet import defer, interfaces, address, error
from twisted.python import log
import server, client
import iocpdebug
from zope.interface import implements
class TcpMixin:
def g... | python2.7/site-packages/twisted/internet/iocpreactor/tcp.py |
import types, socket, operator
from twisted.internet.abstract import isIPAddress # would rather not import "abstract"
from twisted.internet import defer, interfaces, address, error
from twisted.python import log
import server, client
import iocpdebug
from zope.interface import implements
class TcpMixin:
def g... | 0.397237 | 0.058723 |
import towerdev.common
import towerdev.utilities
from colors import *
# Invoke dockerClient()
dockerClient = towerdev.common.dockerClient()
def runContainer(purpose, externalPort, osVersion, containerName, debug=True, **kwargs):
"""Run supplemental container from pre-existing image"""
# Optional debug that ... | towerdev/run.py | import towerdev.common
import towerdev.utilities
from colors import *
# Invoke dockerClient()
dockerClient = towerdev.common.dockerClient()
def runContainer(purpose, externalPort, osVersion, containerName, debug=True, **kwargs):
"""Run supplemental container from pre-existing image"""
# Optional debug that ... | 0.444806 | 0.095898 |
import dataclasses
import functools
import itertools
import logging
import os
from kubernetes.dynamic.exceptions import ResourceNotFoundError, ConflictError
from kluctl.deployment.apply_util import ApplyUtil
from kluctl.deployment.images import SeenImages
from kluctl.deployment.kustomize_deployment import KustomizeDe... | kluctl/deployment/deployment_collection.py | import dataclasses
import functools
import itertools
import logging
import os
from kubernetes.dynamic.exceptions import ResourceNotFoundError, ConflictError
from kluctl.deployment.apply_util import ApplyUtil
from kluctl.deployment.images import SeenImages
from kluctl.deployment.kustomize_deployment import KustomizeDe... | 0.400398 | 0.123842 |
import unittest
from io import StringIO
from windpyutils.buffers import PrintBuffer, Buffer
class TestBuffer(unittest.TestCase):
def setUp(self) -> None:
self.b = Buffer()
def test_all_in_order(self):
self.assertEqual(0, self.b(0, "A").waiting_for())
self.assertEqual(0, self.b(1, "B"... | tests/test_buffers.py | import unittest
from io import StringIO
from windpyutils.buffers import PrintBuffer, Buffer
class TestBuffer(unittest.TestCase):
def setUp(self) -> None:
self.b = Buffer()
def test_all_in_order(self):
self.assertEqual(0, self.b(0, "A").waiting_for())
self.assertEqual(0, self.b(1, "B"... | 0.57523 | 0.647185 |
# HarryLibrary = Library(listofbooks, library_name)
# dictionary (books-nameofperson)
# create a main function and run an infinite while loop asking users for their input
class Library:
def __init__(self, booklist, libname, lenders, donors):
self.booklist = booklist
self.libname = libname
... | Librarymanager.py |
# HarryLibrary = Library(listofbooks, library_name)
# dictionary (books-nameofperson)
# create a main function and run an infinite while loop asking users for their input
class Library:
def __init__(self, booklist, libname, lenders, donors):
self.booklist = booklist
self.libname = libname
... | 0.326593 | 0.130202 |
from twisted.internet.task import react
from twisted.internet.defer import inlineCallbacks
import txaio
from txaioetcd import Client, Expired
@inlineCallbacks
def main(reactor):
etcd = Client(reactor)
status = yield etcd.status()
print(status)
yield example1(reactor, etcd)
yield example2(reac... | examples/lease.py |
from twisted.internet.task import react
from twisted.internet.defer import inlineCallbacks
import txaio
from txaioetcd import Client, Expired
@inlineCallbacks
def main(reactor):
etcd = Client(reactor)
status = yield etcd.status()
print(status)
yield example1(reactor, etcd)
yield example2(reac... | 0.352536 | 0.14978 |
def get_optimizer_params(model, lr, lr_weight_decay_coef, num_layers):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
if lr_weight_decay_coef < 1.0:
optimizer_grouped_parameters = [
{'params': [
p for n, p ... | torchblocks/optims/utils.py | def get_optimizer_params(model, lr, lr_weight_decay_coef, num_layers):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
if lr_weight_decay_coef < 1.0:
optimizer_grouped_parameters = [
{'params': [
p for n, p ... | 0.443359 | 0.356167 |
__author__ = 'Rafael'
from database.Repositories.Interfaces.IInformacoesRepository import IInformacoesRepository
class InformacoesRepository(IInformacoesRepository):
async def create(self, pool, informacao, dado):
"""
Args:
pool (asyncpg.pool.Pool): Conexão com o banco de dados
... | database/Repositories/InformacoesRepository.py |
__author__ = 'Rafael'
from database.Repositories.Interfaces.IInformacoesRepository import IInformacoesRepository
class InformacoesRepository(IInformacoesRepository):
async def create(self, pool, informacao, dado):
"""
Args:
pool (asyncpg.pool.Pool): Conexão com o banco de dados
... | 0.695441 | 0.173673 |
UNPRINTABLE_ESCAPES = frozenset([
0x01, # Start of Heading
0x02, # Start of Text
0x03, # End of Text
0x04, # End of Transmission
0x05, # Enquiry
0x06, # Acknowledge
0x07, # Bell
0x0B, # Vertical Tab
0x0E, # Shift Out
0x0F, # Shift In
0x10, # Data Link Escape
0x... | scripts/gen_inline_jump.py | UNPRINTABLE_ESCAPES = frozenset([
0x01, # Start of Heading
0x02, # Start of Text
0x03, # End of Text
0x04, # End of Transmission
0x05, # Enquiry
0x06, # Acknowledge
0x07, # Bell
0x0B, # Vertical Tab
0x0E, # Shift Out
0x0F, # Shift In
0x10, # Data Link Escape
0x... | 0.271638 | 0.159938 |
import numpy as np
import cv2
from actionRecognize import ActionRecognize
def get3dPCA(vcube, dimens):
x,y,t = dimens
sliceXY = np.swapaxes(vcube,1,2).reshape(t,y*x,order='F')#.swapaxes(0,1)
#sliceXYn = sliceXY / sliceXY.max(axis=0)
sliceXT = np.swapaxes(vcube,0,2).reshape(x,y*t)#.swapaxes(0,1)
... | arrayReshape.py | import numpy as np
import cv2
from actionRecognize import ActionRecognize
def get3dPCA(vcube, dimens):
x,y,t = dimens
sliceXY = np.swapaxes(vcube,1,2).reshape(t,y*x,order='F')#.swapaxes(0,1)
#sliceXYn = sliceXY / sliceXY.max(axis=0)
sliceXT = np.swapaxes(vcube,0,2).reshape(x,y*t)#.swapaxes(0,1)
... | 0.119794 | 0.444987 |
import os
import numpy as np
import glob
import argparse
import shutil
from PIL import Image
CWD = os.path.dirname(os.path.realpath(__file__))
LAST_IMAGE_COUNT = 45
def handle_arguments():
"""
Function to set up commandline arguments
:return args:
"""
parser = argparse.ArgumentParser(description='... | datautils/stack_data.py | import os
import numpy as np
import glob
import argparse
import shutil
from PIL import Image
CWD = os.path.dirname(os.path.realpath(__file__))
LAST_IMAGE_COUNT = 45
def handle_arguments():
"""
Function to set up commandline arguments
:return args:
"""
parser = argparse.ArgumentParser(description='... | 0.467332 | 0.32611 |
from __future__ import division
from enum import Enum
from collections import namedtuple
from .techtree import Node as ResearchNode
# Source: http://wiki.kerbalspaceprogram.com/wiki/Parts, as well as in-game info
kspversion = '1.3 / 1.2'
class RadialSize(Enum):
Tiny = 1
Small = 2
Large = 3
ExtraLar... | kspalculator/parts.py | from __future__ import division
from enum import Enum
from collections import namedtuple
from .techtree import Node as ResearchNode
# Source: http://wiki.kerbalspaceprogram.com/wiki/Parts, as well as in-game info
kspversion = '1.3 / 1.2'
class RadialSize(Enum):
Tiny = 1
Small = 2
Large = 3
ExtraLar... | 0.749821 | 0.286965 |
import numpy as np
from scipy import stats
from inspect import getsource
from ..load_sim import LoadSim
class Profile1D:
@LoadSim.Decorators.check_pickle
def get_profile1d(self, num, fields_y, field_x='r', bins=None, statistic='mean',
prefix='profile1d', savdir=None, force_override... | pyathena/feedback_test/profile_1d.py |
import numpy as np
from scipy import stats
from inspect import getsource
from ..load_sim import LoadSim
class Profile1D:
@LoadSim.Decorators.check_pickle
def get_profile1d(self, num, fields_y, field_x='r', bins=None, statistic='mean',
prefix='profile1d', savdir=None, force_override... | 0.81119 | 0.729761 |
import argparse
import re
import os.path
import glob
def main():
"""Drive the script."""
parser = argparse.ArgumentParser(description=globals()['__doc__'])
parser.add_argument(
'input', type=argparse.FileType(mode='r'), metavar='INPUT',
help='The LAMMPS input file whose dumps are to be co... | catdumps.py | import argparse
import re
import os.path
import glob
def main():
"""Drive the script."""
parser = argparse.ArgumentParser(description=globals()['__doc__'])
parser.add_argument(
'input', type=argparse.FileType(mode='r'), metavar='INPUT',
help='The LAMMPS input file whose dumps are to be co... | 0.587115 | 0.127734 |
def createSapEvent(trackId):
return f'''public static final SoundEvent {trackId} = registerTrack("{trackId}");
'''
def createEvent(extra):
return """
package me.pryter.tracks.registry;
import net.minecraft.sound.SoundEvent;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;... | subProject/generator/template.py | def createSapEvent(trackId):
return f'''public static final SoundEvent {trackId} = registerTrack("{trackId}");
'''
def createEvent(extra):
return """
package me.pryter.tracks.registry;
import net.minecraft.sound.SoundEvent;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;... | 0.517571 | 0.244871 |
import json
import httplib
import logging
from httplib import HTTPException
class AuthError(Exception):pass
class GetMetaError(Exception):pass
class meta(object):
def __init__(self, host, port, user, password, meta_uuid):
self.host = host
self.port = int(port)
self.user = user
se... | vddb_async/src/task_manager/show_meta.py | import json
import httplib
import logging
from httplib import HTTPException
class AuthError(Exception):pass
class GetMetaError(Exception):pass
class meta(object):
def __init__(self, host, port, user, password, meta_uuid):
self.host = host
self.port = int(port)
self.user = user
se... | 0.249813 | 0.047536 |
import enum
from collections import defaultdict
from functools import partial
import riberry
class EventRegistryTypes(enum.Enum):
on_completion = 'on_completion'
on_data_updated = 'on_data_update'
on_report_refresh = 'on_report_refresh'
on_external_result_received = 'on_external_result_received'
c... | riberry/app/context/event_registry.py | import enum
from collections import defaultdict
from functools import partial
import riberry
class EventRegistryTypes(enum.Enum):
on_completion = 'on_completion'
on_data_updated = 'on_data_update'
on_report_refresh = 'on_report_refresh'
on_external_result_received = 'on_external_result_received'
c... | 0.617859 | 0.087058 |
from django import http
from django.contrib import messages
from django.contrib.auth.mixins import AccessMixin
from django.utils.functional import cached_property
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render, get_object_or_404
from vanilla import TemplateView, DetailView, U... | src/settlers/views.py | from django import http
from django.contrib import messages
from django.contrib.auth.mixins import AccessMixin
from django.utils.functional import cached_property
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render, get_object_or_404
from vanilla import TemplateView, DetailView, U... | 0.526343 | 0.068413 |
import hashlib
import bcrypt
from datetime import datetime
from sqlalchemy import (Column, Integer, String, Text, Boolean, DateTime,
Numeric, ForeignKey)
from sqlalchemy.orm import relationship
from geoalchemy2.types import Geometry
from geoalchemy2.shape import to_shape, from_shape
from shapel... | models.py | import hashlib
import bcrypt
from datetime import datetime
from sqlalchemy import (Column, Integer, String, Text, Boolean, DateTime,
Numeric, ForeignKey)
from sqlalchemy.orm import relationship
from geoalchemy2.types import Geometry
from geoalchemy2.shape import to_shape, from_shape
from shapel... | 0.61659 | 0.149718 |
from e621apy import Query, helpers
__all__ = [
'PostQuery',
]
class PostQuery(Query):
"""
Query designed to match Posts data
"""
RATING_SAFE = 'safe'
RATING_QUESTIONABLE = 'questionable'
RATING_EXPLICIT = 'explicit'
RATING_ALL = 'all'
def __init__(self, limit=75, page=1, tags=Non... | e621apy/core/PostQuery.py | from e621apy import Query, helpers
__all__ = [
'PostQuery',
]
class PostQuery(Query):
"""
Query designed to match Posts data
"""
RATING_SAFE = 'safe'
RATING_QUESTIONABLE = 'questionable'
RATING_EXPLICIT = 'explicit'
RATING_ALL = 'all'
def __init__(self, limit=75, page=1, tags=Non... | 0.688678 | 0.154663 |
import pytest
import responses
from nagiosplugin import CheckError
import utils
from check_pa.xml_reader import XMLReader, Finder
class TestCheckPaloAltoXML(object):
@responses.activate
def test_xml_read_response(self):
f = 'diskspace.xml'
xml_reader = XMLReader('test.de', 'test', 'test')
... | tests/test_xml_reader.py | import pytest
import responses
from nagiosplugin import CheckError
import utils
from check_pa.xml_reader import XMLReader, Finder
class TestCheckPaloAltoXML(object):
@responses.activate
def test_xml_read_response(self):
f = 'diskspace.xml'
xml_reader = XMLReader('test.de', 'test', 'test')
... | 0.446253 | 0.237443 |
from NaturalJoin import NaturalJoin, INNER_JOIN
from PositionDAO import PositionDAO
from AbstractDAO import AbstractDAO
from PickupDAO import PickupDAO
from system.PickupLink import PickupLink
from interfacebdd.Connexion import Connexion
import operator
class PickupLinkDAO(AbstractDAO):
'''
Classe PickupLinkD... | vagrant/optraj.istic.univ-rennes1.fr/src/interfacebdd/PickupLinkDAO.py | from NaturalJoin import NaturalJoin, INNER_JOIN
from PositionDAO import PositionDAO
from AbstractDAO import AbstractDAO
from PickupDAO import PickupDAO
from system.PickupLink import PickupLink
from interfacebdd.Connexion import Connexion
import operator
class PickupLinkDAO(AbstractDAO):
'''
Classe PickupLinkD... | 0.449876 | 0.184529 |
import rospy
import sys
import numpy as np
import sensor_msgs.msg
import control_msgs.msg
import trajectory_msgs.msg
from std_msgs.msg import String, Float64, Float64MultiArray
log_joints_desired = []
log_joints_actual = []
log_joints_error = []
log_timestamp = []
def callback(joint_states):
rospy.loginfo(rosp... | applications_aerotech/script/node_read_joint_states.py |
import rospy
import sys
import numpy as np
import sensor_msgs.msg
import control_msgs.msg
import trajectory_msgs.msg
from std_msgs.msg import String, Float64, Float64MultiArray
log_joints_desired = []
log_joints_actual = []
log_joints_error = []
log_timestamp = []
def callback(joint_states):
rospy.loginfo(rosp... | 0.321247 | 0.193929 |
ASCII_BOARD_TPL = """
+---+---+---+
| | | |
| | | |
| | | |
+---+---+---+
| | | |
| | | |
| | | |
+---+---+---+
| | | |
| | | |
| | | |
+---+---+---+
""".strip()
class Sudoku(object):
def __init__(self, matrix):
self.board, self.rows, self.columns, self.boxes... | sudoku.py | ASCII_BOARD_TPL = """
+---+---+---+
| | | |
| | | |
| | | |
+---+---+---+
| | | |
| | | |
| | | |
+---+---+---+
| | | |
| | | |
| | | |
+---+---+---+
""".strip()
class Sudoku(object):
def __init__(self, matrix):
self.board, self.rows, self.columns, self.boxes... | 0.499023 | 0.413655 |
import glob
import os.path
import pandas as pd
import argparse
import numpy as np
import scipy.stats
from scipy.stats import beta
#V0.1.2
BETA_SHAPE1_MIN = 0.1
BETA_SHAPE1_MAX = 10
BETA_SHAPE2_MIN_CIS = 1
BETA_SHAPE2_MIN_TRANS = 5
BETA_SHAPE2_MAX_CIS = 1000000
BETA_SHAPE2_MAX_TRANS = 100000000
def estimate_beta_funct... | Limix_QTL/post_processing/global_fdr_estimation.py | import glob
import os.path
import pandas as pd
import argparse
import numpy as np
import scipy.stats
from scipy.stats import beta
#V0.1.2
BETA_SHAPE1_MIN = 0.1
BETA_SHAPE1_MAX = 10
BETA_SHAPE2_MIN_CIS = 1
BETA_SHAPE2_MIN_TRANS = 5
BETA_SHAPE2_MAX_CIS = 1000000
BETA_SHAPE2_MAX_TRANS = 100000000
def estimate_beta_funct... | 0.189521 | 0.276923 |
from __future__ import absolute_import
import unittest
import datetime
import kubernetes.client
from kubernetes.client.models.io_xk8s_cluster_controlplane_v1alpha3_aws_managed_control_plane_status_network_security_groups import IoXK8sClusterControlplaneV1alpha3AWSManagedControlPlaneStatusNetworkSecurityGroups # noqa... | kubernetes/test/test_io_xk8s_cluster_controlplane_v1alpha3_aws_managed_control_plane_status_network_security_groups.py | from __future__ import absolute_import
import unittest
import datetime
import kubernetes.client
from kubernetes.client.models.io_xk8s_cluster_controlplane_v1alpha3_aws_managed_control_plane_status_network_security_groups import IoXK8sClusterControlplaneV1alpha3AWSManagedControlPlaneStatusNetworkSecurityGroups # noqa... | 0.59972 | 0.11808 |
from functions_global import *
import numpy as np
import pandas as pd
from scipy.optimize import differential_evolution
# Cost function
costfn = rmse
# We start by loading the raw data and tidying it up.
# It contains 4 data points per vaccine configuration per time point.
dataRaw = pd.read_csv('../../data/VNA.csv')
... | code/model-A/bootstrap_base.py | from functions_global import *
import numpy as np
import pandas as pd
from scipy.optimize import differential_evolution
# Cost function
costfn = rmse
# We start by loading the raw data and tidying it up.
# It contains 4 data points per vaccine configuration per time point.
dataRaw = pd.read_csv('../../data/VNA.csv')
... | 0.370225 | 0.347786 |
import numpy as np
def free_energy(weights, max_energy=None, zero_point_energy=1.0e-12,
supermax_value=np.nan):
"""Perform a transformation of probability weights to free energies.
The free energy of probabilities is a transformation of -ln(p)
where p is the properly normalized probability... | src/geomm/free_energy.py | import numpy as np
def free_energy(weights, max_energy=None, zero_point_energy=1.0e-12,
supermax_value=np.nan):
"""Perform a transformation of probability weights to free energies.
The free energy of probabilities is a transformation of -ln(p)
where p is the properly normalized probability... | 0.94656 | 0.807574 |
import math
from math import log10, sqrt
import matplotlib.pyplot as plt
from io import BytesIO
import discord
import discord.commands as scmd
from discord.ext import commands
import si_prefix
from random import randint
from thatkitebot.backend import util
from thatkitebot.backend import pcb_mod
class InputDifferenc... | thatkitebot/cogs/electronics.py |
Width = {self.width}mils
<---->
┌──┐
───┴──┴───
Copper weight = {self.thicc}oz/ft²
Max Current = {self.current}A
ΔTemperature = {self.temp}°C
Internal layer? {self.internal}
```
"""
else:
return """
```
Width = {self.width}mils
<---->
┌──┐
─... | 0.775265 | 0.348728 |
from typing import Any, List, Optional
from sqlalchemy.orm import declared_attr
from sqlmodel import Field, Session, SQLModel, create_engine
class Prep(SQLModel, table=True):
address: str = Field(primary_key=True)
name: Optional[str] = Field(None, index=False)
country: Optional[str] = Field(None, index=... | icon_governance/models/preps.py | from typing import Any, List, Optional
from sqlalchemy.orm import declared_attr
from sqlmodel import Field, Session, SQLModel, create_engine
class Prep(SQLModel, table=True):
address: str = Field(primary_key=True)
name: Optional[str] = Field(None, index=False)
country: Optional[str] = Field(None, index=... | 0.869701 | 0.395601 |
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from chats.models import *
from profiles.models import *
DEFAULT_AUTHOR = '<NAME>'
DEFAULT_PASSWORD = '<PASSWORD>'
LOREM = 'Lorem ipsum dolor sit amet.'
class ChatTest(TestCase):
def test_friendgro... | apps/chats/tests.py | from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from chats.models import *
from profiles.models import *
DEFAULT_AUTHOR = '<NAME>'
DEFAULT_PASSWORD = '<PASSWORD>'
LOREM = 'Lorem ipsum dolor sit amet.'
class ChatTest(TestCase):
def test_friendgro... | 0.41941 | 0.093388 |
import httplib, json
URL = "elections.huffingtonpost.com"
API = "/pollster/api/%s"
STATES = [
"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID",
"IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS",
"MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "N... | api_requester.py | import httplib, json
URL = "elections.huffingtonpost.com"
API = "/pollster/api/%s"
STATES = [
"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID",
"IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS",
"MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "N... | 0.078634 | 0.176441 |
import sys
import numpy as np
import matplotlib.pyplot as plt
def computeU(rho, u, p, gamma):
return np.array([rho, rho * u, rho * (p / ((gamma - 1) * rho)) + ((u ** 2) / 2)])
def computeF(u, gamma):
F1 = u[1]
F2 = (u[1] ** 2) / u[0] + (gamma - 1) * (u[2] - 0.5 * (u[1] ** 2) / u[0])
F3 = (u[2] + (... | sod.py | import sys
import numpy as np
import matplotlib.pyplot as plt
def computeU(rho, u, p, gamma):
return np.array([rho, rho * u, rho * (p / ((gamma - 1) * rho)) + ((u ** 2) / 2)])
def computeF(u, gamma):
F1 = u[1]
F2 = (u[1] ** 2) / u[0] + (gamma - 1) * (u[2] - 0.5 * (u[1] ** 2) / u[0])
F3 = (u[2] + (... | 0.41478 | 0.598635 |
import numpy as np
import sys
from lib import fdutil, rasterutils
STRATEGIES = ['5-crossval_vertical', '5-crossval_horizontal']
def _verify_inputs(fn_raster_in, allocation_strategy, test_stripe, crossval_training):
"""
Verifies the inputs of the function allocate_data().
:param fn_raster_in: ... | lib/data_allocation.py | import numpy as np
import sys
from lib import fdutil, rasterutils
STRATEGIES = ['5-crossval_vertical', '5-crossval_horizontal']
def _verify_inputs(fn_raster_in, allocation_strategy, test_stripe, crossval_training):
"""
Verifies the inputs of the function allocate_data().
:param fn_raster_in: ... | 0.664323 | 0.562357 |
import endpoints
import json
from protorpc import remote
from google.appengine.runtime import DeadlineExceededError
from django.contrib.auth import get_user_model
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import PermissionDenied
from greenday_api.api import greenday_api
f... | appengine/src/greenday_channel/endpoints_api/api.py | import endpoints
import json
from protorpc import remote
from google.appengine.runtime import DeadlineExceededError
from django.contrib.auth import get_user_model
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import PermissionDenied
from greenday_api.api import greenday_api
f... | 0.513425 | 0.05752 |
from mindpile.Mapping.types import InPort, Local, List
from mindpile.Mapping.utils import MethodCall, Requires, Setup
@Setup
def colourSetup():
return '''
from ev3dev2.sensor.lego import ColorSensor
'''
@MethodCall(target="ColorValue.vix", Port=InPort, Color=int)
@Requires(colourSetup)
def colourValue... | mindpile/Mapping/sensors/colour.py | from mindpile.Mapping.types import InPort, Local, List
from mindpile.Mapping.utils import MethodCall, Requires, Setup
@Setup
def colourSetup():
return '''
from ev3dev2.sensor.lego import ColorSensor
'''
@MethodCall(target="ColorValue.vix", Port=InPort, Color=int)
@Requires(colourSetup)
def colourValue... | 0.665628 | 0.227223 |
import argparse
import pafy
import os
import time
import sys
import threading
import random
from vlcyt.command_handler import CommandHandler
from colorama import Fore, Back, Style
class VLCYT:
"""
Stream YouTube playlist audio in VLC behind the scenes from the command line.
"""
command_string = f"{Fo... | vlcyt/app.py | import argparse
import pafy
import os
import time
import sys
import threading
import random
from vlcyt.command_handler import CommandHandler
from colorama import Fore, Back, Style
class VLCYT:
"""
Stream YouTube playlist audio in VLC behind the scenes from the command line.
"""
command_string = f"{Fo... | 0.29381 | 0.091544 |
import pprint
import re # noqa: F401
import six
class TsoaPickAgentConnectionOrAgentConnectionIdOrAgentConnectionUpdatedAtOrAgentConnectionLinkTagOrAgentConnectionStatusOrAgentConnectionStatusReason_(
object
):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the... | syntropy_sdk/models/tsoa_pick_agent_connection_or_agent_connection_id_or_agent_connection_updated_at_or_agent_connection_link_tag_or_agent_connection_status_or_agent_connection_status_reason_.py | import pprint
import re # noqa: F401
import six
class TsoaPickAgentConnectionOrAgentConnectionIdOrAgentConnectionUpdatedAtOrAgentConnectionLinkTagOrAgentConnectionStatusOrAgentConnectionStatusReason_(
object
):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the... | 0.591959 | 0.065038 |
from datetime import datetime, time
from operator import or_
from flask import redirect, session, flash, request
from functools import wraps
from flask.helpers import url_for
from sqlalchemy.orm import relation
from models import *
def create_event(title, start, end, capacity, location, coach, private):
"""Create... | functions.py | from datetime import datetime, time
from operator import or_
from flask import redirect, session, flash, request
from functools import wraps
from flask.helpers import url_for
from sqlalchemy.orm import relation
from models import *
def create_event(title, start, end, capacity, location, coach, private):
"""Create... | 0.544075 | 0.089893 |
from common import *
from scrape import Scraper
from dataminer import Miner
from SentimentAnalysis.web_scraper import ForumSpider
import praw
import scrapy
import pickle
import os
import sys
from datetime import datetime, date, time
from time import mktime
from bs4 import BeautifulSoup
from scrapy.crawler import Crawl... | datamining/test.py | from common import *
from scrape import Scraper
from dataminer import Miner
from SentimentAnalysis.web_scraper import ForumSpider
import praw
import scrapy
import pickle
import os
import sys
from datetime import datetime, date, time
from time import mktime
from bs4 import BeautifulSoup
from scrapy.crawler import Crawl... | 0.21767 | 0.126515 |
import nrefocus
import numpy as np
import qpimage
from skimage.restoration import unwrap
from ._bhfield import simulate_sphere
def field2ap_corr(field):
"""Determine amplitude and offset-corrected phase from a field
The phase jumps sometimes appear after phase unwrapping.
Parameters
----------
... | qpsphere/models/mod_mie.py | import nrefocus
import numpy as np
import qpimage
from skimage.restoration import unwrap
from ._bhfield import simulate_sphere
def field2ap_corr(field):
"""Determine amplitude and offset-corrected phase from a field
The phase jumps sometimes appear after phase unwrapping.
Parameters
----------
... | 0.93453 | 0.800068 |
import requests
from fastapi import FastAPI
from fastapi.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
from error_handlers.warnings import WarningJSON
from error_handlers.exceptions import ExceptionJSON
from training.training import train_models
from datab... | ml-core/main.py | import requests
from fastapi import FastAPI
from fastapi.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
from error_handlers.warnings import WarningJSON
from error_handlers.exceptions import ExceptionJSON
from training.training import train_models
from datab... | 0.651355 | 0.087252 |
import datetime
from typing import Dict, List, Union
import pytz
from django.conf import settings
from django.utils.timezone import get_default_timezone
from opening_hours.decorators import datetime_args_to_default_timezone
from opening_hours.hours import (
Period,
TimeElement,
get_opening_hours,
get_... | opening_hours/utils/opening_hours_client.py | import datetime
from typing import Dict, List, Union
import pytz
from django.conf import settings
from django.utils.timezone import get_default_timezone
from opening_hours.decorators import datetime_args_to_default_timezone
from opening_hours.hours import (
Period,
TimeElement,
get_opening_hours,
get_... | 0.727975 | 0.347897 |
from scenarios import *
scenario = (
send_stanza("<iq from='{jid_one}/{resource_one}' to='#foo%{irc_server_one}' id='1' type='get'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>"),
expect_stanza("/iq[@from='#foo%{irc_server_one}'][@to='{jid_one}/{resource_one}'][@type='result']/disco_info:query",
... | tests/end_to_end/scenarios/muc_disco_info.py | from scenarios import *
scenario = (
send_stanza("<iq from='{jid_one}/{resource_one}' to='#foo%{irc_server_one}' id='1' type='get'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>"),
expect_stanza("/iq[@from='#foo%{irc_server_one}'][@to='{jid_one}/{resource_one}'][@type='result']/disco_info:query",
... | 0.381104 | 0.145935 |
# What is the smallest positive number
# that is evenly divisible by all of the numbers from 1 to 20?
import math
def primeFactors(n):
""" This function returns a list of prime factors for n
--param
n : integer
--return
list : prime factors of n
"""
if n < 2:
return []
elif n i... | q5.py |
# What is the smallest positive number
# that is evenly divisible by all of the numbers from 1 to 20?
import math
def primeFactors(n):
""" This function returns a list of prime factors for n
--param
n : integer
--return
list : prime factors of n
"""
if n < 2:
return []
elif n i... | 0.597373 | 0.578984 |
import asyncio
from sspq import *
from argparse import ArgumentParser
async def _send_msg(message: str, host: str, port: int, retrys: int):
client = Client()
await client.connect(host=host, port=port)
await client.send(message.encode(), retrys=retrys)
await client.disconnect()
async def _receive_ms... | client.py | import asyncio
from sspq import *
from argparse import ArgumentParser
async def _send_msg(message: str, host: str, port: int, retrys: int):
client = Client()
await client.connect(host=host, port=port)
await client.send(message.encode(), retrys=retrys)
await client.disconnect()
async def _receive_ms... | 0.381796 | 0.057785 |
import pytest
import raccoon as rc
from raccoon.utils import assert_series_equal
try:
# noinspection PyUnresolvedReferences
from blist import blist
except ImportError:
pytest.skip("blist is not installed, skipping tests.", allow_module_level=True)
def test_assert_series_equal():
srs1 = rc.Series([1,... | tests/test_dropin/test_series_blist.py | import pytest
import raccoon as rc
from raccoon.utils import assert_series_equal
try:
# noinspection PyUnresolvedReferences
from blist import blist
except ImportError:
pytest.skip("blist is not installed, skipping tests.", allow_module_level=True)
def test_assert_series_equal():
srs1 = rc.Series([1,... | 0.629547 | 0.818338 |
import praw
import sys
import getpass
import fresponder
import time
import settings
c_id = open("secret/client_id").read()
c_secret = open("secret/client_secret").read()
username_to_use = settings.bot_username
reddit = praw.Reddit(client_id = c_id,
client_secret = c_secret,
user_agent = settings.user_agent,
userna... | bot.py | import praw
import sys
import getpass
import fresponder
import time
import settings
c_id = open("secret/client_id").read()
c_secret = open("secret/client_secret").read()
username_to_use = settings.bot_username
reddit = praw.Reddit(client_id = c_id,
client_secret = c_secret,
user_agent = settings.user_agent,
userna... | 0.059231 | 0.067824 |
from functools import wraps
from mimetypes import guess_type
from typing import Any, AsyncGenerator, Dict, Generator, List, Tuple, Union
from falcon.asgi.response import Response as _ASGIResponse
from falcon.constants import MEDIA_HTML, MEDIA_JSON, MEDIA_TEXT
from falcon.response import Response as _Response
from falc... | falca/responses.py | from functools import wraps
from mimetypes import guess_type
from typing import Any, AsyncGenerator, Dict, Generator, List, Tuple, Union
from falcon.asgi.response import Response as _ASGIResponse
from falcon.constants import MEDIA_HTML, MEDIA_JSON, MEDIA_TEXT
from falcon.response import Response as _Response
from falc... | 0.790085 | 0.091301 |