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 unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='A_files',
fields=[
('id', models.AutoField(verbose_name='ID', serialize... | apps/porsuk/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='A_files',
fields=[
('id', models.AutoField(verbose_name='ID', serialize... | 0.638835 | 0.13612 |
import os
import pytest
NORMAL_GT_PLUS_TEST_FAILED_LOG = 'testsuite name="PlusTest" tests="2" failures="1" disabled="0" skipped="0" errors="0"'
NORMAL_GT_MINUS_TEST_FAILED_LOG = 'testsuite name="MinusTest" tests="2" failures="1" disabled="0" skipped="0" errors="0"'
LCOV_HTML_TITLE = '<tr><td class="title">LCOV - code... | test/report_qt6_test.py | import os
import pytest
NORMAL_GT_PLUS_TEST_FAILED_LOG = 'testsuite name="PlusTest" tests="2" failures="1" disabled="0" skipped="0" errors="0"'
NORMAL_GT_MINUS_TEST_FAILED_LOG = 'testsuite name="MinusTest" tests="2" failures="1" disabled="0" skipped="0" errors="0"'
LCOV_HTML_TITLE = '<tr><td class="title">LCOV - code... | 0.617513 | 0.311977 |
import argparse
import glob
from pathlib import Path
import rospy
from sensor_msgs.msg import PointCloud2, PointCloud
from sensor_msgs import point_cloud2
from visualization_msgs.msg import MarkerArray
from visualization_msgs.msg import Marker
from scipy.spatial.transform import Rotation as R
import time
try:
i... | tools/demo_ros.py | import argparse
import glob
from pathlib import Path
import rospy
from sensor_msgs.msg import PointCloud2, PointCloud
from sensor_msgs import point_cloud2
from visualization_msgs.msg import MarkerArray
from visualization_msgs.msg import Marker
from scipy.spatial.transform import Rotation as R
import time
try:
i... | 0.632503 | 0.204163 |
from __future__ import unicode_literals
from django.db import models, IntegrityError
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Timestamped(models.Model):
"""
Adds created and updated fields to a model.
"""
created ... | ross/core/models.py | from __future__ import unicode_literals
from django.db import models, IntegrityError
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Timestamped(models.Model):
"""
Adds created and updated fields to a model.
"""
created ... | 0.61855 | 0.125226 |
from fastapi import APIRouter, status, Depends, HTTPException
from typing import List
from sqlalchemy.orm import Session
from src.schemas.schemas import Servico
from src.infra.sqlalchemy.config.database import get_db
from src.infra.sqlalchemy.repositorios.repositorio_servico \
import RepositorioServico
router = AP... | src/routers/rotas_servicos.py | from fastapi import APIRouter, status, Depends, HTTPException
from typing import List
from sqlalchemy.orm import Session
from src.schemas.schemas import Servico
from src.infra.sqlalchemy.config.database import get_db
from src.infra.sqlalchemy.repositorios.repositorio_servico \
import RepositorioServico
router = AP... | 0.438064 | 0.049062 |
from mmdet.apis import init_detector, inference_detector, show_result
import numpy as np
import os
import cv2
from libs.pascal_voc_io import PascalVocWriter
from PyQt5.QtCore import *
# 首先下载模型文件https://s3.ap-northeast-2.amazonaws.com/open-mmlab/mmdetection/models/faster_rcnn_r50_fpn_1x_20181010-3d1b3351.pth
class detec... | libs/nanodetect.py | from mmdet.apis import init_detector, inference_detector, show_result
import numpy as np
import os
import cv2
from libs.pascal_voc_io import PascalVocWriter
from PyQt5.QtCore import *
# 首先下载模型文件https://s3.ap-northeast-2.amazonaws.com/open-mmlab/mmdetection/models/faster_rcnn_r50_fpn_1x_20181010-3d1b3351.pth
class detec... | 0.308815 | 0.183502 |
from django import forms
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.db.models import Count
import autocomplete_light
from import_export.admin import ExportMixin
from import_export.fields import Field
fro... | mozillians/groups/admin.py | from django import forms
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.db.models import Count
import autocomplete_light
from import_export.admin import ExportMixin
from import_export.fields import Field
fro... | 0.691602 | 0.106458 |
from __future__ import unicode_literals
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.utils.translation import ugettext as _
try:
from django.core.management.commands.syncdb import Command as BaseCommand
has_s... | django_evolution/management/commands/syncdb.py |
from __future__ import unicode_literals
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.utils.translation import ugettext as _
try:
from django.core.management.commands.syncdb import Command as BaseCommand
has_s... | 0.748812 | 0.099208 |
from lxml import html
import os
import requests
import urllib.parse
import re
import progressbar
from urllib.parse import urlparse
from threading import Thread
class DownloadThread(Thread):
def __init__(self, urls, crawler, name, progressbar):
"""Инициализация потока"""
Thread.__init__(self)
... | puzzle/crawler.py | from lxml import html
import os
import requests
import urllib.parse
import re
import progressbar
from urllib.parse import urlparse
from threading import Thread
class DownloadThread(Thread):
def __init__(self, urls, crawler, name, progressbar):
"""Инициализация потока"""
Thread.__init__(self)
... | 0.246352 | 0.074299 |
import tkinter as tk
from tkinter import filedialog
import os
import getpass
import time
from shutil import copyfile
from random import randint
def ClosePopUp(*args):
popupinfo.destroy()
def CloseRoot(*args):
time.sleep(0.05)
root.destroy()
def dirIn(*args):
global directory
global path
... | mp3 Random Renamer/mp3 Random Renamer.py |
import tkinter as tk
from tkinter import filedialog
import os
import getpass
import time
from shutil import copyfile
from random import randint
def ClosePopUp(*args):
popupinfo.destroy()
def CloseRoot(*args):
time.sleep(0.05)
root.destroy()
def dirIn(*args):
global directory
global path
... | 0.074901 | 0.049773 |
import configparser
import getpass
import socket
class RawConfig:
"""Contains the ``configparser.ConfigParser`` object. Write to and
read from the ``config.ini`` file. The boolean values get written to
the file as strings, and they get read from the file into the buffer
as strings too. Not all values ... | borgini/src/config.py | import configparser
import getpass
import socket
class RawConfig:
"""Contains the ``configparser.ConfigParser`` object. Write to and
read from the ``config.ini`` file. The boolean values get written to
the file as strings, and they get read from the file into the buffer
as strings too. Not all values ... | 0.693992 | 0.266483 |
import sys
import requests
import json
def splunkd_auth_header(session_key):
return {'Authorization': 'Splunk ' + session_key}
def get_jira_settings(server_uri, session_key):
result = dict()
for k,v in get_jira_action_config(server_uri, session_key).items():
if k.startswith('param.'):
... | bin/jira_helpers.py | import sys
import requests
import json
def splunkd_auth_header(session_key):
return {'Authorization': 'Splunk ' + session_key}
def get_jira_settings(server_uri, session_key):
result = dict()
for k,v in get_jira_action_config(server_uri, session_key).items():
if k.startswith('param.'):
... | 0.129073 | 0.078501 |
import numpy as np
from scipy import integrate
from saf.euler1d.common.zndsolver import ZNDSolver
FORMAT = '22.16e'
class ScaleConverter:
"""Convert from Erpenbeck scales to scales of Sharpe and Lee&Stewart.
Additionally, convert time quantities to Abouseif&Toong scales.
Parameters
----------
... | saf/euler1d/common/scaleconverter.py | import numpy as np
from scipy import integrate
from saf.euler1d.common.zndsolver import ZNDSolver
FORMAT = '22.16e'
class ScaleConverter:
"""Convert from Erpenbeck scales to scales of Sharpe and Lee&Stewart.
Additionally, convert time quantities to Abouseif&Toong scales.
Parameters
----------
... | 0.816991 | 0.578924 |
from urllib.parse import urlsplit
import urllib3
from log import LoggerObject
urllib3.disable_warnings()
class Downloader(LoggerObject):
def __init__(self, response_processor=None, num_pools=10, **kw):
super().__init__("downloader")
if kw.get("proxy_url") is not None:
print(11)
... | t66y-spider/src/http_request/__init__.py | from urllib.parse import urlsplit
import urllib3
from log import LoggerObject
urllib3.disable_warnings()
class Downloader(LoggerObject):
def __init__(self, response_processor=None, num_pools=10, **kw):
super().__init__("downloader")
if kw.get("proxy_url") is not None:
print(11)
... | 0.339171 | 0.060752 |
import re
import json
import timeago
import numpy as np
from datetime import datetime
from django.shortcuts import render
from django.http import QueryDict
from django.http import JsonResponse
from mainapp.math import corrCoeff
from django.views.decorators.csrf import csrf_exempt
# Главная страница
def index(request)... | mainapp/views.py | import re
import json
import timeago
import numpy as np
from datetime import datetime
from django.shortcuts import render
from django.http import QueryDict
from django.http import JsonResponse
from mainapp.math import corrCoeff
from django.views.decorators.csrf import csrf_exempt
# Главная страница
def index(request)... | 0.239972 | 0.166404 |
try:
from .operation_display_py3 import OperationDisplay
from .operation_py3 import Operation
from .cluster_sku_py3 import ClusterSku
from .cluster_py3 import Cluster
from .available_clusters_list_py3 import AvailableClustersList
from .cluster_quota_configuration_properties_py3 import ClusterQu... | sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2018_01_01_preview/models/__init__.py |
try:
from .operation_display_py3 import OperationDisplay
from .operation_py3 import Operation
from .cluster_sku_py3 import ClusterSku
from .cluster_py3 import Cluster
from .available_clusters_list_py3 import AvailableClustersList
from .cluster_quota_configuration_properties_py3 import ClusterQu... | 0.328745 | 0.093471 |
import pytest
from neat.neatTypes import NeuronType
from neat.genes import Genome, MutationRates, NeuronGene, LinkGene
from neat.innovations import Innovations
from neat.population import Population, PopulationConfiguration
pop_size = 5
inputs = 2
outputs = 2
@pytest.fixture(scope='module')
def population():
pop_... | tests/test_reproduction.py | import pytest
from neat.neatTypes import NeuronType
from neat.genes import Genome, MutationRates, NeuronGene, LinkGene
from neat.innovations import Innovations
from neat.population import Population, PopulationConfiguration
pop_size = 5
inputs = 2
outputs = 2
@pytest.fixture(scope='module')
def population():
pop_... | 0.473901 | 0.771736 |
import requests
import time
import json
import yaml
import pandas as pd
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.types import Integer
def get_app_details():
# The Steam API limits 200 data in 5 miniutes time. So after every 200 data, sleep for 5 minitues.
Ns = 38400
... | src/game_details.py | import requests
import time
import json
import yaml
import pandas as pd
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.types import Integer
def get_app_details():
# The Steam API limits 200 data in 5 miniutes time. So after every 200 data, sleep for 5 minitues.
Ns = 38400
... | 0.187951 | 0.052328 |
from datetime import datetime, timedelta
from airflow.decorators import dag, task
import os, sys
sys.path.append('/opt/airflow/')
from dags.utils.liq20.updater import rounds_auctions
from dags.utils.liq20.clip import get_clipper_calls
from dags.utils.liq20.actions import get_clipper_actions
from dags.utils.liq20.dog ... | dags/mainnet_liquidations20.py |
from datetime import datetime, timedelta
from airflow.decorators import dag, task
import os, sys
sys.path.append('/opt/airflow/')
from dags.utils.liq20.updater import rounds_auctions
from dags.utils.liq20.clip import get_clipper_calls
from dags.utils.liq20.actions import get_clipper_actions
from dags.utils.liq20.dog ... | 0.346652 | 0.159119 |
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import os
import pandas as pd
from sqlalchemy import create_engine
#这个函数用来获取到化合物成分的页面url
def getdrugurl(herb):
path='D:\project\selenium\geckodriver' #win环境下驱动地址
#path='/Users/macbook/downloads/geckodriver' #mac环境下驱... | medicine/src/TCMSPs.py | import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import os
import pandas as pd
from sqlalchemy import create_engine
#这个函数用来获取到化合物成分的页面url
def getdrugurl(herb):
path='D:\project\selenium\geckodriver' #win环境下驱动地址
#path='/Users/macbook/downloads/geckodriver' #mac环境下驱... | 0.062417 | 0.089654 |
import json
import requests
import urllib.parse
from . import endpoints
class RPCWrapper(object):
def __init__(self, api_endpoint, wallet_endpoint):
self.api_endpoint = api_endpoint
self.wallet_endpoint = wallet_endpoint
def request(self, endpoint, uri, body=None):
url = urllib.parse... | pyeosio/json_rpc_wrapper.py | import json
import requests
import urllib.parse
from . import endpoints
class RPCWrapper(object):
def __init__(self, api_endpoint, wallet_endpoint):
self.api_endpoint = api_endpoint
self.wallet_endpoint = wallet_endpoint
def request(self, endpoint, uri, body=None):
url = urllib.parse... | 0.423458 | 0.099689 |
import logging
from datetime import datetime
from apscheduler.job import Job
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.date import DateTrigger
from errors import ProposalNotInFCP
from storage import Storage
log = logging.getLogger(__name__)
class FCPTimers(object):... | fcp_timers.py | import logging
from datetime import datetime
from apscheduler.job import Job
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.date import DateTrigger
from errors import ProposalNotInFCP
from storage import Storage
log = logging.getLogger(__name__)
class FCPTimers(object):... | 0.749546 | 0.312291 |
import asyncio
from config import REPLY_MESSAGE
from pyrogram import Client, errors
from pyrogram.handlers import InlineQueryHandler
from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup
from youtubesearchpython import VideosSearch
buttons = [
... | plugins/inline.py | import asyncio
from config import REPLY_MESSAGE
from pyrogram import Client, errors
from pyrogram.handlers import InlineQueryHandler
from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup
from youtubesearchpython import VideosSearch
buttons = [
... | 0.47171 | 0.161519 |
import pprint
import re
try:
from stage_check import Output
except ImportError:
import Output
try:
from stage_check import EntryTest
except ImportError:
import EntryTest
try:
from stage_check import Linux
except ImportError:
import Linux
try:
from stage_check import AbstractTest
except I... | stage_check/stage_check/TestEthtool.py | import pprint
import re
try:
from stage_check import Output
except ImportError:
import Output
try:
from stage_check import EntryTest
except ImportError:
import EntryTest
try:
from stage_check import Linux
except ImportError:
import Linux
try:
from stage_check import AbstractTest
except I... | 0.41941 | 0.18678 |
import tkinter as tk
from Halma import Halma
import Player
import sys
class Game(tk.Frame):
def __init__(self, master=None):
# Initialize game object and helpers
self.aiPlayer = int(sys.argv[1])
if self.aiPlayer == 1:
self.game = Halma(8, 1, 0)
else:
self.ga... | Runner.py |
import tkinter as tk
from Halma import Halma
import Player
import sys
class Game(tk.Frame):
def __init__(self, master=None):
# Initialize game object and helpers
self.aiPlayer = int(sys.argv[1])
if self.aiPlayer == 1:
self.game = Halma(8, 1, 0)
else:
self.ga... | 0.183996 | 0.221445 |
import logging
from logging.handlers import RotatingFileHandler, SMTPHandler
from .conf import conf
# Provide a class to allow SSL (Not TLS) connection for mail handlers by overloading the emit() method
class SSLSMTPHandler(SMTPHandler):
def emit(self, record):
try:
import smtplib
... | app/logs.py | import logging
from logging.handlers import RotatingFileHandler, SMTPHandler
from .conf import conf
# Provide a class to allow SSL (Not TLS) connection for mail handlers by overloading the emit() method
class SSLSMTPHandler(SMTPHandler):
def emit(self, record):
try:
import smtplib
... | 0.362743 | 0.059292 |
import json
import boto3
import logging
import os
ses_client = boto3.client('sesv2')
logger = logging.getLogger()
logger.setLevel(logging.getLevelName(os.getenv('lambda_logging_level', 'INFO')))
def lambda_handler(event, context):
if event['mode'] == 'create':
# Creates the template using the provided val... | Solutions/VMX2-VoicemailExpress/Code/vmx_ses_template_tool.py | import json
import boto3
import logging
import os
ses_client = boto3.client('sesv2')
logger = logging.getLogger()
logger.setLevel(logging.getLevelName(os.getenv('lambda_logging_level', 'INFO')))
def lambda_handler(event, context):
if event['mode'] == 'create':
# Creates the template using the provided val... | 0.379148 | 0.0686 |
import discord
from discord.ext import commands
import sys
sys.path.insert(1, '../functions')
from functions.cmd_print import cmd_print
from functions.embed import createSimpleEmbed
import asyncio
class Channel_settings(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command... | cogs/channel_settings.py | import discord
from discord.ext import commands
import sys
sys.path.insert(1, '../functions')
from functions.cmd_print import cmd_print
from functions.embed import createSimpleEmbed
import asyncio
class Channel_settings(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command... | 0.211661 | 0.288569 |
"""Contains the logic for `aq show map`."""
from sqlalchemy.orm import contains_eager, joinedload, subqueryload, aliased
from sqlalchemy.orm.attributes import set_committed_value
from aquilon.exceptions_ import NotFoundException
from aquilon.aqdb.model import (Archetype, Personality, HostEnvironment,
... | lib/aquilon/worker/commands/show_map.py | """Contains the logic for `aq show map`."""
from sqlalchemy.orm import contains_eager, joinedload, subqueryload, aliased
from sqlalchemy.orm.attributes import set_committed_value
from aquilon.exceptions_ import NotFoundException
from aquilon.aqdb.model import (Archetype, Personality, HostEnvironment,
... | 0.787482 | 0.290654 |
import gym
import math
import numpy as np
from ..simulator import Simulator
from ..policeman import Policeman
class SimulatorEnv(gym.Env):
def __init__(self, simulator: Simulator, map: str):
super().__init__()
self.action_space = gym.spaces.MultiDiscrete(nvec=[3, 3]) # [Left, Straight, Right], ... | autodrome/envs/env.py | import gym
import math
import numpy as np
from ..simulator import Simulator
from ..policeman import Policeman
class SimulatorEnv(gym.Env):
def __init__(self, simulator: Simulator, map: str):
super().__init__()
self.action_space = gym.spaces.MultiDiscrete(nvec=[3, 3]) # [Left, Straight, Right], ... | 0.62681 | 0.412412 |
import math
import random
import os
import sys
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import transforms, utils
from torchvision import utils as tvutils
from tq... | train.py | import math
import random
import os
import sys
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import transforms, utils
from torchvision import utils as tvutils
from tq... | 0.558809 | 0.291983 |
from __future__ import unicode_literals
import lxml.etree as et
import lxmlx.event as ev
import io
import os
BRS_NS = "http://innodatalabs.com/brs"
BRS_B = et.QName(BRS_NS, 'b').text
BRS_R = et.QName(BRS_NS, 'r').text
BRS_S = et.QName(BRS_NS, 's').text
def parse_brs(binary_data):
'''
Parses BRS XML and prov... | ilabs/brs/brs.py | from __future__ import unicode_literals
import lxml.etree as et
import lxmlx.event as ev
import io
import os
BRS_NS = "http://innodatalabs.com/brs"
BRS_B = et.QName(BRS_NS, 'b').text
BRS_R = et.QName(BRS_NS, 'r').text
BRS_S = et.QName(BRS_NS, 's').text
def parse_brs(binary_data):
'''
Parses BRS XML and prov... | 0.573201 | 0.326137 |
import torch
import torch.nn as nn
import einops
from T2T_Transformer import T2TModule
from layers import SinusoidalEmbedding, TransformerEncoder
class T2TViT(nn.Module):
def __init__(self, img_size: int = 224, in_channels: int = 3,
num_classes: int = 1000, embed_dim: int = 768, depth: int = 12,
... | T2T_Transformer/t2t_transformer.py | import torch
import torch.nn as nn
import einops
from T2T_Transformer import T2TModule
from layers import SinusoidalEmbedding, TransformerEncoder
class T2TViT(nn.Module):
def __init__(self, img_size: int = 224, in_channels: int = 3,
num_classes: int = 1000, embed_dim: int = 768, depth: int = 12,
... | 0.916465 | 0.45175 |
import numpy as np
import pickle
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
# Import necessary items from Keras
from keras.models import Sequential
from keras.layers import Activation, Dropout, UpSampling2D
from keras.layers import Conv2DTranspose, Conv2D, MaxPooling2D
from ... | fully_conv_NN.py | import numpy as np
import pickle
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
# Import necessary items from Keras
from keras.models import Sequential
from keras.layers import Activation, Dropout, UpSampling2D
from keras.layers import Conv2DTranspose, Conv2D, MaxPooling2D
from ... | 0.919072 | 0.688423 |
import bottle
import datetime
import json
import hashlib
import pkg_resources
from mambas.server import models
from mambas.server import views
class MambasWebserver(bottle.Bottle):
def __init__(self, database):
super().__init__()
self.db = database
self.create_routes()
def cr... | mambas/server/webserver.py | import bottle
import datetime
import json
import hashlib
import pkg_resources
from mambas.server import models
from mambas.server import views
class MambasWebserver(bottle.Bottle):
def __init__(self, database):
super().__init__()
self.db = database
self.create_routes()
def cr... | 0.420481 | 0.051654 |
import argparse
import os
import numpy as np
from osgeo import gdal
from hyp3lib.asf_geometry import geotiff2data, data2geotiff
from hyp3lib.asf_time_series import vector_meta
def applyRasterMask(inFile, maskFile, outFile):
(data, dataGeoTrans, dataProj, dataEPSG, dataDtype, dataNoData) = \
geotiff2data(inFile... | hyp3lib/rasterMask.py | import argparse
import os
import numpy as np
from osgeo import gdal
from hyp3lib.asf_geometry import geotiff2data, data2geotiff
from hyp3lib.asf_time_series import vector_meta
def applyRasterMask(inFile, maskFile, outFile):
(data, dataGeoTrans, dataProj, dataEPSG, dataDtype, dataNoData) = \
geotiff2data(inFile... | 0.378459 | 0.500244 |
import IMLearn.learners.regressors.linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_white"
def load_data(filename: str) -> ... | exercises/city_temperature_prediction.py | import IMLearn.learners.regressors.linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_white"
def load_data(filename: str) -> ... | 0.868325 | 0.700718 |
from __future__ import print_function, unicode_literals
import tensorflow as tf
import os
import sys
from nets.PosePriorNetwork import PosePriorNetwork
from data.BinaryDbReader import BinaryDbReader
from utils.general import LearningRateScheduler
# Chose which variant to evaluate
# VARIANT = 'direct'
# VARIANT = 'bo... | trackHand/training_lifting.py | from __future__ import print_function, unicode_literals
import tensorflow as tf
import os
import sys
from nets.PosePriorNetwork import PosePriorNetwork
from data.BinaryDbReader import BinaryDbReader
from utils.general import LearningRateScheduler
# Chose which variant to evaluate
# VARIANT = 'direct'
# VARIANT = 'bo... | 0.590779 | 0.220741 |
import contextlib
import logging
import os
import random
import re
import shlex
import string
import threading
from multiprocessing import Process, Queue
from queue import Empty
from typing import TYPE_CHECKING, Dict, Generator, List, Optional, Tuple, Union
import pytest
from docker.client import DockerClient
from doc... | integration-testing/casperlabsnode_testing/casperlabsnode.py | import contextlib
import logging
import os
import random
import re
import shlex
import string
import threading
from multiprocessing import Process, Queue
from queue import Empty
from typing import TYPE_CHECKING, Dict, Generator, List, Optional, Tuple, Union
import pytest
from docker.client import DockerClient
from doc... | 0.568176 | 0.103386 |
# <codecell>
import requests, json
# <codecell>
headers = {'Content-Type': 'application/xml'}
# <headingcell level=2>
# BBOX query on NGDC Geoportal Server CSW
# <codecell>
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
# <codecell>
input='''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.... | CSW/csw_post_request-Copy0.py |
# <codecell>
import requests, json
# <codecell>
headers = {'Content-Type': 'application/xml'}
# <headingcell level=2>
# BBOX query on NGDC Geoportal Server CSW
# <codecell>
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
# <codecell>
input='''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.... | 0.442396 | 0.157979 |
import numpy as np
import pytest
import rasterio
from rasterio import windows
DATA_WINDOW = ((3, 5), (2, 6))
def test_index():
with rasterio.open('tests/data/RGB.byte.tif') as src:
left, bottom, right, top = src.bounds
assert src.index(left, top) == (0, 0)
assert src.index(right, top) ==... | tests/test_indexing.py | import numpy as np
import pytest
import rasterio
from rasterio import windows
DATA_WINDOW = ((3, 5), (2, 6))
def test_index():
with rasterio.open('tests/data/RGB.byte.tif') as src:
left, bottom, right, top = src.bounds
assert src.index(left, top) == (0, 0)
assert src.index(right, top) ==... | 0.726037 | 0.716467 |
"""Tests for rom_operator_inference._core._intrusive.py."""
import pytest
import numpy as np
from scipy import linalg as la
import rom_operator_inference as roi
from . import MODEL_FORMS, MODEL_KEYS, _get_data, _get_operators
# Mixins (private) ============================================================
class Tes... | tests/_core/test_intrusive.py | """Tests for rom_operator_inference._core._intrusive.py."""
import pytest
import numpy as np
from scipy import linalg as la
import rom_operator_inference as roi
from . import MODEL_FORMS, MODEL_KEYS, _get_data, _get_operators
# Mixins (private) ============================================================
class Tes... | 0.805861 | 0.444203 |
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe:ingredie... | app/recipe/tests/test_ingrediants.py | from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe:ingredie... | 0.58948 | 0.284343 |
from datetime import date, datetime
from fairgraph.base_v3 import KGObjectV3, IRI
from fairgraph.fields import Field
class CommonCoordinateSpace(KGObjectV3):
"""
"""
default_space = "atlas"
type = ["https://openminds.ebrains.eu/sands/CommonCoordinateSpace"]
context = {
"schema": "h... | fairgraph/openminds/sands/atlas/common_coordinate_space.py |
from datetime import date, datetime
from fairgraph.base_v3 import KGObjectV3, IRI
from fairgraph.fields import Field
class CommonCoordinateSpace(KGObjectV3):
"""
"""
default_space = "atlas"
type = ["https://openminds.ebrains.eu/sands/CommonCoordinateSpace"]
context = {
"schema": "h... | 0.726523 | 0.492615 |
import os
from setuptools import setup, find_packages
__doc__ = """Admin interface for editing thumbnail aliases"""
project_name = 'easy-thumbnails-admin'
app_name = 'easy_thumbnails_admin'
def exec_file(filepath):
global_vars = {}
with open(filepath) as f:
code = compile(f.read(), os.path.split(fil... | setup.py | import os
from setuptools import setup, find_packages
__doc__ = """Admin interface for editing thumbnail aliases"""
project_name = 'easy-thumbnails-admin'
app_name = 'easy_thumbnails_admin'
def exec_file(filepath):
global_vars = {}
with open(filepath) as f:
code = compile(f.read(), os.path.split(fil... | 0.293303 | 0.082328 |
from odoo import api, fields, models
class FleetBattery(models.Model):
_name = "fleet.battery"
_description = "Battery"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char(
string="S/N",
)
model = fields.Char(
string="Model",
)
date_start = fields.Dat... | odoo/custom/src/private/fleet_ebike/models/fleet_battery.py |
from odoo import api, fields, models
class FleetBattery(models.Model):
_name = "fleet.battery"
_description = "Battery"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char(
string="S/N",
)
model = fields.Char(
string="Model",
)
date_start = fields.Dat... | 0.596668 | 0.294057 |
import pickle
import unittest
import functools
from ..problems import *
from ..operators import RandomGenerator
class TestProblemsSimple(unittest.TestCase):
def test_DTLZ1(self):
self._run_test(DTLZ1(2))
def test_DTLZ2(self):
self._run_test(DTLZ2(2))
def test_DTLZ3(self):
... | platypus/tests/test_problems.py | import pickle
import unittest
import functools
from ..problems import *
from ..operators import RandomGenerator
class TestProblemsSimple(unittest.TestCase):
def test_DTLZ1(self):
self._run_test(DTLZ1(2))
def test_DTLZ2(self):
self._run_test(DTLZ2(2))
def test_DTLZ3(self):
... | 0.33231 | 0.510924 |
"""Utilities for Qt integration."""
from PyQt5 import QtCore, QtGui, QtWidgets
def get_elided_text(rect, font, text):
"""Get elided text to fit given rectangle.
Args:
rect: Rectangle which will contain the text. Type: QtCore.QRect
font: Font used to render text. Type: QtCore.QFont
te... | pomito/plugins/ui/qt/utils.py | """Utilities for Qt integration."""
from PyQt5 import QtCore, QtGui, QtWidgets
def get_elided_text(rect, font, text):
"""Get elided text to fit given rectangle.
Args:
rect: Rectangle which will contain the text. Type: QtCore.QRect
font: Font used to render text. Type: QtCore.QFont
te... | 0.901867 | 0.193109 |
import numpy as np
import scipy.stats as ss
# our scripts
import settings as st
class nz_dist(object):
def __init__(self, zmin: float = None, zmax: float = None, nzmax: int = None):
if zmin is None:
self.zmin = st.survey_zmin
else:
self.zmin = zmin
if zmax is N... | emulator/cosmology/redshift.py | import numpy as np
import scipy.stats as ss
# our scripts
import settings as st
class nz_dist(object):
def __init__(self, zmin: float = None, zmax: float = None, nzmax: int = None):
if zmin is None:
self.zmin = st.survey_zmin
else:
self.zmin = zmin
if zmax is N... | 0.793426 | 0.390069 |
from abc import ABC, abstractmethod
from typing import List
from math import ceil
from ..core.base_position import BasePosition
class BaseRoute(ABC):
"""
Contains information about a route - duration, distace, coordinates
"""
def __init__(
self,
created_at: int,
coordinates: L... | simobility/routers/base_route.py | from abc import ABC, abstractmethod
from typing import List
from math import ceil
from ..core.base_position import BasePosition
class BaseRoute(ABC):
"""
Contains information about a route - duration, distace, coordinates
"""
def __init__(
self,
created_at: int,
coordinates: L... | 0.946188 | 0.546436 |
def frequencyList(input1,utf8=False):
'''
Returns a list of the frequency of characters in a string as fractions of the total
>>> frequencyList("abcde",utf8=True)
[0.2, 0.2, 0.2, 0.2, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
>>> frequencyList(b... | src/core.py | def frequencyList(input1,utf8=False):
'''
Returns a list of the frequency of characters in a string as fractions of the total
>>> frequencyList("abcde",utf8=True)
[0.2, 0.2, 0.2, 0.2, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
>>> frequencyList(b... | 0.350199 | 0.597784 |
from django.db import IntegrityError
from . import types, models
from graphql_jwt.decorators import login_required
from django.utils import timezone
from django.db.models import Q
from django.db.models.expressions import RawSQL
from locations import models as location_models
from notifications import models as notif... | pinner/locations/queries.py | from django.db import IntegrityError
from . import types, models
from graphql_jwt.decorators import login_required
from django.utils import timezone
from django.db.models import Q
from django.db.models.expressions import RawSQL
from locations import models as location_models
from notifications import models as notif... | 0.458349 | 0.103205 |
import textwrap
import unittest
from makani.lib.python.pack2 import parser
class TestParserEnum(unittest.TestCase):
def testEnum(self):
text = textwrap.dedent("""\
enum8 test_enum8 {
VALNEG = -1,
VAL0 = 0,
VAL1 = 1,
VAL2 = 0b10,
VAL_MAX = 0x7f,
... | lib/python/pack2/tests/parser_test_enum.py |
import textwrap
import unittest
from makani.lib.python.pack2 import parser
class TestParserEnum(unittest.TestCase):
def testEnum(self):
text = textwrap.dedent("""\
enum8 test_enum8 {
VALNEG = -1,
VAL0 = 0,
VAL1 = 1,
VAL2 = 0b10,
VAL_MAX = 0x7f,
... | 0.568296 | 0.293303 |
import json
from urllib.parse import urlencode
from django.views.generic import ListView, TemplateView
from website.apps.projects.models import Project
MODEL_FACETS = {
'package': ('pkg_type', 'license', 'taxonomy',),
'project': ('countries', 'taxonomy', 'collaborators', 'num_users'),
'user': ('countries... | src/website/apps/core/views.py | import json
from urllib.parse import urlencode
from django.views.generic import ListView, TemplateView
from website.apps.projects.models import Project
MODEL_FACETS = {
'package': ('pkg_type', 'license', 'taxonomy',),
'project': ('countries', 'taxonomy', 'collaborators', 'num_users'),
'user': ('countries... | 0.37319 | 0.139367 |
import os
import re
import urllib2
from zipfile import ZipFile
import csv
import cPickle as pickle
def downloadNames():
u = urllib2.urlopen('https://www.ssa.gov/oact/babynames/names.zip')
localFile = open('names.zip', 'w')
localFile.write(u.read())
localFile.close()
def getNameList():
if not os.p... | src/Gender_Prediction.py |
import os
import re
import urllib2
from zipfile import ZipFile
import csv
import cPickle as pickle
def downloadNames():
u = urllib2.urlopen('https://www.ssa.gov/oact/babynames/names.zip')
localFile = open('names.zip', 'w')
localFile.write(u.read())
localFile.close()
def getNameList():
if not os.p... | 0.045469 | 0.068257 |
import argparse
from matplotlib import pyplot as plt
from condel._DEPRECATED_.weights import load_weights
from transfic.cmdhelper import DefaultCommandHelper
def main():
parser = argparse.ArgumentParser(
description="Plot cutoffs")
cmd = DefaultCommandHelper(parser)
parser.add_argument("path", metavar="PATH"... | chapter3/transfic/transfic/_DEPRECATED_/cutoffs_plot.py |
import argparse
from matplotlib import pyplot as plt
from condel._DEPRECATED_.weights import load_weights
from transfic.cmdhelper import DefaultCommandHelper
def main():
parser = argparse.ArgumentParser(
description="Plot cutoffs")
cmd = DefaultCommandHelper(parser)
parser.add_argument("path", metavar="PATH"... | 0.534855 | 0.355887 |
import pygame
from os import environ
from CarPiLogging import log
from ConfigParser import ConfigParser
IO_CONFIG_SECTION = 'IO'
IO_CONFIG_KEY_OUTPUT_DEVICE = 'output'
IO_CONFIG_KEY_MOUSE_DRIVER = 'mouse_driver'
IO_CONFIG_KEY_MOUSE_DEVICE = 'mouse_device'
ENV_OUTPUT = 'SDL_FBDEV'
ENV_MOUSE_DRIVER = 'SDL_MOUSEDRV'
ENV... | CarPiUI/PygameUtils.py | import pygame
from os import environ
from CarPiLogging import log
from ConfigParser import ConfigParser
IO_CONFIG_SECTION = 'IO'
IO_CONFIG_KEY_OUTPUT_DEVICE = 'output'
IO_CONFIG_KEY_MOUSE_DRIVER = 'mouse_driver'
IO_CONFIG_KEY_MOUSE_DEVICE = 'mouse_device'
ENV_OUTPUT = 'SDL_FBDEV'
ENV_MOUSE_DRIVER = 'SDL_MOUSEDRV'
ENV... | 0.391988 | 0.057732 |
import requests
import json
from langdetect import detect
import unicodedata
BASE_API = "http://localhost:8000/api/search/search"
def run_query(query, api=BASE_API):
""""""
if query and api:
r = requests.post(url=api, json=query)
if r.status_code == requests.codes.ok:
return r.sta... | search_service/search/manualtests/queries.py | import requests
import json
from langdetect import detect
import unicodedata
BASE_API = "http://localhost:8000/api/search/search"
def run_query(query, api=BASE_API):
""""""
if query and api:
r = requests.post(url=api, json=query)
if r.status_code == requests.codes.ok:
return r.sta... | 0.26827 | 0.316911 |
import math
from typing import List, Tuple, Union
import cv2
import dataclasses
import numpy as np
from mediapipe.framework.formats import landmark_pb2
PRESENCE_THRESHOLD = 0.5
RGB_CHANNELS = 3
RED_COLOR = (0, 0, 255)
VISIBILITY_THRESHOLD = 0.5
@dataclasses.dataclass
class DrawingSpec:
# Color for drawing the an... | mediapipe/python/solutions/drawing_utils.py | import math
from typing import List, Tuple, Union
import cv2
import dataclasses
import numpy as np
from mediapipe.framework.formats import landmark_pb2
PRESENCE_THRESHOLD = 0.5
RGB_CHANNELS = 3
RED_COLOR = (0, 0, 255)
VISIBILITY_THRESHOLD = 0.5
@dataclasses.dataclass
class DrawingSpec:
# Color for drawing the an... | 0.854308 | 0.419113 |
from talon import Context, Module, app, actions, speech_system
from talon import canvas, ui
from talon.types import Rect
mod = Module()
modes = {
"admin": "enable extra administration commands terminal (docker, etc)",
"debug": "a way to force debugger commands to be loaded",
"gdb": "a way to force gdb com... | modes/modes.py | from talon import Context, Module, app, actions, speech_system
from talon import canvas, ui
from talon.types import Rect
mod = Module()
modes = {
"admin": "enable extra administration commands terminal (docker, etc)",
"debug": "a way to force debugger commands to be loaded",
"gdb": "a way to force gdb com... | 0.599485 | 0.133246 |
import entity
import config as cfg
from affine import Affine
class Exporter:
def __init__(self):
super().__init__()
def draw(self, ent, transform=None):
if transform is None:
transform = entity.Transform(scale=cfg.EXPORTER_SCALE_DEFAULT)
if isinstance(ent, entity.Point):
... | exporter/exporter.py | import entity
import config as cfg
from affine import Affine
class Exporter:
def __init__(self):
super().__init__()
def draw(self, ent, transform=None):
if transform is None:
transform = entity.Transform(scale=cfg.EXPORTER_SCALE_DEFAULT)
if isinstance(ent, entity.Point):
... | 0.646572 | 0.217234 |
from ...abc import Expression
from ..value.eventexpr import EVENT
from ..value.eventexpr import KWARGS
from ..value.eventexpr import ARG
from ..value.valueexpr import VALUE
from ..utility.context import CONTEXT
class ITEM(Expression):
"""
Get the item from a dictionary.
There are two forms:
1) Mapping form
!ITEM... | bspump/declarative/expression/datastructs/itemexpr.py | from ...abc import Expression
from ..value.eventexpr import EVENT
from ..value.eventexpr import KWARGS
from ..value.eventexpr import ARG
from ..value.valueexpr import VALUE
from ..utility.context import CONTEXT
class ITEM(Expression):
"""
Get the item from a dictionary.
There are two forms:
1) Mapping form
!ITEM... | 0.179531 | 0.244081 |
import asyncio
import json
from typing import Any, Coroutine, List, TYPE_CHECKING
import auraxium
from auraxium import census
from auraxium.types import CensusData
# Slightly sketchy double-import to appease Pylance
if TYPE_CHECKING:
from ._queries import amend_query, get_collections
from ._utils import SERVI... | tools/fetch_examples.py | import asyncio
import json
from typing import Any, Coroutine, List, TYPE_CHECKING
import auraxium
from auraxium import census
from auraxium.types import CensusData
# Slightly sketchy double-import to appease Pylance
if TYPE_CHECKING:
from ._queries import amend_query, get_collections
from ._utils import SERVI... | 0.617282 | 0.208904 |
import datetime
import filecmp
import os
import shutil
import pytest
from exports.ht_bib_full import ht_bib_full
from lib.utils import ConsoleMessenger
@pytest.fixture
def env_setup(td_tmpdir, monkeypatch):
# use tmpdir configuration, export-path and cache-path.
monkeypatch.setenv(
"ZEPHIR_OVERRIDE_... | zephir-exports/tests/exports/test_ht_bib_full.py | import datetime
import filecmp
import os
import shutil
import pytest
from exports.ht_bib_full import ht_bib_full
from lib.utils import ConsoleMessenger
@pytest.fixture
def env_setup(td_tmpdir, monkeypatch):
# use tmpdir configuration, export-path and cache-path.
monkeypatch.setenv(
"ZEPHIR_OVERRIDE_... | 0.135861 | 0.151529 |
from .base import Actor, Value, ActorCritic, construcConv, construcLinear,\
forwardConv, forwardLinear, layersFromConfig
from rofl.functions.const import *
from rofl.functions.functions import Texp, Tcat, F, outputFromGymSpace, inputFromGymSpace
from rofl.functions.distributions import Categorical, Normal
from... | rofl/networks/pg.py | from .base import Actor, Value, ActorCritic, construcConv, construcLinear,\
forwardConv, forwardLinear, layersFromConfig
from rofl.functions.const import *
from rofl.functions.functions import Texp, Tcat, F, outputFromGymSpace, inputFromGymSpace
from rofl.functions.distributions import Categorical, Normal
from... | 0.809201 | 0.233914 |
"""User models."""
import datetime as dt
from dataclasses import dataclass
from flask_login import UserMixin
from ..extensions import bcrypt
from .database import Column, Model, SurrogatePK, db, reference_col, relationship
@dataclass
class User(UserMixin, SurrogatePK, Model):
"""A user of the app."""
__tab... | fa_management_server/models/user.py | """User models."""
import datetime as dt
from dataclasses import dataclass
from flask_login import UserMixin
from ..extensions import bcrypt
from .database import Column, Model, SurrogatePK, db, reference_col, relationship
@dataclass
class User(UserMixin, SurrogatePK, Model):
"""A user of the app."""
__tab... | 0.715026 | 0.142143 |
from pymongo import MongoClient, ReturnDocument
import yaml
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', stream=sys.stdout, level=logging.DEBUG,
datefmt='%Y-%m-%d %H:%M:%S')
class MongoMgr:
def __init__(self):
with open('config/co... | mongo_manager.py | from pymongo import MongoClient, ReturnDocument
import yaml
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', stream=sys.stdout, level=logging.DEBUG,
datefmt='%Y-%m-%d %H:%M:%S')
class MongoMgr:
def __init__(self):
with open('config/co... | 0.247441 | 0.070592 |
import unittest, sys, subprocess, os
from tests import common_test
from bobcatlib.settings import settings
settings["quiet"] = True
class TestSampleDocument(unittest.TestCase):
"""Test case for a sample document run through Bobcat.
"""
def test(self):
"""sample document should run through with exp... | src/test_all.py | import unittest, sys, subprocess, os
from tests import common_test
from bobcatlib.settings import settings
settings["quiet"] = True
class TestSampleDocument(unittest.TestCase):
"""Test case for a sample document run through Bobcat.
"""
def test(self):
"""sample document should run through with exp... | 0.290477 | 0.40486 |
import os, sys, json, concurrent.futures, hashlib, logging, threading, time, traceback, itertools
from fnmatch import fnmatchcase
import hca
from ..networking import HTTPRequest
logger = logging.getLogger(__name__)
def page_iterator(iterator, page_size):
return iter(lambda: list(itertools.islice(iterator, page_s... | dcplib/etl/__init__.py | import os, sys, json, concurrent.futures, hashlib, logging, threading, time, traceback, itertools
from fnmatch import fnmatchcase
import hca
from ..networking import HTTPRequest
logger = logging.getLogger(__name__)
def page_iterator(iterator, page_size):
return iter(lambda: list(itertools.islice(iterator, page_s... | 0.386648 | 0.074265 |
import pickle
import numpy as np
from numpy.testing import assert_equal, assert_raises
from .. import fetch_rrlyrae, fetch_rrlyrae_templates
from nose import SkipTest
try:
# Python 3
from urllib.error import URLError
ConnectionError = ConnectionResetError
except ImportError:
# Python 2
from urllib2... | gatspy/datasets/tests/test_rrlyrae.py | import pickle
import numpy as np
from numpy.testing import assert_equal, assert_raises
from .. import fetch_rrlyrae, fetch_rrlyrae_templates
from nose import SkipTest
try:
# Python 3
from urllib.error import URLError
ConnectionError = ConnectionResetError
except ImportError:
# Python 2
from urllib2... | 0.644001 | 0.55254 |
import os
import torch
from torch import nn
from torch.nn import init
# Classes
class BatchNormModule(nn.Module):
"""
DESCRIPTION:
Module to store the batch normalisation (BN) equations to apply per timestep and layer.
The whole class has been adapted from:
https://github.com/jihunchoi/recurrent-b... | bnlstm.py |
import os
import torch
from torch import nn
from torch.nn import init
# Classes
class BatchNormModule(nn.Module):
"""
DESCRIPTION:
Module to store the batch normalisation (BN) equations to apply per timestep and layer.
The whole class has been adapted from:
https://github.com/jihunchoi/recurrent-b... | 0.945839 | 0.653763 |
import time
import logging
from assemblyline.al.common import forge, log as al_log, queue
from assemblyline.al.core.datastore import SearchException
from assemblyline.common.charset import safe_str
ds = forge.get_datastore()
DATABASE_NUM = 4
config = forge.get_config()
al_log.init_logging('workflow_filter')
log = lo... | assemblyline/assemblyline/al/run/workflow_filter.py | import time
import logging
from assemblyline.al.common import forge, log as al_log, queue
from assemblyline.al.core.datastore import SearchException
from assemblyline.common.charset import safe_str
ds = forge.get_datastore()
DATABASE_NUM = 4
config = forge.get_config()
al_log.init_logging('workflow_filter')
log = lo... | 0.327561 | 0.14627 |
import torch.nn as nn
from torch import Tensor
from typing import Tuple
from seq2seq.model.sublayers import BaseRNN
class Seq2seqEncoder(BaseRNN):
r"""
Converts low level features into higher level features
Args:
input_size (int): size of input
hidden_dim (int): the number of features in ... | seq2seq/model/encoder.py | import torch.nn as nn
from torch import Tensor
from typing import Tuple
from seq2seq.model.sublayers import BaseRNN
class Seq2seqEncoder(BaseRNN):
r"""
Converts low level features into higher level features
Args:
input_size (int): size of input
hidden_dim (int): the number of features in ... | 0.930714 | 0.75021 |
import logging
import time
from .bmctools import BMC, BMCException
RAW_CHECK_NFS_SERVICE_STATUS = '0x32 0xd8 0x06 0x01 0x01 0x00'
RAW_GET_VMEDIA_DEVICE_COUNT = '0x32 0xca %s' # (type)
RAW_SET_VMEDIA_DEVICE_COUNT = '0x32 0xcb %s %s' # (type, count)
( VMEDIA_DEVICE_TYPE_CD,
VMEDIA_DEVICE_TYPE_FD,
VMEDIA_DEVIC... | src/remoteinstaller/installer/bmc_management/falcon.py |
import logging
import time
from .bmctools import BMC, BMCException
RAW_CHECK_NFS_SERVICE_STATUS = '0x32 0xd8 0x06 0x01 0x01 0x00'
RAW_GET_VMEDIA_DEVICE_COUNT = '0x32 0xca %s' # (type)
RAW_SET_VMEDIA_DEVICE_COUNT = '0x32 0xcb %s %s' # (type, count)
( VMEDIA_DEVICE_TYPE_CD,
VMEDIA_DEVICE_TYPE_FD,
VMEDIA_DEVIC... | 0.347537 | 0.085251 |
from ast import literal_eval
from tensorflow.keras.applications import efficientnet
from tensorflow.python.keras.applications.efficientnet import preprocess_input
from custom_dataset import Image_Data_Generator
from tensorflow.keras.applications.efficientnet import EfficientNetB7, EfficientNetB0
from tensorflow.keras.a... | src/models/train_image_model_2.py | from ast import literal_eval
from tensorflow.keras.applications import efficientnet
from tensorflow.python.keras.applications.efficientnet import preprocess_input
from custom_dataset import Image_Data_Generator
from tensorflow.keras.applications.efficientnet import EfficientNetB7, EfficientNetB0
from tensorflow.keras.a... | 0.729616 | 0.225331 |
import cuxfilter
from clx.eda.analysis import Analysis
class SummaryStatistics(Analysis):
def __init__(self, dataframe):
super().__init__(dataframe)
def __summary_obj(self, series):
summary = {}
uniq_count = len(series.unique())
total = series.notna().sum()
summary["... | python/clx/eda/summary_stats.py |
import cuxfilter
from clx.eda.analysis import Analysis
class SummaryStatistics(Analysis):
def __init__(self, dataframe):
super().__init__(dataframe)
def __summary_obj(self, series):
summary = {}
uniq_count = len(series.unique())
total = series.notna().sum()
summary["... | 0.706697 | 0.4081 |
import sys
from argparse import ArgumentParser
from importlib import import_module
from itertools import chain, starmap
from pathlib import Path
from pprint import pformat
from random import choices, randint, sample
from string import ascii_letters, digits, punctuation
from typing import Callable, List, NamedTuple, Opt... | leetcode/problems/003_longest_substring_without_repeating_characters/test_solution.py | import sys
from argparse import ArgumentParser
from importlib import import_module
from itertools import chain, starmap
from pathlib import Path
from pprint import pformat
from random import choices, randint, sample
from string import ascii_letters, digits, punctuation
from typing import Callable, List, NamedTuple, Opt... | 0.663233 | 0.390708 |
import sys
import numpy as np
import pdb
if __name__ == '__main__':
if len(sys.argv) != 3:
print ('Usage: python [lane_num] [vec_size]')
exit(1)
lane_num = int(sys.argv[1])
vec_size = int(sys.argv[2])
code_str = '#ifndef _PIPE_H\n'+'#define _PIPE_H\n'
# channel_vec
pipe_depth = ... | project/device/pipe_gen_v2.py | import sys
import numpy as np
import pdb
if __name__ == '__main__':
if len(sys.argv) != 3:
print ('Usage: python [lane_num] [vec_size]')
exit(1)
lane_num = int(sys.argv[1])
vec_size = int(sys.argv[2])
code_str = '#ifndef _PIPE_H\n'+'#define _PIPE_H\n'
# channel_vec
pipe_depth = ... | 0.052851 | 0.086208 |
import os, csv, requests, json, time, sys
import scraper, config
from multiprocessing.dummy import Pool as ThreadPool
def get_recent_run():
#find the most timestamp of shops added to the archive
scraper.pprint('--get recent run')
files = os.listdir("./data")
dates = []
for f in files:
sub_... | application/analyzer.py | import os, csv, requests, json, time, sys
import scraper, config
from multiprocessing.dummy import Pool as ThreadPool
def get_recent_run():
#find the most timestamp of shops added to the archive
scraper.pprint('--get recent run')
files = os.listdir("./data")
dates = []
for f in files:
sub_... | 0.227899 | 0.122366 |
import astropy.units as q
import numpy as np
from hotsoss import utils
from hotsoss import locate_trace as lt
from .utilities import combine_spectra
def extract(data, filt, pixel_masks=None, subarray='SUBSTRIP256', units=q.erg/q.s/q.cm**2/q.AA, **kwargs):
"""
Extract the time-series 1D spectra from a data cu... | specialsoss/binning.py | import astropy.units as q
import numpy as np
from hotsoss import utils
from hotsoss import locate_trace as lt
from .utilities import combine_spectra
def extract(data, filt, pixel_masks=None, subarray='SUBSTRIP256', units=q.erg/q.s/q.cm**2/q.AA, **kwargs):
"""
Extract the time-series 1D spectra from a data cu... | 0.888783 | 0.679607 |
import sys, os
import pandas as pd
from Bio import SeqIO
def filter_corset(transcripts,corset_cluster,DIR):
if DIR == ".": DIR = os.getcwd()
if os.path.isabs(DIR) == False: DIR = os.path.abspath(DIR)
if DIR[-1] != "/": DIR += "/"
path_transcript, files_transcript = os.path.split(transcripts)
transcripts_name =... | src/pdc2/scripts/filter_corset_output.py | import sys, os
import pandas as pd
from Bio import SeqIO
def filter_corset(transcripts,corset_cluster,DIR):
if DIR == ".": DIR = os.getcwd()
if os.path.isabs(DIR) == False: DIR = os.path.abspath(DIR)
if DIR[-1] != "/": DIR += "/"
path_transcript, files_transcript = os.path.split(transcripts)
transcripts_name =... | 0.103431 | 0.233477 |
import pandas as pd
import matplotlib.pyplot as plt
from downloadTabelas import downloadTabela
import os
datasp = pd.DataFrame(columns=['ano', 'sp', 'sbc', 'g', 'c', 'sjc'])
# Downloading files in 'seade.gov.br'
downloadTabela()
# Excel to Pandas
import glob, os
os.chdir("C:/Users/Matheus/Documents/PIBbrasil/SeadeFil... | main.py | import pandas as pd
import matplotlib.pyplot as plt
from downloadTabelas import downloadTabela
import os
datasp = pd.DataFrame(columns=['ano', 'sp', 'sbc', 'g', 'c', 'sjc'])
# Downloading files in 'seade.gov.br'
downloadTabela()
# Excel to Pandas
import glob, os
os.chdir("C:/Users/Matheus/Documents/PIBbrasil/SeadeFil... | 0.320077 | 0.369571 |
import os
import sys
import json
from dotenv import find_dotenv, load_dotenv
from utils import settings
from utils import db_utils as db
from utils import connection_utils as glc
class Build(object):
def __init__(self, static_json_dir = "ref/", build_plan = None, global_populate = True):
load_dotenv(find_dotenv... | setup_dotabase.py |
import os
import sys
import json
from dotenv import find_dotenv, load_dotenv
from utils import settings
from utils import db_utils as db
from utils import connection_utils as glc
class Build(object):
def __init__(self, static_json_dir = "ref/", build_plan = None, global_populate = True):
load_dotenv(find_dotenv... | 0.121934 | 0.065965 |
import argparse
from pathlib import Path
import sys
import pandas as pd
from IM_calculation.Advanced_IM.runlibs_2d import analysis_status
from qcore import simulation_structure
# want to show "finished" first
ALL_STATUS = [analysis_status.finished.name] + [
analysis_status(x).name for x in analysis_status if x ... | IM_calculation/Advanced_IM/scripts/overview_adv_IM_status.py |
import argparse
from pathlib import Path
import sys
import pandas as pd
from IM_calculation.Advanced_IM.runlibs_2d import analysis_status
from qcore import simulation_structure
# want to show "finished" first
ALL_STATUS = [analysis_status.finished.name] + [
analysis_status(x).name for x in analysis_status if x ... | 0.359701 | 0.29931 |
import pandas as pd
import sklearn
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.decomposition import IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
if __na... | pca.py | import pandas as pd
import sklearn
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.decomposition import IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
if __na... | 0.575349 | 0.437763 |
class MinScorePlayer:
def __init__(self, color):
self.color = color
self.opponent_color = None
def getOppositeColor(self, color, board):
if color == board.BLACK:
return board.WHITE
else:
return board.BLACK
def play(self, board):
... | models/players/min_score_player.py | class MinScorePlayer:
def __init__(self, color):
self.color = color
self.opponent_color = None
def getOppositeColor(self, color, board):
if color == board.BLACK:
return board.WHITE
else:
return board.BLACK
def play(self, board):
... | 0.641085 | 0.269805 |
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
import os
ROOT_DIR = os.getenv('PLASTICC_DIR')
WORK_DIR = os.path.join(ROOT_DIR, 'plasticc')
DATA_DIR = os.path.join(ROOT_DIR, 'plasticc_data')
sys.path.append(WORK_DIR)
import numpy as np
import ANTARES_object
import plasticc
imp... | bin/make_cadence_vs_gallat.py | from __future__ import absolute_import
from __future__ import unicode_literals
import sys
import os
ROOT_DIR = os.getenv('PLASTICC_DIR')
WORK_DIR = os.path.join(ROOT_DIR, 'plasticc')
DATA_DIR = os.path.join(ROOT_DIR, 'plasticc_data')
sys.path.append(WORK_DIR)
import numpy as np
import ANTARES_object
import plasticc
imp... | 0.198181 | 0.168207 |
# imports
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def file_adder(file_path, msg):
filename = file_path
attachment = open(filename, 'rb')
p = MIMEBase('application', 'octet-stream')
... | mailing_client.py |
# imports
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def file_adder(file_path, msg):
filename = file_path
attachment = open(filename, 'rb')
p = MIMEBase('application', 'octet-stream')
... | 0.350421 | 0.06724 |
import operator
import webbrowser
import pandas as pd
def sorted_dict_items(d, reverse=False):
"""Sorted (key, value) pairs by value.
"""
result = sorted(d.items(), key=operator.itemgetter(1))
if reverse:
return result[::-1]
else:
return result
def get_beaker_lookup(UserId: str, ... | pathutils/utils.py | import operator
import webbrowser
import pandas as pd
def sorted_dict_items(d, reverse=False):
"""Sorted (key, value) pairs by value.
"""
result = sorted(d.items(), key=operator.itemgetter(1))
if reverse:
return result[::-1]
else:
return result
def get_beaker_lookup(UserId: str, ... | 0.65379 | 0.099645 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from minerva.backend.models.pytorch.callbacks import CallbackList, TrainingMonitor, ValidationMonitor, ModelCheckpoint, \
NeptuneMonitor, NeptuneMonitorLocalizer, Ex... | minerva/whales/models.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from minerva.backend.models.pytorch.callbacks import CallbackList, TrainingMonitor, ValidationMonitor, ModelCheckpoint, \
NeptuneMonitor, NeptuneMonitorLocalizer, Ex... | 0.939623 | 0.440048 |
import datetime
from sawtooth.exceptions import InvalidTransactionError
from journal.transaction import Update
class CreateBondUpdate(Update):
def __init__(self, update_type, issuer, corporate_debt_ratings,
maturity_date, amount_outstanding, coupon_type, coupon_rate,
coupon_fre... | extensions/invoice_finance/updates/invoice_finance.py |
import datetime
from sawtooth.exceptions import InvalidTransactionError
from journal.transaction import Update
class CreateBondUpdate(Update):
def __init__(self, update_type, issuer, corporate_debt_ratings,
maturity_date, amount_outstanding, coupon_type, coupon_rate,
coupon_fre... | 0.420838 | 0.094093 |
import ast
import sys
# needs a special python mysql connector installation
def main():
print("\nStart configureMysql python script")
try:
print("Try to import mysql.connector")
import mysql.connector
except ImportError:
print("Failed to load the Package mysql.connector. Please inst... | server/src/main/resources/cloudFoundry/deployment_scripts/configureMysql.py | import ast
import sys
# needs a special python mysql connector installation
def main():
print("\nStart configureMysql python script")
try:
print("Try to import mysql.connector")
import mysql.connector
except ImportError:
print("Failed to load the Package mysql.connector. Please inst... | 0.096307 | 0.05279 |
from __future__ import annotations
import math
from .hash_table import KT, VT, HashTable, TableEntry
class Cuckoo(HashTable[KT, VT]):
"""
A hash system with worst-case constant-time lookup and deletion, and amortized
expected O(1) insertion.
Cuckoo hashing works by maintaining two arrays and two un... | cs/structures/hash_table/cuckoo.py | from __future__ import annotations
import math
from .hash_table import KT, VT, HashTable, TableEntry
class Cuckoo(HashTable[KT, VT]):
"""
A hash system with worst-case constant-time lookup and deletion, and amortized
expected O(1) insertion.
Cuckoo hashing works by maintaining two arrays and two un... | 0.847163 | 0.566078 |
import copy
def printGrid(array2D):
for row in array2D:
print(row)
def printCube(array3D):
for idx, plane in enumerate(array3D):
print("Z is: " + str(int(idx +0.5 - len(array3D)/2)))
printGrid(plane)
startCube = [[[1 if char == '#' else 0 for char in line.rstrip()] for line in open("d... | day17.py | import copy
def printGrid(array2D):
for row in array2D:
print(row)
def printCube(array3D):
for idx, plane in enumerate(array3D):
print("Z is: " + str(int(idx +0.5 - len(array3D)/2)))
printGrid(plane)
startCube = [[[1 if char == '#' else 0 for char in line.rstrip()] for line in open("d... | 0.083487 | 0.517205 |
import datetime
from random import randint
from discord.ext.commands import Cog, command
from faker import Faker
from utils.apis.Somerandomapi import SRA
class Profile(Cog, description='A cog that generates fake profile info'):
def __init__(self, bot):
self.bot = bot
self.config = self.bot.confi... | cogs/Profile.py | import datetime
from random import randint
from discord.ext.commands import Cog, command
from faker import Faker
from utils.apis.Somerandomapi import SRA
class Profile(Cog, description='A cog that generates fake profile info'):
def __init__(self, bot):
self.bot = bot
self.config = self.bot.confi... | 0.408867 | 0.099252 |
import socket
import pickle
import threading
from utils.inspector import Inspector
class Connector:
def __init__(self, ip, port, conn=None):
ip = Inspector.verify_ip(ip)
if ip is None:
print("Invalid IP.")
raise ValueError
port = Inspector.verify_port(port)
... | communication/connector.py | import socket
import pickle
import threading
from utils.inspector import Inspector
class Connector:
def __init__(self, ip, port, conn=None):
ip = Inspector.verify_ip(ip)
if ip is None:
print("Invalid IP.")
raise ValueError
port = Inspector.verify_port(port)
... | 0.435181 | 0.066751 |
import datetime
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),
('products', '0002_auto_20220215_2350'... | backend/orders/migrations/0001_initial.py |
import datetime
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),
('products', '0002_auto_20220215_2350'... | 0.505371 | 0.152537 |
from __future__ import division
import numpy as np
import mpmath as mp
from .cubic_equation_solver import solve
from .coord_conversion import lla_to_ecef
from .interpolator import Interpolator
from ..tuples import TimeInterval
from ..errors import VisibilityFinderError
class VisibilityFinder(object):
"""An ada... | kaos/algorithm/visibility_finder.py |
from __future__ import division
import numpy as np
import mpmath as mp
from .cubic_equation_solver import solve
from .coord_conversion import lla_to_ecef
from .interpolator import Interpolator
from ..tuples import TimeInterval
from ..errors import VisibilityFinderError
class VisibilityFinder(object):
"""An ada... | 0.887759 | 0.538923 |
__all__ = ('EggObserver',)
class EggObserver(object):
"""
Provides a convenient API for calling an observer of egg operations.
`observer` will be called with:
- ``('analyze', filename, -1, -1)`` during module analysis.
- ``('add', filename, file_fraction, byte_fraction)`` while writing files.
... | openmdao.util/src/openmdao/util/eggobserver.py | __all__ = ('EggObserver',)
class EggObserver(object):
"""
Provides a convenient API for calling an observer of egg operations.
`observer` will be called with:
- ``('analyze', filename, -1, -1)`` during module analysis.
- ``('add', filename, file_fraction, byte_fraction)`` while writing files.
... | 0.846165 | 0.234768 |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 837840602
"""
"""
random actions, total chaos
"""
board = gamma_new(8, 5, 6, 5)
assert board is... | z2/part2/interactive/jm/random_fuzzy_arrows_1/837840602.py | from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 837840602
"""
"""
random actions, total chaos
"""
board = gamma_new(8, 5, 6, 5)
assert board is... | 0.834204 | 0.862699 |