code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import caffe
from .jpeg_pack import JPEGPack
import numpy
import ast
import threading
import random
class JPEGDataLayer(caffe.Layer):
def setup(self, bottom, top):
self.param_ = eval(self.param_str)
print 'JPEGDataLayer initializing with', self.param_
self.batch_size_ = self.param_['batch_s... | python/caffe_util/jpeg_data_layer.py | import caffe
from .jpeg_pack import JPEGPack
import numpy
import ast
import threading
import random
class JPEGDataLayer(caffe.Layer):
def setup(self, bottom, top):
self.param_ = eval(self.param_str)
print 'JPEGDataLayer initializing with', self.param_
self.batch_size_ = self.param_['batch_s... | 0.433022 | 0.340293 |
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
arrays = ['BH', 'BS', 'DR', 'GC', 'PA', 'TB']
type_stack = 'PWS'
cc_stack = 'PWS'
threshold = 0.005
# Read output files
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}... | src/plot_variations.py |
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
arrays = ['BH', 'BS', 'DR', 'GC', 'PA', 'TB']
type_stack = 'PWS'
cc_stack = 'PWS'
threshold = 0.005
# Read output files
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}... | 0.360377 | 0.420421 |
import sys
from datetime import datetime, timezone, timedelta
from oauth2client import client
from googleapiclient import sample_tools
def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'calendar', 'v3', __doc__, __file__,
scope='https://www.googleap... | MoneyPit.py | import sys
from datetime import datetime, timezone, timedelta
from oauth2client import client
from googleapiclient import sample_tools
def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'calendar', 'v3', __doc__, __file__,
scope='https://www.googleap... | 0.267408 | 0.207375 |
import matplotlib.pyplot as plt
from optimism.JaxConfig import *
from optimism.contact.SmoothMinMax import *
from optimism.test.TestFixture import *
class TestSmoothMinMax(TestFixture):
def test_max_x_zero(self):
tol = 0.2
eps = 1e-15
tolm = tol*(1.-eps)
self.assertEqual... | optimism/contact/test/testSmoothMinMax.py | import matplotlib.pyplot as plt
from optimism.JaxConfig import *
from optimism.contact.SmoothMinMax import *
from optimism.test.TestFixture import *
class TestSmoothMinMax(TestFixture):
def test_max_x_zero(self):
tol = 0.2
eps = 1e-15
tolm = tol*(1.-eps)
self.assertEqual... | 0.47244 | 0.7413 |
import sys
from xml.etree.ElementTree import parse
if sys.version_info.major > 2:
from urllib.request import urlopen
else:
from urllib import urlopen
import datetime
class Base:
def __init__(self, url):
self.rss = ''
self.fecha = ''
self.__url = url
self.__fecha_de_actualizacion = ''
self.__localidad =... | src/Aemet.py | import sys
from xml.etree.ElementTree import parse
if sys.version_info.major > 2:
from urllib.request import urlopen
else:
from urllib import urlopen
import datetime
class Base:
def __init__(self, url):
self.rss = ''
self.fecha = ''
self.__url = url
self.__fecha_de_actualizacion = ''
self.__localidad =... | 0.107274 | 0.130313 |
import argparse
import tokenize
import re
import typing
import pkgutil
import io
from . import gatekeepers
from . import providers
class Obfuscator:
def obfuscate(
self, source: typing.IO, output: typing.IO, provider: providers.Provider
):
output_tokens = []
gatekeeper = gatekeepers.Sa... | sutdobfs/__main__.py | import argparse
import tokenize
import re
import typing
import pkgutil
import io
from . import gatekeepers
from . import providers
class Obfuscator:
def obfuscate(
self, source: typing.IO, output: typing.IO, provider: providers.Provider
):
output_tokens = []
gatekeeper = gatekeepers.Sa... | 0.500977 | 0.233379 |
from datetime import datetime, timezone
from unittest.mock import MagicMock
import pytest
from source_dcl_logistics.models.order import Order
from source_dcl_logistics.source import Orders
@pytest.fixture
def patch_base_class(mocker):
# Mock abstract methods to enable instantiating abstract class
mocker.pat... | airbyte-integrations/connectors/source-dcl-logistics/unit_tests/test_orders_stream.py |
from datetime import datetime, timezone
from unittest.mock import MagicMock
import pytest
from source_dcl_logistics.models.order import Order
from source_dcl_logistics.source import Orders
@pytest.fixture
def patch_base_class(mocker):
# Mock abstract methods to enable instantiating abstract class
mocker.pat... | 0.761716 | 0.296973 |
from django.http import HttpResponse
from django.views.generic import View
import feedgen.feed
import html
import json
import re
import requests
import urllib
from .. import services
class PChomeLightNovelView(View):
def get(self, *args, **kwargs):
url = 'https://ecapi.pchome.com.tw/cdn/ecshop/prodapi/v2/... | general/views/pchome.py | from django.http import HttpResponse
from django.views.generic import View
import feedgen.feed
import html
import json
import re
import requests
import urllib
from .. import services
class PChomeLightNovelView(View):
def get(self, *args, **kwargs):
url = 'https://ecapi.pchome.com.tw/cdn/ecshop/prodapi/v2/... | 0.336549 | 0.076961 |
from __future__ import division,with_statement
from nose.tools import assert_almost_equal
def test_gal():
"""Cross-check Gal <-> Supergal <-> FK5 coordinate conversions.
Implicitly also tests networkx conversion routing and matrix composition of
transforms.
Thanks to <NAME> for the data set used for... | tests/test_coords.py | from __future__ import division,with_statement
from nose.tools import assert_almost_equal
def test_gal():
"""Cross-check Gal <-> Supergal <-> FK5 coordinate conversions.
Implicitly also tests networkx conversion routing and matrix composition of
transforms.
Thanks to <NAME> for the data set used for... | 0.372505 | 0.517998 |
import torch
import torch.nn as nn
from neuroir.inputters import BOS, PAD
from neuroir.modules.embeddings import Embeddings
from neuroir.encoders.rnn_encoder import RNNEncoder
from neuroir.decoders.rnn_decoder import RNNDecoder
class Embedder(nn.Module):
def __init__(self,
emsize,
... | neuroir/recommender/layers.py | import torch
import torch.nn as nn
from neuroir.inputters import BOS, PAD
from neuroir.modules.embeddings import Embeddings
from neuroir.encoders.rnn_encoder import RNNEncoder
from neuroir.decoders.rnn_decoder import RNNDecoder
class Embedder(nn.Module):
def __init__(self,
emsize,
... | 0.909717 | 0.169097 |
from pprint import pformat
from six import iteritems
import re
class DeviceEventData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | src/mbed_cloud/_backends/device_directory/models/device_event_data.py | from pprint import pformat
from six import iteritems
import re
class DeviceEventData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.719285 | 0.222468 |
import chemlib
import discord
from discord.ext import commands
from discord import Button, ButtonStyle
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['Element'])
async def element(self, ctx, arg=None):
if arg is None:
... | cogs/chem_info.py | import chemlib
import discord
from discord.ext import commands
from discord import Button, ButtonStyle
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['Element'])
async def element(self, ctx, arg=None):
if arg is None:
... | 0.563018 | 0.397675 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
from typing import Tuple, Union, Callable
class Embedding(nn.Module):
"""Embedding class"""
def __init__(self, num_embeddings: int, embedding_dim: int, p... | Efficient_Character-level_Document_Classification_by_Combining_Convolution_and_Recurrent_Layers/model/ops.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
from typing import Tuple, Union, Callable
class Embedding(nn.Module):
"""Embedding class"""
def __init__(self, num_embeddings: int, embedding_dim: int, p... | 0.975414 | 0.596991 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'ShardingInstanceMongoListArgs',
'ShardingInstanceShardListArgs',
]
@pulumi.input_type
class ShardingInstanceMongoListArgs:
def __init__(__self__,... | sdk/python/pulumi_alicloud/mongodb/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'ShardingInstanceMongoListArgs',
'ShardingInstanceShardListArgs',
]
@pulumi.input_type
class ShardingInstanceMongoListArgs:
def __init__(__self__,... | 0.822153 | 0.116036 |
from tkinter import *
janela = Tk()
janela.title('Calculadora Simples')
e = Entry(janela, width=35, bg='white', borderwidth=5)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# e.insert(0, 'Enter your name: ')
def criar_botao(numero):
atual = e.get()
e.delete(0, END)
e.insert(0, str(atual) + str(... | Calculadora.py | from tkinter import *
janela = Tk()
janela.title('Calculadora Simples')
e = Entry(janela, width=35, bg='white', borderwidth=5)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# e.insert(0, 'Enter your name: ')
def criar_botao(numero):
atual = e.get()
e.delete(0, END)
e.insert(0, str(atual) + str(... | 0.313945 | 0.142799 |
import queue
import threading
from lib.api.api import InternalException
from lib.socket_wrapper import Connect
from owner import Owner
class SubscriptionsWorker(threading.Thread):
def __init__(self, own: Owner, conn: Connect):
super().__init__()
self.own = own
self._conn = conn
se... | src/lib/subscriptions_worker.py | import queue
import threading
from lib.api.api import InternalException
from lib.socket_wrapper import Connect
from owner import Owner
class SubscriptionsWorker(threading.Thread):
def __init__(self, own: Owner, conn: Connect):
super().__init__()
self.own = own
self._conn = conn
se... | 0.379953 | 0.080141 |
from pathlib import Path
import datetime
import pytube
import os
class VideoDownloader:
def __init__(self, request_body=None, video_id=None):
self.__body = request_body
self.__url = f'https://www.youtube.com/watch?v={video_id}'
self.__youtube = pytube.YouTube(self.__url)
self.__fi... | baixatube-service/utils/downloader_utils.py | from pathlib import Path
import datetime
import pytube
import os
class VideoDownloader:
def __init__(self, request_body=None, video_id=None):
self.__body = request_body
self.__url = f'https://www.youtube.com/watch?v={video_id}'
self.__youtube = pytube.YouTube(self.__url)
self.__fi... | 0.611034 | 0.092401 |
import os
import csv
import random
def find_unique(annotations: str) -> dict:
"""
find_unique will loop through the annotations csv, and generate a dictionary which contains
the unique images, and all associated rows. This is neccesary as the csv sometimes contains
multiple entries for an image, specif... | ML/createSplits.py | import os
import csv
import random
def find_unique(annotations: str) -> dict:
"""
find_unique will loop through the annotations csv, and generate a dictionary which contains
the unique images, and all associated rows. This is neccesary as the csv sometimes contains
multiple entries for an image, specif... | 0.718989 | 0.498901 |
from app import app
from flask import Flask, render_template, request, session, flash, redirect, url_for, g
from .forms import LoginForm
import pandas as pd
import numpy as np
import os
import glob
from nltk.corpus import stopwords
from gensim import corpora, models, similarities
import gensim
import sqlite3
dictionar... | apps/app/views.py | from app import app
from flask import Flask, render_template, request, session, flash, redirect, url_for, g
from .forms import LoginForm
import pandas as pd
import numpy as np
import os
import glob
from nltk.corpus import stopwords
from gensim import corpora, models, similarities
import gensim
import sqlite3
dictionar... | 0.29088 | 0.088741 |
from __future__ import absolute_import
from django.conf import settings
from sentry.tasks.base import instrumented_task
from sentry.utils.safe import safe_execute
@instrumented_task(
name='sentry.tasks.store.preprocess_event',
queue='events')
def preprocess_event(cache_key=None, data=None, **kwargs):
fr... | src/sentry/tasks/store.py | from __future__ import absolute_import
from django.conf import settings
from sentry.tasks.base import instrumented_task
from sentry.utils.safe import safe_execute
@instrumented_task(
name='sentry.tasks.store.preprocess_event',
queue='events')
def preprocess_event(cache_key=None, data=None, **kwargs):
fr... | 0.284377 | 0.160858 |
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job
import os
import keys
import random
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def start(bot, update):
update.message.reply_text(
'Hi ... | bot.py | import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job
import os
import keys
import random
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def start(bot, update):
update.message.reply_text(
'Hi ... | 0.208501 | 0.086093 |
import unittest
import servertest
import dxapi
class TestTickDB(servertest.TBServerTest):
streamKeys = [
'bars1min', 'tradeBBO', 'l2'
]
def test_isOpen(self):
self.assertTrue(self.db.isOpen())
def test_isReadOnly(self):
self.assertFalse(self.db.isReadOnly())
def test_cre... | python/test/TestTickDB.py | import unittest
import servertest
import dxapi
class TestTickDB(servertest.TBServerTest):
streamKeys = [
'bars1min', 'tradeBBO', 'l2'
]
def test_isOpen(self):
self.assertTrue(self.db.isOpen())
def test_isReadOnly(self):
self.assertFalse(self.db.isReadOnly())
def test_cre... | 0.436382 | 0.522933 |
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
... | opentimesheet/tasks/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
... | 0.511473 | 0.12424 |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | vega/datasets/pytorch/common/dataset.py |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | 0.900952 | 0.215402 |
from django.test import TestCase
import adapter
class AdapterTest(TestCase):
record = {
u'location': u'5109 W. STILES ST.\r\n5111-13 W. STILES ST.',
u'violation_code': u'CP-802',
u'violation_details_id': 2729519,
u'__metadata': {
u'type': u'PlanPhillyModel.violationde... | phillydata/violations/tests.py | from django.test import TestCase
import adapter
class AdapterTest(TestCase):
record = {
u'location': u'5109 W. STILES ST.\r\n5111-13 W. STILES ST.',
u'violation_code': u'CP-802',
u'violation_details_id': 2729519,
u'__metadata': {
u'type': u'PlanPhillyModel.violationde... | 0.416203 | 0.134009 |
from typing import List, Tuple
__author__ = 'Laptop$'
__date__ = '2017-07-16'
__description__ = " "
__version__ = '1.0'
import datetime
import re
import matplotlib.pyplot as plt
import pandas as pd
from hydsensread.file_reader.abstract_file_reader import TimeSeriesFileReader, date_list, LineDefinition
class XLSHan... | hydsensread/file_reader/compagny_file_reader/hanna_file_reader.py | from typing import List, Tuple
__author__ = 'Laptop$'
__date__ = '2017-07-16'
__description__ = " "
__version__ = '1.0'
import datetime
import re
import matplotlib.pyplot as plt
import pandas as pd
from hydsensread.file_reader.abstract_file_reader import TimeSeriesFileReader, date_list, LineDefinition
class XLSHan... | 0.812198 | 0.225502 |
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import conint
from redis import Redis
from scoretracker import players
from . import schemas
from .deps import get_redis
router = APIRouter(tags=["Games"])
@router.post(
"/games/new",
summary="Record a ne... | scoretracker/games.py | from typing import List
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import conint
from redis import Redis
from scoretracker import players
from . import schemas
from .deps import get_redis
router = APIRouter(tags=["Games"])
@router.post(
"/games/new",
summary="Record a ne... | 0.638723 | 0.165965 |
import os
import subprocess
import traceback
from pkg_resources import resource_filename
from typing import List
import pretty_midi
from sinethesizer.io import (
convert_events_to_timeline,
convert_tsv_to_events,
create_instruments_registry,
write_timeline_to_wav
)
from sinethesizer.utils.music_theory ... | rlmusician/utils/io.py | import os
import subprocess
import traceback
from pkg_resources import resource_filename
from typing import List
import pretty_midi
from sinethesizer.io import (
convert_events_to_timeline,
convert_tsv_to_events,
create_instruments_registry,
write_timeline_to_wav
)
from sinethesizer.utils.music_theory ... | 0.816589 | 0.249859 |
__license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: <EMAIL>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Fou... | Dangerous/Golismero/plugins/testing/recon/theharvester.py | __license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: <EMAIL>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Fou... | 0.376967 | 0.061537 |
from __future__ import print_function
import datetime
import pickle
import os.path
import argparse
import hy
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dateutil.parser import parse as dateparse
# If modifyin... | download.py | from __future__ import print_function
import datetime
import pickle
import os.path
import argparse
import hy
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dateutil.parser import parse as dateparse
# If modifyin... | 0.324449 | 0.107227 |
from migen import *
import math
from third_party import wishbone as wb
class IOControl(Module):
def __init__(self, pins, config, bus=None, debug_bus=None):
if bus is None:
self.bus = wb.Interface(data_width=32, adr_width=32)
else:
self.bus = bus
if debug_bus is None... | soc/rtl/io_control.py | from migen import *
import math
from third_party import wishbone as wb
class IOControl(Module):
def __init__(self, pins, config, bus=None, debug_bus=None):
if bus is None:
self.bus = wb.Interface(data_width=32, adr_width=32)
else:
self.bus = bus
if debug_bus is None... | 0.396535 | 0.347094 |
import rospy
import numpy as np
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import String
import tf_conversions
import tf2_ros
class CommandCenter(object):
def __init__(self):
self.pub_vel = rospy.Publisher("cmd_vel", Twist, queue_size = 10)
self.pub_res... | code used for testing/send_twist_msgs.py | import rospy
import numpy as np
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import String
import tf_conversions
import tf2_ros
class CommandCenter(object):
def __init__(self):
self.pub_vel = rospy.Publisher("cmd_vel", Twist, queue_size = 10)
self.pub_res... | 0.413359 | 0.201794 |
from . import attach_common_event_handlers, chunk, parser_process_chunks
from .context import python_http_parser
def test_req():
"""
Test the stream/event based parser with a HTTP request that conforms to RFC7230
"""
errors = []
results = {
'req_method': None,
'req_uri... | tests/test_stream.py |
from . import attach_common_event_handlers, chunk, parser_process_chunks
from .context import python_http_parser
def test_req():
"""
Test the stream/event based parser with a HTTP request that conforms to RFC7230
"""
errors = []
results = {
'req_method': None,
'req_uri... | 0.646349 | 0.265749 |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import conjuntos
class Janela(Gtk.Window):
def __init__(self):
#Janela Principal
Gtk.Window.__init__(self, title="Álgebra de Conjuntos")
Gtk.Window.set_size_request(self,500,400)
... | gui_conjuntos.py | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import conjuntos
class Janela(Gtk.Window):
def __init__(self):
#Janela Principal
Gtk.Window.__init__(self, title="Álgebra de Conjuntos")
Gtk.Window.set_size_request(self,500,400)
... | 0.29798 | 0.255119 |
import asyncio
from datetime import datetime, timedelta
from typing import Union
from pyrogram import Client
from pyrogram.errors import (ChatAdminRequired,
UserAlreadyParticipant,
UserNotParticipant)
from pyrogram.types import InlineKeyboardMarkup
from pytgca... | YukkiMusic/core/call.py |
import asyncio
from datetime import datetime, timedelta
from typing import Union
from pyrogram import Client
from pyrogram.errors import (ChatAdminRequired,
UserAlreadyParticipant,
UserNotParticipant)
from pyrogram.types import InlineKeyboardMarkup
from pytgca... | 0.44071 | 0.061933 |
import itertools
import gpuscheduler
import argparse
import os
import uuid
import hashlib
import glob
from itertools import product
from torch.optim.lr_scheduler import OneCycleLR
from os.path import join
parser = argparse.ArgumentParser(description='Compute script.')
parser.add_argument('--dry', action='store_true')... | scripts/sde/grid_search.py | import itertools
import gpuscheduler
import argparse
import os
import uuid
import hashlib
import glob
from itertools import product
from torch.optim.lr_scheduler import OneCycleLR
from os.path import join
parser = argparse.ArgumentParser(description='Compute script.')
parser.add_argument('--dry', action='store_true')... | 0.284675 | 0.085404 |
import asyncio
import datetime
import logging
import os
from aiohttp import web
from .constants import *
class EternalServer:
SHUTDOWN_TIMEOUT = 5
def __init__(self, *, address=None, port=8080, ssl_context=None,
mode=OperationMode.clock, buffer_size=128*2**10, loop=None):
self._loop... | http_tarpit/server.py | import asyncio
import datetime
import logging
import os
from aiohttp import web
from .constants import *
class EternalServer:
SHUTDOWN_TIMEOUT = 5
def __init__(self, *, address=None, port=8080, ssl_context=None,
mode=OperationMode.clock, buffer_size=128*2**10, loop=None):
self._loop... | 0.362518 | 0.051012 |
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from lightly.api.utils import getenv, get_request, post_request
from typing import Union
def _prefix(dataset_id: Union[str, None] = None,
sample_id: Union[str, None] = None,
*args, **kwargs):
"""Returns the prefix... | lightly/api/routes/users/datasets/samples/service.py |
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from lightly.api.utils import getenv, get_request, post_request
from typing import Union
def _prefix(dataset_id: Union[str, None] = None,
sample_id: Union[str, None] = None,
*args, **kwargs):
"""Returns the prefix... | 0.835484 | 0.238445 |
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.optim import Adam
from sklearn.preprocessing import MinMaxScaler
# Source: https://github.com/techshot25/Autoencoders
class Autoencoder(nn.Module):
"""Makes the main denoising autoencoder
Parameters
----------
in_shape [int]... | autoencoder.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.optim import Adam
from sklearn.preprocessing import MinMaxScaler
# Source: https://github.com/techshot25/Autoencoders
class Autoencoder(nn.Module):
"""Makes the main denoising autoencoder
Parameters
----------
in_shape [int]... | 0.956654 | 0.437703 |
import pandas as pd
class Emissions:
def __init__(self):
ds = pd.read_csv('tri.csv')
df = pd.DataFrame(ds)
self.data = pd.DataFrame(columns=['Facility','Sector','FRS-ID','Latitude','Longitude','Chemical','Emissions','Off-Site','Production-Waste'])
lf = []
ls = []
lfi = []
lla = []
ll... | src/pp.py | import pandas as pd
class Emissions:
def __init__(self):
ds = pd.read_csv('tri.csv')
df = pd.DataFrame(ds)
self.data = pd.DataFrame(columns=['Facility','Sector','FRS-ID','Latitude','Longitude','Chemical','Emissions','Off-Site','Production-Waste'])
lf = []
ls = []
lfi = []
lla = []
ll... | 0.12873 | 0.257876 |
from __future__ import print_function
import os
import getpass
from cStringIO import StringIO
try:
import paramiko
except ImportError:
print("Please install paramiko to use SSH connection")
raise
# make these optional so not everyone has to build C binaries
try:
import pandas as pd
if pd.__version... | poseidon/ssh.py | from __future__ import print_function
import os
import getpass
from cStringIO import StringIO
try:
import paramiko
except ImportError:
print("Please install paramiko to use SSH connection")
raise
# make these optional so not everyone has to build C binaries
try:
import pandas as pd
if pd.__version... | 0.593963 | 0.079961 |
import argparse
import pandas as pd
from password_analyse import PasswordAnalyse
from generate_password import GeneratePassword
DATA_PATH = 'data/'
WORD_LIST_PATH = 'data/wordlist.txt'
KEY_LIST_PATH = 'data/keylist.txt'
TRAIN_DATA_PATH = 'data/12306.csv'
PATTERN_FILE = 'result/pattern.txt'
PATTERN_PATH = 're... | main.py | import argparse
import pandas as pd
from password_analyse import PasswordAnalyse
from generate_password import GeneratePassword
DATA_PATH = 'data/'
WORD_LIST_PATH = 'data/wordlist.txt'
KEY_LIST_PATH = 'data/keylist.txt'
TRAIN_DATA_PATH = 'data/12306.csv'
PATTERN_FILE = 'result/pattern.txt'
PATTERN_PATH = 're... | 0.111241 | 0.06236 |
from app import socketio
from config import *
from .spi import *
from ..socketio_queue import EmitQueue
from flask_socketio import Namespace
import logging
logger = logging.getLogger("SIO_Server")
class XApiNamespace(Namespace):
md = None
td = None
mq = None
spi = None
orders_map = {}
def ... | languages/Server/app/api/events.py | from app import socketio
from config import *
from .spi import *
from ..socketio_queue import EmitQueue
from flask_socketio import Namespace
import logging
logger = logging.getLogger("SIO_Server")
class XApiNamespace(Namespace):
md = None
td = None
mq = None
spi = None
orders_map = {}
def ... | 0.270769 | 0.167151 |
import spotipy.util as util
from progress.bar import Bar
import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
import json, requests, urllib.parse, re, time, sys, click, spotipy, os
def auth():
username = 'default'
scope = 'user-read-private user-read-p... | generate_freq.py | import spotipy.util as util
from progress.bar import Bar
import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
import json, requests, urllib.parse, re, time, sys, click, spotipy, os
def auth():
username = 'default'
scope = 'user-read-private user-read-p... | 0.12692 | 0.080719 |
import os
import h5py, torch
import numpy as np
import keras
from numpy.random import seed as numpy_seed
from tensorflow import set_random_seed
from keras.engine.saving import load_attributes_from_hdf5_group
def initialize_with_keras_hdf5(keras_model, dict_map, torch_model,
model_path=N... | utils/weight_transfer.py | import os
import h5py, torch
import numpy as np
import keras
from numpy.random import seed as numpy_seed
from tensorflow import set_random_seed
from keras.engine.saving import load_attributes_from_hdf5_group
def initialize_with_keras_hdf5(keras_model, dict_map, torch_model,
model_path=N... | 0.7917 | 0.366873 |
from typing import Iterable, Mapping, Union, Optional, Tuple
import pathlib
import json
from abc import abstractmethod
from enum import Enum, auto
import torch
from torch import nn
from .codemaps_helpers import (CodemapsHelper,
SimpleCodemapsHelper, ZigZagCodemapsHelper)
from VQCPCB.tra... | interactive_spectrogram_inpainting/priors/transformer.py | from typing import Iterable, Mapping, Union, Optional, Tuple
import pathlib
import json
from abc import abstractmethod
from enum import Enum, auto
import torch
from torch import nn
from .codemaps_helpers import (CodemapsHelper,
SimpleCodemapsHelper, ZigZagCodemapsHelper)
from VQCPCB.tra... | 0.853027 | 0.38856 |
!pip install wandb -qqq
import wandb
wandb.init(project="Back_Propagation", entity="cs20m040")
!wandb login fb3bb8a505ba908b667b747ed68e4b154b2f6fc5
from tqdm.notebook import tqdm
from sklearn.preprocessing import OneHotEncoder
from keras.datasets import fashion_mnist
import numpy as np
import matplotlib.pypl... | FeedForwardNetwork.py | !pip install wandb -qqq
import wandb
wandb.init(project="Back_Propagation", entity="cs20m040")
!wandb login fb3bb8a505ba908b667b747ed68e4b154b2f6fc5
from tqdm.notebook import tqdm
from sklearn.preprocessing import OneHotEncoder
from keras.datasets import fashion_mnist
import numpy as np
import matplotlib.pypl... | 0.597373 | 0.37777 |
# Copyright (C) 2016 ETH Zurich, Institute for Astronomy
# System imports
from __future__ import print_function, division, absolute_import, unicode_literals
__author__ = 'sibirrer'
from MultiLens.Cosmo.cosmo import CosmoProp
import MultiLens.Utils.constants as const
class LensObject(object):
"""
class to... | MultiLens/lens_object.py |
# Copyright (C) 2016 ETH Zurich, Institute for Astronomy
# System imports
from __future__ import print_function, division, absolute_import, unicode_literals
__author__ = 'sibirrer'
from MultiLens.Cosmo.cosmo import CosmoProp
import MultiLens.Utils.constants as const
class LensObject(object):
"""
class to... | 0.874721 | 0.337285 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | dfparser/rsb_event_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | 0.261048 | 0.15444 |
from os import path
import json
import datetime
from coinoxr.response import Response
from coinoxr.client import HttpClient
from urllib.parse import urlparse
class StubHttpClient(HttpClient):
def __init__(self):
self._app_ids = []
self._dates = []
def get(self, url, params):
route = ... | tests/stub_client.py | from os import path
import json
import datetime
from coinoxr.response import Response
from coinoxr.client import HttpClient
from urllib.parse import urlparse
class StubHttpClient(HttpClient):
def __init__(self):
self._app_ids = []
self._dates = []
def get(self, url, params):
route = ... | 0.473414 | 0.075892 |
""" utils/test/test_utils """
import unittest
import numpy as np
from sklearn.preprocessing import normalize, StandardScaler, MinMaxScaler
from ilcksvd.utils.utils import Normalizer
class Test_Normalizer(unittest.TestCase):
def setUp(self):
samples = 3
features = 5
self.data = np.rando... | ilcksvd/utils/test/test_utils.py | """ utils/test/test_utils """
import unittest
import numpy as np
from sklearn.preprocessing import normalize, StandardScaler, MinMaxScaler
from ilcksvd.utils.utils import Normalizer
class Test_Normalizer(unittest.TestCase):
def setUp(self):
samples = 3
features = 5
self.data = np.rando... | 0.802981 | 0.721541 |
def PCG_128BIT_CONSTANT(high, low):
''' Some members of the PCG library use 128-bit math.
This is not a problem for Python at all. But still provide this
method of constructing literals, for compatibility.
'''
return high << 64 | low
# C++ iostreams don't exist. Instead, the Engine class s... | pcg_random/pcg_extras.py | def PCG_128BIT_CONSTANT(high, low):
''' Some members of the PCG library use 128-bit math.
This is not a problem for Python at all. But still provide this
method of constructing literals, for compatibility.
'''
return high << 64 | low
# C++ iostreams don't exist. Instead, the Engine class s... | 0.523177 | 0.502747 |
import enum
import math
from multimethod import multimethod
def parse_unit(str_unit: str):
for u in Unit:
if str_unit == u.name:
return u
if str_unit == "KiB":
return Unit.KibiByte
elif str_unit in ["4KiB blocks", "4KiB Blocks"]:
return Unit.Blocks4096
elif str_u... | test/functional/test-framework/test_utils/size.py |
import enum
import math
from multimethod import multimethod
def parse_unit(str_unit: str):
for u in Unit:
if str_unit == u.name:
return u
if str_unit == "KiB":
return Unit.KibiByte
elif str_unit in ["4KiB blocks", "4KiB Blocks"]:
return Unit.Blocks4096
elif str_u... | 0.656768 | 0.403273 |
xs_gen = """\
set title "[CHAR] {reactor} Cross Section Generator"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{coolant}
therm lwt... | bright/xsgen/templates/lwr/serpent.py | xs_gen = """\
set title "[CHAR] {reactor} Cross Section Generator"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{coolant}
therm lwt... | 0.54359 | 0.343438 |
import valideer
from tornado.web import Application
from tornado.web import RequestHandler
from tornado.testing import AsyncHTTPTestCase
from tornwrap import validated
class Handler(RequestHandler):
@validated({"+name": valideer.Enum(("steve", "joe"))})
def get(self, arguments):
self.finish("Hello, %... | tornwrap/tests/test_validated.py | import valideer
from tornado.web import Application
from tornado.web import RequestHandler
from tornado.testing import AsyncHTTPTestCase
from tornwrap import validated
class Handler(RequestHandler):
@validated({"+name": valideer.Enum(("steve", "joe"))})
def get(self, arguments):
self.finish("Hello, %... | 0.581541 | 0.165054 |
import unittest
from modules.inventory.items.baseitems import StackableItem, NonStackableItem
characteristic = "An Example of a stackable item!"
asset = "path/to/asset"
class ExampleStackable(StackableItem):
@property
def characteristic(self):
return characteristic
@property
def asset(self)... | romantic-revolutionaries/test/test_items.py | import unittest
from modules.inventory.items.baseitems import StackableItem, NonStackableItem
characteristic = "An Example of a stackable item!"
asset = "path/to/asset"
class ExampleStackable(StackableItem):
@property
def characteristic(self):
return characteristic
@property
def asset(self)... | 0.807992 | 0.496948 |
import numpy as np
class Player:
"""docstring for Player"""
def __init__(self, symbol):
self.symbol = symbol
class Board:
"""docstring for Board"""
def __init__(self,size):
self.num_rows = size
self.num_cols = size
self.board = [ [' ' for _ in range(self.num_rows)] for _ in range(self.num_cols)]
def d... | tictactoe.py | import numpy as np
class Player:
"""docstring for Player"""
def __init__(self, symbol):
self.symbol = symbol
class Board:
"""docstring for Board"""
def __init__(self,size):
self.num_rows = size
self.num_cols = size
self.board = [ [' ' for _ in range(self.num_rows)] for _ in range(self.num_cols)]
def d... | 0.204978 | 0.324824 |
import os
CI_MODE = bool(os.environ.get('TRAVIS', False))
if not CI_MODE:
import matplotlib
from matplotlib import patches
import matplotlib.pyplot as plt
import random
from typing import List
import networkx as nx
from airflow import DAG
from networkx.drawing.nx_agraph import graphviz_layout
from ditto.... | ditto/rendering.py | import os
CI_MODE = bool(os.environ.get('TRAVIS', False))
if not CI_MODE:
import matplotlib
from matplotlib import patches
import matplotlib.pyplot as plt
import random
from typing import List
import networkx as nx
from airflow import DAG
from networkx.drawing.nx_agraph import graphviz_layout
from ditto.... | 0.377082 | 0.321487 |
import csv
import os
import xmltodict
fileList = os.listdir("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\")
fileList.sort()
with open("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\2000.csv", "w", newline="") as csvfile:
fieldnames = ["year","experiment_id","title","objective","sponsors","year","plot dime... | processYieldbook.py | import csv
import os
import xmltodict
fileList = os.listdir("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\")
fileList.sort()
with open("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\2000.csv", "w", newline="") as csvfile:
fieldnames = ["year","experiment_id","title","objective","sponsors","year","plot dime... | 0.150934 | 0.056236 |
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
class AccountsTests(TestCase):
"""Tests for the accounts app"""
def setUp(self):
"""Creates a User for testing"""
self.test_user = User.objects.create_user(
email='<EMAIL>... | pizzeria/accounts/tests.py | from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
class AccountsTests(TestCase):
"""Tests for the accounts app"""
def setUp(self):
"""Creates a User for testing"""
self.test_user = User.objects.create_user(
email='<EMAIL>... | 0.639173 | 0.573081 |
from scipy.stats import normaltest, ttest_ind, ks_2samp
import numpy as np
import matplotlib.pyplot as plt
class comparator():
def __init__(self,A,B,confidence=0.05,normaltest=True):
self.A = A
self.B = B
self.confidence = confidence
self.normaltest = normaltest
self.get_stat()
self.log()
... | stat_analysis/comparator.py | from scipy.stats import normaltest, ttest_ind, ks_2samp
import numpy as np
import matplotlib.pyplot as plt
class comparator():
def __init__(self,A,B,confidence=0.05,normaltest=True):
self.A = A
self.B = B
self.confidence = confidence
self.normaltest = normaltest
self.get_stat()
self.log()
... | 0.399929 | 0.475971 |
import json
import click
import networkx as nx
from networkx.readwrite import json_graph
N = 60
SPLIT = 4
@click.command()
@click.option('--horizontal_file', required=True, default='horizontal.json')
@click.option('--vertical_file', required=True, default='vertical.json')
def grids(horizontal_file, vertical_file):
... | tests/fixtures/grids.py | import json
import click
import networkx as nx
from networkx.readwrite import json_graph
N = 60
SPLIT = 4
@click.command()
@click.option('--horizontal_file', required=True, default='horizontal.json')
@click.option('--vertical_file', required=True, default='vertical.json')
def grids(horizontal_file, vertical_file):
... | 0.572364 | 0.347343 |
import numpy as np
class Board:
def __init__(self, n=3):
self.n = n
self.N = n ** 2
self.last_move = None
self.pieces = np.zeros((self.N, self.N)).astype(int)
self.win_status = np.zeros((n, n)).astype(int)
def copy(self, other):
self.n = other.n
self.N... | ultimate_tictactoe/UltimateTicTacToeLogic.py | import numpy as np
class Board:
def __init__(self, n=3):
self.n = n
self.N = n ** 2
self.last_move = None
self.pieces = np.zeros((self.N, self.N)).astype(int)
self.win_status = np.zeros((n, n)).astype(int)
def copy(self, other):
self.n = other.n
self.N... | 0.484624 | 0.375191 |
from mlutils.simpleknn.template_selector import TemplateSelector
from mlutils.simpleknn.templates import Develop
from mlutils.version import __email__, __author__, __version__ # noqa
class SimpleKNN(object):
"""
A simplistic KNN (K Nearest Neighbors) indexing with names as keys
"""
def __new__(cls,... | mlutils/simpleknn/__init__.py | from mlutils.simpleknn.template_selector import TemplateSelector
from mlutils.simpleknn.templates import Develop
from mlutils.version import __email__, __author__, __version__ # noqa
class SimpleKNN(object):
"""
A simplistic KNN (K Nearest Neighbors) indexing with names as keys
"""
def __new__(cls,... | 0.67854 | 0.148047 |
# LIBRERÍAS
from imutils.video import FileVideoStream # Gestión de video
import numpy as np # Soporte vectores y matrices
import imutils
import cv2
import time
import os, random
from cvlib.object_detection import draw_bbox # Detección de objetos
import cvlib as cv # Detección de objetos
from inputimeout ... | CVAPP-Computer-Vision Desktop/CVAPP.py |
# LIBRERÍAS
from imutils.video import FileVideoStream # Gestión de video
import numpy as np # Soporte vectores y matrices
import imutils
import cv2
import time
import os, random
from cvlib.object_detection import draw_bbox # Detección de objetos
import cvlib as cv # Detección de objetos
from inputimeout ... | 0.155976 | 0.188997 |
import sqlite3
conn = sqlite3.connect('northwind_small.sqlite3')
cursor = conn.cursor()
#What are the most expensive items in the database
query1 = '''
SELECT
ProductName,
UnitPrice
FROM Product
ORDER BY
UnitPrice DESC
LIMIT 10;
'''
result = cursor.execute(query1).fetchall()
print(f'Ten Most Expensive Items {res... | Answers/northwind.py | import sqlite3
conn = sqlite3.connect('northwind_small.sqlite3')
cursor = conn.cursor()
#What are the most expensive items in the database
query1 = '''
SELECT
ProductName,
UnitPrice
FROM Product
ORDER BY
UnitPrice DESC
LIMIT 10;
'''
result = cursor.execute(query1).fetchall()
print(f'Ten Most Expensive Items {res... | 0.199347 | 0.312895 |
import click
from cg_manage_rds.cmds.utils import run_sync
from cg_manage_rds.cmds.engine import Engine
from cg_manage_rds.cmds import cf_cmds as cf
class MySql(Engine):
def prerequisites(self) -> None:
click.echo("Checking for locally installed mysql utilities")
cmd = ["which", "mysql"]
c... | cg_manage_rds/cmds/mysql.py | import click
from cg_manage_rds.cmds.utils import run_sync
from cg_manage_rds.cmds.engine import Engine
from cg_manage_rds.cmds import cf_cmds as cf
class MySql(Engine):
def prerequisites(self) -> None:
click.echo("Checking for locally installed mysql utilities")
cmd = ["which", "mysql"]
c... | 0.094866 | 0.064153 |
import os
import argparse
import json
import torch
from torch import nn, autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils import clip_grad_value_
from dataset import KaldiFeatureLabelReader
from model import Net
# [TODO] use toke accuracy as cv metric
d... | pytorch/train.py | import os
import argparse
import json
import torch
from torch import nn, autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils import clip_grad_value_
from dataset import KaldiFeatureLabelReader
from model import Net
# [TODO] use toke accuracy as cv metric
d... | 0.556159 | 0.312265 |
from datetime import datetime
from flask_bcrypt import generate_password_hash, check_password_hash
from database import db
class Comment(db.EmbeddedDocument):
content = db.StringField(required=True)
sender = db.ReferenceField('User')
created_date = db.DateTimeField(required=True, default=datetime.now)
... | database/models.py |
from datetime import datetime
from flask_bcrypt import generate_password_hash, check_password_hash
from database import db
class Comment(db.EmbeddedDocument):
content = db.StringField(required=True)
sender = db.ReferenceField('User')
created_date = db.DateTimeField(required=True, default=datetime.now)
... | 0.569613 | 0.044995 |
import sys
from heapq import heappush, heappop, heapify
BEFORE = True
AFTER = False
def load_num():
line = sys.stdin.readline()
if line == ' ' or line == '\n':
return None
return int(line)
def load_case():
npeople = load_num()
people = []
for p in range(npeople):
people.app... | 10037 - Bridge/main.py | import sys
from heapq import heappush, heappop, heapify
BEFORE = True
AFTER = False
def load_num():
line = sys.stdin.readline()
if line == ' ' or line == '\n':
return None
return int(line)
def load_case():
npeople = load_num()
people = []
for p in range(npeople):
people.app... | 0.219505 | 0.243465 |
import os
import argparse
import pickle
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential, load_model
from keras.layers import Embedding, LSTM, Dense, Activation, Dropout
from keras.callbacks import EarlyStopping
from keras import backend as k
import numpy as np
from numpy.ran... | train_lm.py | import os
import argparse
import pickle
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential, load_model
from keras.layers import Embedding, LSTM, Dense, Activation, Dropout
from keras.callbacks import EarlyStopping
from keras import backend as k
import numpy as np
from numpy.ran... | 0.777596 | 0.343067 |
from datetime import datetime
from django.core.validators import MaxValueValidator
from django.db import models
from django.test import TestCase
from freezegun import freeze_time
from conditioner.conditions.dates import DayOfMonthCondition, DayOfWeekCondition
from conditioner.base import BaseCronCondition
from condi... | conditioner/tests/conditions/test_dates.py | from datetime import datetime
from django.core.validators import MaxValueValidator
from django.db import models
from django.test import TestCase
from freezegun import freeze_time
from conditioner.conditions.dates import DayOfMonthCondition, DayOfWeekCondition
from conditioner.base import BaseCronCondition
from condi... | 0.857664 | 0.507385 |
import numpy as np
def calculate_factorial(x: int) -> int:
if x == 1:
return 1
else:
return x * calculate_factorial(x - 1)
def p1(k: int) -> str:
answer_string = ""
for x in range(k, 0, -1):
factorial = calculate_factorial(x)
if x == k:
answer_string = str... | Homework1/homework1.py | import numpy as np
def calculate_factorial(x: int) -> int:
if x == 1:
return 1
else:
return x * calculate_factorial(x - 1)
def p1(k: int) -> str:
answer_string = ""
for x in range(k, 0, -1):
factorial = calculate_factorial(x)
if x == k:
answer_string = str... | 0.347537 | 0.639441 |
import unittest
from pymath.expression import Expression
from pymath.fraction import Fraction
from pymath.generic import first_elem
from pymath.renders import txt_render
class TestExpression(unittest.TestCase):
"""Testing functions from pymath.expression"""
def test_init_from_str(self):
exp = Exp... | test/test_expression.py |
import unittest
from pymath.expression import Expression
from pymath.fraction import Fraction
from pymath.generic import first_elem
from pymath.renders import txt_render
class TestExpression(unittest.TestCase):
"""Testing functions from pymath.expression"""
def test_init_from_str(self):
exp = Exp... | 0.53048 | 0.701575 |
def extractWuxiaNation(item):
"""
'WuxiaNation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Announcements' in item['tags']:
return None
tagmap = [
('Mysterious Job Called Oda Nobunaga', ... | WebMirror/management/rss_parser_funcs/feed_parse_extractWuxiaNation.py | def extractWuxiaNation(item):
"""
'WuxiaNation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Announcements' in item['tags']:
return None
tagmap = [
('Mysterious Job Called Oda Nobunaga', ... | 0.309858 | 0.237963 |
import torch
import torch.nn as nn
# built-in
from math import sqrt
import functools
# Based on implementation from <NAME> (2016)
class ResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=32, nc16=64, nc8=128):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, ... | experiments/cifar10/models/resnet.py | import torch
import torch.nn as nn
# built-in
from math import sqrt
import functools
# Based on implementation from <NAME> (2016)
class ResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=32, nc16=64, nc8=128):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, ... | 0.955142 | 0.494385 |
import re
from typing import List, Optional
from parso.python.tree import Module
from globality_black.constants import (
MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT,
TYPES_TO_CHECK_FMT_ON_OFF,
)
class SyntaxTreeVisitor:
def __init__(
self,
module: Module,
types_to_find: Optional[Li... | globality_black/common.py | import re
from typing import List, Optional
from parso.python.tree import Module
from globality_black.constants import (
MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT,
TYPES_TO_CHECK_FMT_ON_OFF,
)
class SyntaxTreeVisitor:
def __init__(
self,
module: Module,
types_to_find: Optional[Li... | 0.783077 | 0.323754 |
import httplib
import json
import logging
from conpaas.core import https
class AgentException(Exception):
pass
def _check(response):
code, body = response
if code != httplib.OK:
raise AgentException('Received HTTP response code %d' % (code))
try:
data = json.loads(body)
except E... | conpaas-services/src/conpaas/services/mysql/agent/client.py | import httplib
import json
import logging
from conpaas.core import https
class AgentException(Exception):
pass
def _check(response):
code, body = response
if code != httplib.OK:
raise AgentException('Received HTTP response code %d' % (code))
try:
data = json.loads(body)
except E... | 0.202286 | 0.095898 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
class SearchableKernelMaker:
def make_searchable_kernel_w_and_conds(self, kernel_w, tf_masks, thresholds, is_supergraph_training_tensor,
... | graph/searchable_utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
class SearchableKernelMaker:
def make_searchable_kernel_w_and_conds(self, kernel_w, tf_masks, thresholds, is_supergraph_training_tensor,
... | 0.701917 | 0.525004 |
import os
import logging
import uuid
import threading
import webbrowser
import datetime
from typing import Any
from typing import List
from typing import Optional
from typing import Dict
import msal
import flask
import requests
from flask import request
from werkzeug.serving import make_server
app = flask.Flask(__nam... | flowd/integrations.py | import os
import logging
import uuid
import threading
import webbrowser
import datetime
from typing import Any
from typing import List
from typing import Optional
from typing import Dict
import msal
import flask
import requests
from flask import request
from werkzeug.serving import make_server
app = flask.Flask(__nam... | 0.756627 | 0.101145 |
import pandas as pd
import six
class InstrumentMixin(object):
def __init__(self, instruments):
self._instruments = {i.order_book_id: i for i in instruments}
self._sym_id_map = {i.symbol: k for k, i in six.iteritems(self._instruments)
# 过滤掉 CSI300, SSE50, CSI500, SSE180... | rqalpha/data/instrument_mixin.py |
import pandas as pd
import six
class InstrumentMixin(object):
def __init__(self, instruments):
self._instruments = {i.order_book_id: i for i in instruments}
self._sym_id_map = {i.symbol: k for k, i in six.iteritems(self._instruments)
# 过滤掉 CSI300, SSE50, CSI500, SSE180... | 0.36139 | 0.233717 |
from paida.paida_core.PAbsorber import *
from paida.paida_core.IBaseHistogram import *
from paida.paida_core.PExceptions import *
from paida.math.array.binArray import binArray3
class IHistogram(IBaseHistogram):
def __init__(self, title, binEdges):
IBaseHistogram.__init__(self, title)
self._sizeX = len(binEdges[0... | paida-3.2.1_2.10.1/paida/paida_core/IHistogram.py | from paida.paida_core.PAbsorber import *
from paida.paida_core.IBaseHistogram import *
from paida.paida_core.PExceptions import *
from paida.math.array.binArray import binArray3
class IHistogram(IBaseHistogram):
def __init__(self, title, binEdges):
IBaseHistogram.__init__(self, title)
self._sizeX = len(binEdges[0... | 0.490968 | 0.489015 |
import dash_html_components as html
import dash_bootstrap_components as dbc
import yaml
from navbar import Navbar
from footer import Footer
def Users():
"""Builds the AboutUs->Model Users using assets/users/organizations.yml"""
with open("assets/users/organizations.yml") as f:
collaborators = yaml.l... | about_us/users.py | import dash_html_components as html
import dash_bootstrap_components as dbc
import yaml
from navbar import Navbar
from footer import Footer
def Users():
"""Builds the AboutUs->Model Users using assets/users/organizations.yml"""
with open("assets/users/organizations.yml") as f:
collaborators = yaml.l... | 0.409929 | 0.105073 |
import numpy as np
import plot_schema
import matplotlib.pyplot as plt
class PlotsNine():
'''
classdocs
'''
def __init__(self, directory, full=True):
'''
Constructor
'''
self.t_gap_ms = 5.0
self.directory = directory
self.full = full
if self.full:... | tools/cardiac_py/experiments/nine.py | import numpy as np
import plot_schema
import matplotlib.pyplot as plt
class PlotsNine():
'''
classdocs
'''
def __init__(self, directory, full=True):
'''
Constructor
'''
self.t_gap_ms = 5.0
self.directory = directory
self.full = full
if self.full:... | 0.437824 | 0.36869 |
from pathlib import Path
import datetime
from dataclasses import dataclass
IVMS_FOLDER = Path(r'.\\data_files\\IVMS')
DRIVER_TRAINING = Path(r'.\\data_files\\IVMS\\driver_training_db.xlsx')
DATABASE = r'ivms_db.sqlite3'
@dataclass
class IvmsVehicle:
asset_descr: str
registration: str
make: str
model:... | ivms_settings.py | from pathlib import Path
import datetime
from dataclasses import dataclass
IVMS_FOLDER = Path(r'.\\data_files\\IVMS')
DRIVER_TRAINING = Path(r'.\\data_files\\IVMS\\driver_training_db.xlsx')
DATABASE = r'ivms_db.sqlite3'
@dataclass
class IvmsVehicle:
asset_descr: str
registration: str
make: str
model:... | 0.670608 | 0.165458 |
import logging
import requests
from lxml import html
from collections import namedtuple
from datetime import datetime
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
XP_USAGE_SINCE = '//*[@id="main"]/div/section/' \
'div[2]/section[1]/div/h2/text()'
XP_USAGE_TOTAL = '//*[... | vodafone_ie_account_checker/api.py |
import logging
import requests
from lxml import html
from collections import namedtuple
from datetime import datetime
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
XP_USAGE_SINCE = '//*[@id="main"]/div/section/' \
'div[2]/section[1]/div/h2/text()'
XP_USAGE_TOTAL = '//*[... | 0.323594 | 0.049017 |
import argparse
import os
import random
import pandas as pd
import numpy as np
lang_families = {'arz': 'Afro-Asiatic', 'afb': 'Afro-Asiatic', 'ara': 'Afro-Asiatic', 'syc': 'Afro-Asiatic',
'heb': 'Afro-Asiatic', 'amh': 'Afro-Asiatic',
'gup': 'Arnhem',
'aym... | sigmorphon-2021/all_data/generate_data.py | import argparse
import os
import random
import pandas as pd
import numpy as np
lang_families = {'arz': 'Afro-Asiatic', 'afb': 'Afro-Asiatic', 'ara': 'Afro-Asiatic', 'syc': 'Afro-Asiatic',
'heb': 'Afro-Asiatic', 'amh': 'Afro-Asiatic',
'gup': 'Arnhem',
'aym... | 0.35354 | 0.172538 |
__author__ = 'laifuyu'
import configparser
import sys
import mysql.connector
from globalpkg.global_var import logger
class MyDB:
"""动作类,获取数据库连接,配置数据库IP,端口等信息,获取数据库连接"""
def __init__(self, config_file, db):
config = configparser.ConfigParser()
# 从配置文件中读取数据库服务器IP、域名,端口
config.read(co... | globalpkg/mydb.py |
__author__ = 'laifuyu'
import configparser
import sys
import mysql.connector
from globalpkg.global_var import logger
class MyDB:
"""动作类,获取数据库连接,配置数据库IP,端口等信息,获取数据库连接"""
def __init__(self, config_file, db):
config = configparser.ConfigParser()
# 从配置文件中读取数据库服务器IP、域名,端口
config.read(co... | 0.206414 | 0.058185 |
"""CLI - Utilities."""
from __future__ import absolute_import, print_function, unicode_literals
import json
import platform
from contextlib import contextmanager
import click
import six
from click_spinner import spinner
from ..core.api.version import get_version as get_api_version
from ..core.version import get_vers... | cloudsmith_cli/cli/utils.py | """CLI - Utilities."""
from __future__ import absolute_import, print_function, unicode_literals
import json
import platform
from contextlib import contextmanager
import click
import six
from click_spinner import spinner
from ..core.api.version import get_version as get_api_version
from ..core.version import get_vers... | 0.696062 | 0.167797 |
import os
import datetime
import traceback
import asyncio
import asyncpg
import sys
try:
import uvloop
except ImportError:
if sys.platform == "win32":
pass
elif sys.platform == "linux":
print(
"""UvLoop is not installed. Please install it with "pip install uvloop".
"... | Zane/main.py | import os
import datetime
import traceback
import asyncio
import asyncpg
import sys
try:
import uvloop
except ImportError:
if sys.platform == "win32":
pass
elif sys.platform == "linux":
print(
"""UvLoop is not installed. Please install it with "pip install uvloop".
"... | 0.280025 | 0.078784 |
from users_model import User, Init
from . import api
from flask import request, jsonify
import ConfigParser
from botasky.utils.MyCONN import MySQL
from botasky.utils.MyFILE import project_abdir, recursiveSearchFile
from botasky.utils.MyLOG import MyLog
logConfig = recursiveSearchFile(project_abdir, '*l... | botasky/api_0_1/register_verify_user.py | from users_model import User, Init
from . import api
from flask import request, jsonify
import ConfigParser
from botasky.utils.MyCONN import MySQL
from botasky.utils.MyFILE import project_abdir, recursiveSearchFile
from botasky.utils.MyLOG import MyLog
logConfig = recursiveSearchFile(project_abdir, '*l... | 0.287268 | 0.046184 |
import GeodisTK
import numpy as np
import time
from PIL import Image
import matplotlib.pyplot as plt
def geodesic_distance_2d(I, S, lamb, iter):
'''
get 2d geodesic disntance by raser scanning.
I: input image, can have multiple channels. Type should be np.float32.
S: binary image where non-zero pixels... | demo2d.py | import GeodisTK
import numpy as np
import time
from PIL import Image
import matplotlib.pyplot as plt
def geodesic_distance_2d(I, S, lamb, iter):
'''
get 2d geodesic disntance by raser scanning.
I: input image, can have multiple channels. Type should be np.float32.
S: binary image where non-zero pixels... | 0.481698 | 0.678331 |
import datetime
import hashlib
import textwrap
import uuid
import itertools
import json
import logging
import pathlib
import pprintpp
import time
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing impor... | spinta/cli/push.py | import datetime
import hashlib
import textwrap
import uuid
import itertools
import json
import logging
import pathlib
import pprintpp
import time
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing impor... | 0.547585 | 0.100834 |
from mozinor.config.params import *
from mozinor.config.explain import *
Fast_Regressors = {
"DecisionTreeRegressor": {
"import": "sklearn.tree",
"criterion": ["mse", "mae"],
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_lea... | mozinor/config/regressors.py | from mozinor.config.params import *
from mozinor.config.explain import *
Fast_Regressors = {
"DecisionTreeRegressor": {
"import": "sklearn.tree",
"criterion": ["mse", "mae"],
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_lea... | 0.627381 | 0.536434 |
import os
import sys
from faker import Factory
sys.path.append(os.getcwd())
import api
import user
fake = Factory.create()
MOCK_NEW_USER = {
'name': '<NAME>',
'user_id': '3141592654',
'email': '<EMAIL>'
}
MOCK_SCAN = {
"env": {
"LANG": "en_US.UTF-8",
"AWS_DEFAULT_REGION"... | tests/test_api.py | import os
import sys
from faker import Factory
sys.path.append(os.getcwd())
import api
import user
fake = Factory.create()
MOCK_NEW_USER = {
'name': '<NAME>',
'user_id': '3141592654',
'email': '<EMAIL>'
}
MOCK_SCAN = {
"env": {
"LANG": "en_US.UTF-8",
"AWS_DEFAULT_REGION"... | 0.197444 | 0.123656 |
import sys, os, socket, time
def auto_help(name,rank,description):
stbl = " " + name + " "*(13-len(name)+4) + rank + " "*(8-len(rank)+4) + description
return stbl
def auto_targ(targetlist):
print "Vulnrable Applications (%s)\n" %name
print " ID Device"
print " -- ------"
for _ in targetlist:
pr... | example_api.py | import sys, os, socket, time
def auto_help(name,rank,description):
stbl = " " + name + " "*(13-len(name)+4) + rank + " "*(8-len(rank)+4) + description
return stbl
def auto_targ(targetlist):
print "Vulnrable Applications (%s)\n" %name
print " ID Device"
print " -- ------"
for _ in targetlist:
pr... | 0.066255 | 0.061678 |
import datetime
import logging
import os
from airflow import configuration
from airflow import models
from airflow.contrib.hooks import gcs_hook
from airflow.contrib.operators import dataflow_operator
from airflow.operators import python_operator
from airflow.utils.trigger_rule import TriggerRule
# Set start_date of ... | cloud_automation/airflow/dag.py | import datetime
import logging
import os
from airflow import configuration
from airflow import models
from airflow.contrib.hooks import gcs_hook
from airflow.contrib.operators import dataflow_operator
from airflow.operators import python_operator
from airflow.utils.trigger_rule import TriggerRule
# Set start_date of ... | 0.360377 | 0.29626 |
import os
import time
import hmac
from hashlib import md5
from collections import UserDict
from threading import RLock, Lock
from starlette.config import Config
from starlette.templating import Jinja2Templates
templates = Jinja2Templates(directory='web/templates')
async def exception_custom(req, exce_info: int):
... | web/utils.py | import os
import time
import hmac
from hashlib import md5
from collections import UserDict
from threading import RLock, Lock
from starlette.config import Config
from starlette.templating import Jinja2Templates
templates = Jinja2Templates(directory='web/templates')
async def exception_custom(req, exce_info: int):
... | 0.515376 | 0.091544 |
from .enum_loader import enum_loader
from bes.common.string_util import string_util
from bes.system.compat import with_metaclass
class _flag_enum_meta_class(type):
'cheesy enum. Id rather use the one in python3 but i want to support python 2.7 with no exta deps.'
def __new__(meta, name, bases, class_dict):
... | lib/bes/enum/flag_enum.py |
from .enum_loader import enum_loader
from bes.common.string_util import string_util
from bes.system.compat import with_metaclass
class _flag_enum_meta_class(type):
'cheesy enum. Id rather use the one in python3 but i want to support python 2.7 with no exta deps.'
def __new__(meta, name, bases, class_dict):
... | 0.634656 | 0.154695 |
import numpy as np
from collections import OrderedDict, deque
import warnings
import dm_env
from dm_env import specs
from dm_control import suite
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
from dm_control import manipulation
from dm_control.suite.wrappers imp... | dmc.py | import numpy as np
from collections import OrderedDict, deque
import warnings
import dm_env
from dm_env import specs
from dm_control import suite
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
from dm_control import manipulation
from dm_control.suite.wrappers imp... | 0.747063 | 0.281952 |