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 logging
from dataclasses import asdict
import voluptuous as vol
from homeassistant import config_entries
from .const import CONF_URL, CONF_TOKEN, DOMAIN
_LOGGER = logging.getLogger(__name__)
class ZWaveMeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""ZWaveMe integration config flow."""
VE... | homeassistant/components/zwave_me/config_flow.py |
import logging
from dataclasses import asdict
import voluptuous as vol
from homeassistant import config_entries
from .const import CONF_URL, CONF_TOKEN, DOMAIN
_LOGGER = logging.getLogger(__name__)
class ZWaveMeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""ZWaveMe integration config flow."""
VE... | 0.690768 | 0.067701 |
import os
import html
import signal
from chwall.gui.shared import ChwallGui
from chwall.wallpaper import current_wallpaper_info
from chwall.utils import get_binary_path, reset_pending_list
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, GdkPixbuf, GLib, Gtk # noqa: E402
import gettext # ... | chwall/gui/app.py |
import os
import html
import signal
from chwall.gui.shared import ChwallGui
from chwall.wallpaper import current_wallpaper_info
from chwall.utils import get_binary_path, reset_pending_list
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, GdkPixbuf, GLib, Gtk # noqa: E402
import gettext # ... | 0.358578 | 0.064979 |
from behave import Given, When, Then
import time
@Given(u'the manager is on the login page')
def get_login_page(context):
context.driver.get("http://127.0.0.1:5500/home.html")
@When(u'the manager inputs their username into the username bar')
def enter_username(context):
context.home_page.select_username_inp... | steps/manager_steps.py | from behave import Given, When, Then
import time
@Given(u'the manager is on the login page')
def get_login_page(context):
context.driver.get("http://127.0.0.1:5500/home.html")
@When(u'the manager inputs their username into the username bar')
def enter_username(context):
context.home_page.select_username_inp... | 0.359027 | 0.133387 |
import math
class Shot():
def __init__(self, power, angle, my_tank, enemy_tank, map_height, map_width):
self.power = power/5
self.angle = angle
self.my_tank = my_tank
self.enemy_tank = enemy_tank
self.map_width = map_width
self.map_height = map_height
sel... | shot.py | import math
class Shot():
def __init__(self, power, angle, my_tank, enemy_tank, map_height, map_width):
self.power = power/5
self.angle = angle
self.my_tank = my_tank
self.enemy_tank = enemy_tank
self.map_width = map_width
self.map_height = map_height
sel... | 0.518059 | 0.535402 |
import urllib.parse
import requests_oauthlib as roauth
import pandas as pd
from tradeking import utils
BASE_URL = 'https://api.tradeking.com/v1'
_DATE_KEYS = ('date', 'datetime', 'divexdate', 'divpaydt', 'timestamp',
'pr_date', 'wk52hidate', 'wk52lodate', 'xdate')
_FLOAT_KEYS = ('ask', 'bid', 'chg', ... | tradeking/api.py |
import urllib.parse
import requests_oauthlib as roauth
import pandas as pd
from tradeking import utils
BASE_URL = 'https://api.tradeking.com/v1'
_DATE_KEYS = ('date', 'datetime', 'divexdate', 'divpaydt', 'timestamp',
'pr_date', 'wk52hidate', 'wk52lodate', 'xdate')
_FLOAT_KEYS = ('ask', 'bid', 'chg', ... | 0.416559 | 0.245582 |
"""Tests for meteofrance module. Helpers."""
from typing import List
import pytest
from meteofrance_api.helpers import get_phenomenon_name_from_indice
from meteofrance_api.helpers import get_warning_text_status_from_indice_color
from meteofrance_api.helpers import is_coastal_department
from meteofrance_api.helpers im... | tests/test_helpers.py | """Tests for meteofrance module. Helpers."""
from typing import List
import pytest
from meteofrance_api.helpers import get_phenomenon_name_from_indice
from meteofrance_api.helpers import get_warning_text_status_from_indice_color
from meteofrance_api.helpers import is_coastal_department
from meteofrance_api.helpers im... | 0.888976 | 0.427098 |
from blacksheep import Content, Request, Response
from blacksheep.client import ClientSession
from blacksheep.server import Application
from modules.rand import randimg
from modules import ip_todo,sql_todo,qq_todo,randimg_todo,yiyan_todo
from app import docs,service,router
from dataclass import sql,httpclient,con... | main.py | from blacksheep import Content, Request, Response
from blacksheep.client import ClientSession
from blacksheep.server import Application
from modules.rand import randimg
from modules import ip_todo,sql_todo,qq_todo,randimg_todo,yiyan_todo
from app import docs,service,router
from dataclass import sql,httpclient,con... | 0.221267 | 0.069258 |
from app.api.models.LXDModule import LXDModule
from app.lib.conf import MetaConf
from app.api.utils.firebaseAuthentication import firebaseLogin
from app import __metadata__ as meta
import logging
import requests
import subprocess
import shutil
import os
import yaml
import tarfile
logging = logging.getLogger(__name__)
... | app/api/models/LXCImage.py | from app.api.models.LXDModule import LXDModule
from app.lib.conf import MetaConf
from app.api.utils.firebaseAuthentication import firebaseLogin
from app import __metadata__ as meta
import logging
import requests
import subprocess
import shutil
import os
import yaml
import tarfile
logging = logging.getLogger(__name__)
... | 0.193452 | 0.05151 |
import csv
import random
import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial
def loadCsv(filename):
'''
load data.
https://stackoverflow.com/questions/4315506/load-csv-into-2d-matrix-with-numpy-for-plotting
https://machinelearningmastery.com/index-slice-reshape-numpy-arrays-machine-learnin... | knn.py | import csv
import random
import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial
def loadCsv(filename):
'''
load data.
https://stackoverflow.com/questions/4315506/load-csv-into-2d-matrix-with-numpy-for-plotting
https://machinelearningmastery.com/index-slice-reshape-numpy-arrays-machine-learnin... | 0.538983 | 0.651604 |
from odoo import api
from odoo.addons.mail.tests.common import TestMail
class TestTracking(TestMail):
def test_message_track(self):
""" Testing auto tracking of fields. Warning, it has not be cleaned and
should probably be. """
Subtype = self.env['mail.message.subtype']
Data = se... | apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/mail/tests/test_message_track.py |
from odoo import api
from odoo.addons.mail.tests.common import TestMail
class TestTracking(TestMail):
def test_message_track(self):
""" Testing auto tracking of fields. Warning, it has not be cleaned and
should probably be. """
Subtype = self.env['mail.message.subtype']
Data = se... | 0.395951 | 0.207857 |
errors_semantic = []
def append_error_semantic(fila, column, error):
errors_semantic.append(f'({fila}, {column}) - {error}')
class Method:
def __init__(self, id, parametros, returned_type):
self.returnedType = returned_type
self.id = id
self.args = parametros
class Attribute:
def... | src/semantic/types.py | errors_semantic = []
def append_error_semantic(fila, column, error):
errors_semantic.append(f'({fila}, {column}) - {error}')
class Method:
def __init__(self, id, parametros, returned_type):
self.returnedType = returned_type
self.id = id
self.args = parametros
class Attribute:
def... | 0.431105 | 0.163212 |
class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class SolutionTwoPointersIter(object):
def insert(self, head, insertVal):
"""
:type head: Node
:type insertVal: int
:rtype: Node
Time complexity: O(n).
... | lc0708_insert_into_a_sorted_circular_linked_list.py | class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class SolutionTwoPointersIter(object):
def insert(self, head, insertVal):
"""
:type head: Node
:type insertVal: int
:rtype: Node
Time complexity: O(n).
... | 0.766031 | 0.28582 |
import os
import subprocess
from contextlib import contextmanager
from pathlib import Path
from pydockenv import definitions
BIN_PATH = str(Path(definitions.ROOT_DIR, 'bin', 'pydockenv'))
class Commander:
_instance = None
def __init__(self, env=None):
self._bin_path = BIN_PATH
self._env =... | tests/commander.py | import os
import subprocess
from contextlib import contextmanager
from pathlib import Path
from pydockenv import definitions
BIN_PATH = str(Path(definitions.ROOT_DIR, 'bin', 'pydockenv'))
class Commander:
_instance = None
def __init__(self, env=None):
self._bin_path = BIN_PATH
self._env =... | 0.371593 | 0.084682 |
# License for THIS FILE ONLY: CC0 Public Domain Dedication
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import absolute_import, division, with_statement
from textwrap import dedent
from pyflyby._format import FormatParams, fill, pyfill
def test_fill_1():
res... | tests/test_format.py |
# License for THIS FILE ONLY: CC0 Public Domain Dedication
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import absolute_import, division, with_statement
from textwrap import dedent
from pyflyby._format import FormatParams, fill, pyfill
def test_fill_1():
res... | 0.712232 | 0.474266 |
from ffi_navigator import langserver
from ffi_navigator.util import join_path, normalize_path
import logging
import os
curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))
def run_find_definition(server, path, line, character):
uri = langserver.path2uri(path)
res = server.m_text_docume... | tests/python/test_langserver.py | from ffi_navigator import langserver
from ffi_navigator.util import join_path, normalize_path
import logging
import os
curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))
def run_find_definition(server, path, line, character):
uri = langserver.path2uri(path)
res = server.m_text_docume... | 0.393851 | 0.316184 |
from __future__ import absolute_import
from central.decoders import Decoder
from central.exceptions import DecoderError
from datetime import date, datetime, time
from unittest import TestCase
class TestDecoder(TestCase):
def test_get_instance(self):
self.assertEqual(Decoder, type(Decoder.instance()))
... | tests/test_decoders.py | from __future__ import absolute_import
from central.decoders import Decoder
from central.exceptions import DecoderError
from datetime import date, datetime, time
from unittest import TestCase
class TestDecoder(TestCase):
def test_get_instance(self):
self.assertEqual(Decoder, type(Decoder.instance()))
... | 0.779867 | 0.604778 |
import os
import sys
import environs
import re
import datetime
import numpy as np
import math
import locale
import pandas as pd
from pandas import DataFrame
import click
import lib.utils as utils
from config import get_configs_by_filename
from zephir_db_utils import createZephirItemDetailsFileFromDB
from zephir_d... | marctools/output_zephir_records_for_auto_split.py | import os
import sys
import environs
import re
import datetime
import numpy as np
import math
import locale
import pandas as pd
from pandas import DataFrame
import click
import lib.utils as utils
from config import get_configs_by_filename
from zephir_db_utils import createZephirItemDetailsFileFromDB
from zephir_d... | 0.108732 | 0.066539 |
from flask import Module, request, abort, make_response, Response, jsonify, g, send_from_directory, current_app
from werkzeug import secure_filename
from p2ptracker import bencode
import logging
import hashlib
import os
from datetime import datetime
torrents = Module(__name__, url_prefix='/torrents')
log = logging.ge... | p2ptracker/torrents.py | from flask import Module, request, abort, make_response, Response, jsonify, g, send_from_directory, current_app
from werkzeug import secure_filename
from p2ptracker import bencode
import logging
import hashlib
import os
from datetime import datetime
torrents = Module(__name__, url_prefix='/torrents')
log = logging.ge... | 0.29747 | 0.100128 |
from pthat.pthat import Axis
import time
ramp_up_speed = 200
def wait_for_responses(axis, responses_to_check, msg):
responses = axis.get_all_responses()
while not all(x in responses for x in responses_to_check):
responses = responses + axis.get_all_responses()
# Print the responses
print(msg... | examples/ChangeSpeed.py | from pthat.pthat import Axis
import time
ramp_up_speed = 200
def wait_for_responses(axis, responses_to_check, msg):
responses = axis.get_all_responses()
while not all(x in responses for x in responses_to_check):
responses = responses + axis.get_all_responses()
# Print the responses
print(msg... | 0.595728 | 0.372277 |
import logging
import os
import re
from urllib.parse import urlparse
import click
from .config import parse
from .db import Adapter
from .socket import SocketServer
from .util import wait_for
LOGGER = logging.getLogger(__name__)
# Create thread pool, each worker consumes from a queue
# Each worker is configured for s... | logrdis/core.py | import logging
import os
import re
from urllib.parse import urlparse
import click
from .config import parse
from .db import Adapter
from .socket import SocketServer
from .util import wait_for
LOGGER = logging.getLogger(__name__)
# Create thread pool, each worker consumes from a queue
# Each worker is configured for s... | 0.393851 | 0.055234 |
import requests
from sport_activities_features.tcx_manipulation import TCXFile
from datetime import datetime, timedelta
from sport_activities_features.weather_objects.AverageWeather import AverageWeather
from sport_activities_features.weather_objects.Weather import Weather
class WeatherIdentification(object):
r... | sport_activities_features/weather_identification.py | import requests
from sport_activities_features.tcx_manipulation import TCXFile
from datetime import datetime, timedelta
from sport_activities_features.weather_objects.AverageWeather import AverageWeather
from sport_activities_features.weather_objects.Weather import Weather
class WeatherIdentification(object):
r... | 0.648578 | 0.430506 |
from django.db import models
from datetime import datetime
class Language(models.Model):
name = models.CharField(max_length=100, help_text="Name of the language.")
audio_url = models.URLField(help_text="URL of audios.")
published = models.BooleanField(default=True, help_text="Decide whether this language i... | audios/models.py | from django.db import models
from datetime import datetime
class Language(models.Model):
name = models.CharField(max_length=100, help_text="Name of the language.")
audio_url = models.URLField(help_text="URL of audios.")
published = models.BooleanField(default=True, help_text="Decide whether this language i... | 0.580709 | 0.163379 |
from django.shortcuts import render, redirect
from django.views import View
from django.utils.crypto import get_random_string
from django.http import JsonResponse
from django.contrib.staticfiles.utils import get_files
from models.models import *
from API.serializers import PlaylistSerializer
import json
"""
Since... | activity/views.py | from django.shortcuts import render, redirect
from django.views import View
from django.utils.crypto import get_random_string
from django.http import JsonResponse
from django.contrib.staticfiles.utils import get_files
from models.models import *
from API.serializers import PlaylistSerializer
import json
"""
Since... | 0.480479 | 0.068257 |
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Publication():
title : str
content: str
publishedDate : datetime
url : str
media : list
class Parser(ABC):
@abstractmethod
def __init__(self):
pass
@abstractme... | sus/engines/base_engine.py | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Publication():
title : str
content: str
publishedDate : datetime
url : str
media : list
class Parser(ABC):
@abstractmethod
def __init__(self):
pass
@abstractme... | 0.886966 | 0.275702 |
import os
from astropy.io import ascii
try:
from cStringIO import StringIO
BytesIO = StringIO
except ImportError:
from io import StringIO, BytesIO
import io
HERE = os.path.abspath(os.path.dirname(__file__))
class _ASCIISuite:
def setup(self):
self.tables = {}
self.data = {}
... | benchmarks/io_ascii/main.py | import os
from astropy.io import ascii
try:
from cStringIO import StringIO
BytesIO = StringIO
except ImportError:
from io import StringIO, BytesIO
import io
HERE = os.path.abspath(os.path.dirname(__file__))
class _ASCIISuite:
def setup(self):
self.tables = {}
self.data = {}
... | 0.328637 | 0.149004 |
from typing import Final
import numpy as np
from PIL import Image
from PIL.ImageFilter import BoxBlur
# Images will be resized to this before applying SSIM (must be larger than
# `WIN_SIZE`).
SSIM_SIZE: Final = (64, 64)
K1: Final = 0.01 # Algorithm parameter K1 (small constant, see the SSIM paper)
K2: Final = 0.03 ... | imgtools/utils.py | from typing import Final
import numpy as np
from PIL import Image
from PIL.ImageFilter import BoxBlur
# Images will be resized to this before applying SSIM (must be larger than
# `WIN_SIZE`).
SSIM_SIZE: Final = (64, 64)
K1: Final = 0.01 # Algorithm parameter K1 (small constant, see the SSIM paper)
K2: Final = 0.03 ... | 0.925546 | 0.667588 |
from ..constants import *
from ..statics import *
import os, re
class Deleter:
pass
def __init__(self,name,scheme):
self.name = name
self.scheme = scheme
addr_path = self.scheme['locations']['address']+os.sep+self.name+ADDR_EXT
self.addr = open(addr_path,'rb+')
... | galaxydb/low_level/deleter.py | from ..constants import *
from ..statics import *
import os, re
class Deleter:
pass
def __init__(self,name,scheme):
self.name = name
self.scheme = scheme
addr_path = self.scheme['locations']['address']+os.sep+self.name+ADDR_EXT
self.addr = open(addr_path,'rb+')
... | 0.134378 | 0.07603 |
from decimal import Decimal
class Bookings:
"""Representing a collection of Booking objects
"""
def __init__(self, env, customers, pets, services):
self.bookings = {}
self.by_start_date = {}
self.env = env
self.loaded = False
self.customers = customers
self.... | booking.py | from decimal import Decimal
class Bookings:
"""Representing a collection of Booking objects
"""
def __init__(self, env, customers, pets, services):
self.bookings = {}
self.by_start_date = {}
self.env = env
self.loaded = False
self.customers = customers
self.... | 0.471953 | 0.217213 |
import os
from os.path import join
import json
from collections import Counter
def get_counter(dirpath, tag):
dirname = os.path.basename(dirpath)
ann_dirpath = join(dirpath, 'ann')
letters = ''
lens = []
for filename in os.listdir(ann_dirpath):
json_filepath = join(ann_dirpath, filename)
... | ocrImpl/TextImageGenerator.py | import os
from os.path import join
import json
from collections import Counter
def get_counter(dirpath, tag):
dirname = os.path.basename(dirpath)
ann_dirpath = join(dirpath, 'ann')
letters = ''
lens = []
for filename in os.listdir(ann_dirpath):
json_filepath = join(ann_dirpath, filename)
... | 0.19521 | 0.143908 |
import os
import time
import argparse
import torch
from torch import nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import utils
import matplotlib.pyplot as plt
from utils.datasets import create_dataloader
from utils.util import parse_cfg
from models import build_model
from torchviz imp... | train.py | import os
import time
import argparse
import torch
from torch import nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import utils
import matplotlib.pyplot as plt
from utils.datasets import create_dataloader
from utils.util import parse_cfg
from models import build_model
from torchviz imp... | 0.786664 | 0.488466 |
import csv
from scrapy.spider import Spider
from scrapy.http import Request
import os
from itertools import islice
from onderwijsscrapers.items import DANSVoBranch
def float_or_none(string):
try:
return float(string.replace(',','.'))
except Exception:
return None
class DANSVoBranchesSpider(Sp... | onderwijsscrapers/onderwijsscrapers/spiders/dans.py | import csv
from scrapy.spider import Spider
from scrapy.http import Request
import os
from itertools import islice
from onderwijsscrapers.items import DANSVoBranch
def float_or_none(string):
try:
return float(string.replace(',','.'))
except Exception:
return None
class DANSVoBranchesSpider(Sp... | 0.435902 | 0.220217 |
import model
def test_calculated_delta_values():
deltas = model.deltas_state.from_year(1999)
deltas = deltas.update_gross_salary(30000)
deltas = deltas.update_tax(19000)
deltas = deltas.update_tax_refund(700)
deltas = deltas.update_spending(60)
assert 11700 == deltas.total_net_income
assert... | tests/test_model.py | import model
def test_calculated_delta_values():
deltas = model.deltas_state.from_year(1999)
deltas = deltas.update_gross_salary(30000)
deltas = deltas.update_tax(19000)
deltas = deltas.update_tax_refund(700)
deltas = deltas.update_spending(60)
assert 11700 == deltas.total_net_income
assert... | 0.516108 | 0.701659 |
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
SoundFile, ImageFile, Align)
fro... | blocks/robot.py | from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
SoundFile, ImageFile, Align)
fro... | 0.684053 | 0.497131 |
import pytest
import random
import subprocess
import getpass
import shutil
import six
import dask.dataframe as dd
from ..helpers import (
ResettingCounter, skip_unless_gcs, GCS_TEST_BUCKET, df_from_csv_str,
equal_frame_and_index_content)
from bionic.exception import CodeVersioningError
import bionic as bn
... | tests/test_flow/test_persistence_gcs.py | import pytest
import random
import subprocess
import getpass
import shutil
import six
import dask.dataframe as dd
from ..helpers import (
ResettingCounter, skip_unless_gcs, GCS_TEST_BUCKET, df_from_csv_str,
equal_frame_and_index_content)
from bionic.exception import CodeVersioningError
import bionic as bn
... | 0.602529 | 0.464719 |
import ctypes
import os
import shutil
import site
import sys
import urllib.request
class InstallDnD:
def __init__(self):
self.install_success = False
self.message = ""
try:
operating_system = sys.platform
if "linux" in operating_system:
operating_... | topasgraphsim/src/classes/install_dnd.py | import ctypes
import os
import shutil
import site
import sys
import urllib.request
class InstallDnD:
def __init__(self):
self.install_success = False
self.message = ""
try:
operating_system = sys.platform
if "linux" in operating_system:
operating_... | 0.136666 | 0.1015 |
from django.db import models
class Group(models.Model):
STATUS_NORMAL = 1
STATUS_DISBAND = 0
STATUS_ITEMS = (
(STATUS_NORMAL, '正常'),
(STATUS_DISBAND, '解散')
)
name = models.CharField(max_length=50, verbose_name='组合名')
name_jp = models.CharField(max_length=50, verbose_name='日文')... | pictures/models.py | from django.db import models
class Group(models.Model):
STATUS_NORMAL = 1
STATUS_DISBAND = 0
STATUS_ITEMS = (
(STATUS_NORMAL, '正常'),
(STATUS_DISBAND, '解散')
)
name = models.CharField(max_length=50, verbose_name='组合名')
name_jp = models.CharField(max_length=50, verbose_name='日文')... | 0.50415 | 0.081447 |
from binaryninja import *
class ROPChain(BinaryDataNotification):
def __init__(self, bv: BinaryView, segment: Segment, length: int, arch: Architecture):
BinaryDataNotification.__init__(self)
self.bv = bv
self.segment = segment
self.chain = [0x0] * length
self.arch = arch
... | model.py | from binaryninja import *
class ROPChain(BinaryDataNotification):
def __init__(self, bv: BinaryView, segment: Segment, length: int, arch: Architecture):
BinaryDataNotification.__init__(self)
self.bv = bv
self.segment = segment
self.chain = [0x0] * length
self.arch = arch
... | 0.689306 | 0.207074 |
"""REPL arguments tokenizer."""
import sys
import re
class Tokenizer(object): # noqa
"""Main class for the Tokenizer.
Tokenize all the arguments passed into the REPL for parsing.
"""
def __init__(self, chars):
"""Initialize the Tokenizer class.
:chars: Passed in arguments to parse... | mini_matlab/tokenizer.py | """REPL arguments tokenizer."""
import sys
import re
class Tokenizer(object): # noqa
"""Main class for the Tokenizer.
Tokenize all the arguments passed into the REPL for parsing.
"""
def __init__(self, chars):
"""Initialize the Tokenizer class.
:chars: Passed in arguments to parse... | 0.556882 | 0.405979 |
import os
import asyncio
from random import randint, sample
import discord
from discord.ext import commands
class Social:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def kiss(self, context, user: discord.Member):
""" kiss anyone """
msg = '{0} Was KISSED by {1... | social/social.py | import os
import asyncio
from random import randint, sample
import discord
from discord.ext import commands
class Social:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def kiss(self, context, user: discord.Member):
""" kiss anyone """
msg = '{0} Was KISSED by {1... | 0.316264 | 0.139719 |
__all__ = ['PolarToCartesianWarp', 'CameraRadarCoordinateTransform', 'compute_radar_intrinsic_matrix']
# Cell
import tensorflow as tf
from tensorflow.keras import models, layers
import tensorflow_addons as tfa
import numpy as np
from .radar import v1_constants
# Cell
class PolarToCartesianWarp(layers.Layer):
... | radicalsdk/geometry.py |
__all__ = ['PolarToCartesianWarp', 'CameraRadarCoordinateTransform', 'compute_radar_intrinsic_matrix']
# Cell
import tensorflow as tf
from tensorflow.keras import models, layers
import tensorflow_addons as tfa
import numpy as np
from .radar import v1_constants
# Cell
class PolarToCartesianWarp(layers.Layer):
... | 0.909343 | 0.695753 |
import torch
from torch import nn
from typing import Optional
from typing import NamedTuple
from .discriminators import DiscriminatorOutput
from ....misc.toolkit import get_gradient
class GANTarget(NamedTuple):
is_real: bool
labels: Optional[torch.Tensor] = None
class GradientNormLoss(nn.Module):
def ... | cflearn/models/cv/gan/losses.py | import torch
from torch import nn
from typing import Optional
from typing import NamedTuple
from .discriminators import DiscriminatorOutput
from ....misc.toolkit import get_gradient
class GANTarget(NamedTuple):
is_real: bool
labels: Optional[torch.Tensor] = None
class GradientNormLoss(nn.Module):
def ... | 0.944035 | 0.350144 |
from __future__ import division
from itertools import cycle
import numpy as np
import pandas as pd
from psychopy import visual, event
from visigoth.stimuli import Pattern, FixationTask
def create_stimuli(exp):
"""Initialize stimulus objects."""
# Fixation point, with color change detection task
fix = F... | loc/experiment.py | from __future__ import division
from itertools import cycle
import numpy as np
import pandas as pd
from psychopy import visual, event
from visigoth.stimuli import Pattern, FixationTask
def create_stimuli(exp):
"""Initialize stimulus objects."""
# Fixation point, with color change detection task
fix = F... | 0.633183 | 0.311545 |
import json
LEFT_FILE = 'coverage-datailed.json'
RIGHT_FILE = 'coverage-datailed.json'
def line_info(lines):
if lines is None:
return None
all_line_numbers = set()
code_line_numbers = set()
covered_line_numbers = set()
for line in lines:
line_number = line['line_number']
... | coverage/coverage_diff.py | import json
LEFT_FILE = 'coverage-datailed.json'
RIGHT_FILE = 'coverage-datailed.json'
def line_info(lines):
if lines is None:
return None
all_line_numbers = set()
code_line_numbers = set()
covered_line_numbers = set()
for line in lines:
line_number = line['line_number']
... | 0.501709 | 0.191933 |
def api_v4(self):
""" API core commands for Cloudflare API"""
# The API commands for /user/
user(self)
user_load_balancers(self)
user_virtual_dns(self)
# The API commands for /zones/
zones(self)
zones_settings(self)
zones_analytics(self)
zones_firewall(self)
zones_rate_limi... | proxySTAR_V3/certbot/venv/lib/python2.7/site-packages/CloudFlare/api_v4.py |
def api_v4(self):
""" API core commands for Cloudflare API"""
# The API commands for /user/
user(self)
user_load_balancers(self)
user_virtual_dns(self)
# The API commands for /zones/
zones(self)
zones_settings(self)
zones_analytics(self)
zones_firewall(self)
zones_rate_limi... | 0.53607 | 0.101589 |
import shutil
from PIL import Image
from PIL.ExifTags import TAGS
def square(old_path, new_path, side):
"""
剪切图片为正方形
side: 边长
"""
try:
img = Image.open(old_path).convert('RGB')
except IOError:
raise IOError(u'图片格式异常,无法处理。')
w, h = img.size
if w != h or w > side:
... | sharper/util/imgtool.py | import shutil
from PIL import Image
from PIL.ExifTags import TAGS
def square(old_path, new_path, side):
"""
剪切图片为正方形
side: 边长
"""
try:
img = Image.open(old_path).convert('RGB')
except IOError:
raise IOError(u'图片格式异常,无法处理。')
w, h = img.size
if w != h or w > side:
... | 0.275617 | 0.323313 |
from rest_framework import serializers
from django.contrib.sites.shortcuts import get_current_site
from urllib.parse import urlsplit
from posts.models import Post
from comments.api.serializers import CommentListSerializers
from comments.models import Comments
class PostListSerializer(serializers.ModelSerializer):
... | src/posts/api/serializers.py | from rest_framework import serializers
from django.contrib.sites.shortcuts import get_current_site
from urllib.parse import urlsplit
from posts.models import Post
from comments.api.serializers import CommentListSerializers
from comments.models import Comments
class PostListSerializer(serializers.ModelSerializer):
... | 0.595375 | 0.075312 |
import bpy
import os
import sys
import math
from mathutils import Vector, Quaternion, Matrix
from bpy.props import *
from bpy_extras.io_utils import ExportHelper, ImportHelper
from . import mh
from .error import MHError, handleMHError
from . import utils
from .utils import round, setObjectMode
#----------------------... | makehuman-master/blendertools/maketarget/pose.py | import bpy
import os
import sys
import math
from mathutils import Vector, Quaternion, Matrix
from bpy.props import *
from bpy_extras.io_utils import ExportHelper, ImportHelper
from . import mh
from .error import MHError, handleMHError
from . import utils
from .utils import round, setObjectMode
#----------------------... | 0.217254 | 0.224374 |
from misago.acl.testutils import override_acl
from misago.categories.models import Category
from misago.conf import settings
from misago.threads import testutils
from misago.threads.checksums import update_post_checksum
from misago.threads.events import record_event
from misago.threads.moderation import threads as thre... | misago/threads/tests/test_threadview.py | from misago.acl.testutils import override_acl
from misago.categories.models import Category
from misago.conf import settings
from misago.threads import testutils
from misago.threads.checksums import update_post_checksum
from misago.threads.events import record_event
from misago.threads.moderation import threads as thre... | 0.765067 | 0.239549 |
import arrow
from purepage.ext import r, db, abort
class Admin:
"""
后台管理
$shared:
user:
id?str: 用户ID
role?str: 角色
email?email&optional: 邮箱
github?url&optional: Github地址
avatar?url&default="http://purepage.org/static/avatar-default.png": ... | api/purepage/views/admin.py | import arrow
from purepage.ext import r, db, abort
class Admin:
"""
后台管理
$shared:
user:
id?str: 用户ID
role?str: 角色
email?email&optional: 邮箱
github?url&optional: Github地址
avatar?url&default="http://purepage.org/static/avatar-default.png": ... | 0.192463 | 0.175079 |
import torch
import torch.nn as nn
from typing import Dict
class ApexAgent(torch.jit.ScriptModule):
__constants__ = ["multi_step", "gamma"]
def __init__(self, net_cons, multi_step, gamma):
super().__init__()
self.net_cons = net_cons
self.multi_step = multi_step
self.gamma = g... | pyrela/apex.py |
import torch
import torch.nn as nn
from typing import Dict
class ApexAgent(torch.jit.ScriptModule):
__constants__ = ["multi_step", "gamma"]
def __init__(self, net_cons, multi_step, gamma):
super().__init__()
self.net_cons = net_cons
self.multi_step = multi_step
self.gamma = g... | 0.934954 | 0.503052 |
import sys
import os
sys.path.append("src")
args = sys.argv
if len(args) <= 1 :
print("Please specify a command.")
print("Usage recap : ")
print(" sample datapath tempdir nbr_samples")
print("filter datapath tempdir targetpath fieldname")
print("compute_institutions datapath institutionpath")
eli... | main.py | import sys
import os
sys.path.append("src")
args = sys.argv
if len(args) <= 1 :
print("Please specify a command.")
print("Usage recap : ")
print(" sample datapath tempdir nbr_samples")
print("filter datapath tempdir targetpath fieldname")
print("compute_institutions datapath institutionpath")
eli... | 0.087367 | 0.397237 |
import yaml
import os
import re
import train, test
from model import model_lstm
import logging
import torch
import torch.distributed as dist
import torch.nn as nn
# General config
def load_config(path):
''' Loads config file.
Args:
path (str): path to config file
default_path (bool): whether to... | config/configer.py | import yaml
import os
import re
import train, test
from model import model_lstm
import logging
import torch
import torch.distributed as dist
import torch.nn as nn
# General config
def load_config(path):
''' Loads config file.
Args:
path (str): path to config file
default_path (bool): whether to... | 0.661814 | 0.172276 |
import h5py
import numpy as np
class Dataset(object):
def __init__(self, dataset_path, view='pca', view_dims=(0,), noise=0):
"""
Create a new dataset handler for Lorenz data.
:param dataset_path: The path to the HDF5 dataset.
:param view: Which view to use, 'pca' or 'original'. 'pca... | lorenz/dataset.py | import h5py
import numpy as np
class Dataset(object):
def __init__(self, dataset_path, view='pca', view_dims=(0,), noise=0):
"""
Create a new dataset handler for Lorenz data.
:param dataset_path: The path to the HDF5 dataset.
:param view: Which view to use, 'pca' or 'original'. 'pca... | 0.764892 | 0.707733 |
from collections import OrderedDict
import multiprocessing
import os
from typing import Tuple
from numba import jitclass, float64
import pandas as pd
from .util import compile_model, hash_string, DATA_DIR, CACHE_DIR, gev_cdf, random_gev
from .param import FloodPriorParameters
@jitclass(
OrderedDict(
loc... | leveesim/flood.py | from collections import OrderedDict
import multiprocessing
import os
from typing import Tuple
from numba import jitclass, float64
import pandas as pd
from .util import compile_model, hash_string, DATA_DIR, CACHE_DIR, gev_cdf, random_gev
from .param import FloodPriorParameters
@jitclass(
OrderedDict(
loc... | 0.894508 | 0.36923 |
import os
import argparse
import ujson as json
parser = argparse.ArgumentParser()
parser.add_argument(
"--task",
default=None,
type=str,
required=True,
help="Task name",
)
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="data directory",
)
parser.... | run.py | import os
import argparse
import ujson as json
parser = argparse.ArgumentParser()
parser.add_argument(
"--task",
default=None,
type=str,
required=True,
help="Task name",
)
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="data directory",
)
parser.... | 0.592431 | 0.075653 |
import os
import pickle
import tempfile
import unittest
import base64
import sys
import pcapfile.test.fixture as fixture
from pcapfile import savefile
def create_pcap():
"""
Create a capture file from the test fixtures.
"""
tfile = tempfile.NamedTemporaryFile()
if sys.version_info[0] >= 3: # pyt... | pcapfile/test/savefile_test.py | import os
import pickle
import tempfile
import unittest
import base64
import sys
import pcapfile.test.fixture as fixture
from pcapfile import savefile
def create_pcap():
"""
Create a capture file from the test fixtures.
"""
tfile = tempfile.NamedTemporaryFile()
if sys.version_info[0] >= 3: # pyt... | 0.581184 | 0.383295 |
import torch
import torch.nn.functional as F
import torch.utils.data
import torchvision.datasets
import time
batch_size = 64
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Training MNIST Model on', device)
print("=" * 60)
train_dataset = torchvision.datasets.MNIST(root='../data',
... | PyTorch Zero To All S1/10-2Basic CNN Exercise.py | import torch
import torch.nn.functional as F
import torch.utils.data
import torchvision.datasets
import time
batch_size = 64
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Training MNIST Model on', device)
print("=" * 60)
train_dataset = torchvision.datasets.MNIST(root='../data',
... | 0.906423 | 0.680215 |
"""Tests for modeling_strategy_descriptor."""
from absl.testing import absltest
from typing import Dict
from typing import Type
import numpy as np
from wfa_planning_evaluation_framework.models.goerg_model import (
GoergModel,
)
from wfa_planning_evaluation_framework.models.reach_curve import (
ReachCurve,
)
fr... | src/driver/tests/modeling_strategy_descriptor_test.py | """Tests for modeling_strategy_descriptor."""
from absl.testing import absltest
from typing import Dict
from typing import Type
import numpy as np
from wfa_planning_evaluation_framework.models.goerg_model import (
GoergModel,
)
from wfa_planning_evaluation_framework.models.reach_curve import (
ReachCurve,
)
fr... | 0.900169 | 0.316422 |
"""The abstract robot class."""
import abc
from typing import Optional, Sequence
# Action names for robots operating kinematically.
LINEAR_VELOCITY = "linear_velocity"
ANGULAR_VELOCITY = "angular_velocity"
class RobotBase(metaclass=abc.ABCMeta):
"""The base class for all robots used in the mobility team."""
@a... | examples/pybullet/gym/pybullet_envs/minitaur/robots/robot_base.py | """The abstract robot class."""
import abc
from typing import Optional, Sequence
# Action names for robots operating kinematically.
LINEAR_VELOCITY = "linear_velocity"
ANGULAR_VELOCITY = "angular_velocity"
class RobotBase(metaclass=abc.ABCMeta):
"""The base class for all robots used in the mobility team."""
@a... | 0.967302 | 0.691761 |
from flask import jsonify, request, current_app as app
from flask_api import status
from rest.decorators import handle_errors
from web_exceptions import BadRequest
from service.membership_service import MembershipService
from service.user_profile_service import UserProfileService
@app.route("/api/membership", method... | sis-web/rest/membership_controller.py | from flask import jsonify, request, current_app as app
from flask_api import status
from rest.decorators import handle_errors
from web_exceptions import BadRequest
from service.membership_service import MembershipService
from service.user_profile_service import UserProfileService
@app.route("/api/membership", method... | 0.342681 | 0.041191 |
from copy import deepcopy
import extras
class Piece:
moves = []
def __init__(self, name, symbol, team, row, col, points):
self.name = name
self.symbol = symbol
self.team = team
self.row = row
self.col = col
self.points = points
self.has_... | piece.py | from copy import deepcopy
import extras
class Piece:
moves = []
def __init__(self, name, symbol, team, row, col, points):
self.name = name
self.symbol = symbol
self.team = team
self.row = row
self.col = col
self.points = points
self.has_... | 0.630457 | 0.406302 |
from random import choice, randint
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from faker import Faker
from backend.commands import models
fake = Faker()
def make_text(min_paragraphs, max_paragraphs):
return '\n'.join(
fake.paragraphs(nb=randint(mi... | backend/commands/management/commands/fill_fake_data.py | from random import choice, randint
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from faker import Faker
from backend.commands import models
fake = Faker()
def make_text(min_paragraphs, max_paragraphs):
return '\n'.join(
fake.paragraphs(nb=randint(mi... | 0.4917 | 0.079496 |
import errno
import os
import socket
import ssl as sys_ssl
from typing import Union
from thor.dns import lookup
from thor.loop import LoopBase
from thor.tcp import TcpClient, TcpConnection
TcpConnection.block_errs.add(sys_ssl.SSL_ERROR_WANT_READ)
TcpConnection.block_errs.add(sys_ssl.SSL_ERROR_WANT_WRITE)
TcpConnectio... | thor/tls.py | import errno
import os
import socket
import ssl as sys_ssl
from typing import Union
from thor.dns import lookup
from thor.loop import LoopBase
from thor.tcp import TcpClient, TcpConnection
TcpConnection.block_errs.add(sys_ssl.SSL_ERROR_WANT_READ)
TcpConnection.block_errs.add(sys_ssl.SSL_ERROR_WANT_WRITE)
TcpConnectio... | 0.219338 | 0.07373 |
import numpy as np
import logging
import sys
from enum import Enum
import matplotlib.pyplot as plt
from collections import namedtuple
from sklearn.datasets import load_boston
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split, KFold
logging.basicConfig(stream=sys.... | src/linear_regression.py | import numpy as np
import logging
import sys
from enum import Enum
import matplotlib.pyplot as plt
from collections import namedtuple
from sklearn.datasets import load_boston
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split, KFold
logging.basicConfig(stream=sys.... | 0.714628 | 0.394872 |
import logging
import os
from datetime import timedelta
from pathlib import Path
import environ
from django.utils.log import DEFAULT_LOGGING
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env(
# set casting, default value
DEBU... | backend/config/settings.py | import logging
import os
from datetime import timedelta
from pathlib import Path
import environ
from django.utils.log import DEFAULT_LOGGING
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env(
# set casting, default value
DEBU... | 0.47098 | 0.153327 |
import asyncio
from typing import List, Union
from bscscan import BscScan
from web3 import Web3
from senkalib.chain.bsc.bsc_transaction import BscTransaction
from senkalib.chain.transaction import Transaction
from senkalib.chain.transaction_generator import TransactionGenerator
class BscTransactionGenerator(Transac... | src/senkalib/chain/bsc/bsc_transaction_generator.py | import asyncio
from typing import List, Union
from bscscan import BscScan
from web3 import Web3
from senkalib.chain.bsc.bsc_transaction import BscTransaction
from senkalib.chain.transaction import Transaction
from senkalib.chain.transaction_generator import TransactionGenerator
class BscTransactionGenerator(Transac... | 0.705886 | 0.222964 |
import mock
import unittest
import os
from dcipipeline.main import (
process_args,
overload_dicts,
get_prev_stages,
pre_process_stage,
post_process_stage,
upload_junit_files_from_dir,
)
class TestMain(unittest.TestCase):
def test_process_args_empty(self):
args = ["dci-pipeline"]
... | dcipipeline/test_main.py |
import mock
import unittest
import os
from dcipipeline.main import (
process_args,
overload_dicts,
get_prev_stages,
pre_process_stage,
post_process_stage,
upload_junit_files_from_dir,
)
class TestMain(unittest.TestCase):
def test_process_args_empty(self):
args = ["dci-pipeline"]
... | 0.409339 | 0.327295 |
import math
import time
import numpy as np
import taichi as ti
ti.init(arch=ti.gpu)
res = 1280, 720
color_buffer = ti.Vector.field(3, dtype=ti.f32, shape=res)
max_ray_depth = 15
eps = 1e-4
inf = 8.2e0 # Scatter Radius
fov = 0.7 # field of view
dist_limit = 100
camera_pos = ti.Vector([0.00, 0.00, 5.0]) # [x, y, z... | src/prototype/atom.py | import math
import time
import numpy as np
import taichi as ti
ti.init(arch=ti.gpu)
res = 1280, 720
color_buffer = ti.Vector.field(3, dtype=ti.f32, shape=res)
max_ray_depth = 15
eps = 1e-4
inf = 8.2e0 # Scatter Radius
fov = 0.7 # field of view
dist_limit = 100
camera_pos = ti.Vector([0.00, 0.00, 5.0]) # [x, y, z... | 0.579162 | 0.51818 |
import collections
import gym
import numpy as np
from gym import spaces
__all__ = [
'FlatBoxView',
'FlattenObservations',
'BufferObservations',
'SemiSupervisedFiniteReward',
]
def _flatten_space(space):
"""Flaten a space to a 1D box.
Args:
space: A `gym.Space` instance.
Returns... | src/gym_utils/env_wrappers.py | import collections
import gym
import numpy as np
from gym import spaces
__all__ = [
'FlatBoxView',
'FlattenObservations',
'BufferObservations',
'SemiSupervisedFiniteReward',
]
def _flatten_space(space):
"""Flaten a space to a 1D box.
Args:
space: A `gym.Space` instance.
Returns... | 0.912859 | 0.603581 |
import traceback
import uuid
import humanfriendly
from flask import Flask, request, render_template, abort, send_from_directory
from functools import wraps, update_wrapper
from datetime import datetime
from flask import make_response
from panoptes.database import init_db, db_session
from panoptes.models import Workfl... | panoptes/app.py | import traceback
import uuid
import humanfriendly
from flask import Flask, request, render_template, abort, send_from_directory
from functools import wraps, update_wrapper
from datetime import datetime
from flask import make_response
from panoptes.database import init_db, db_session
from panoptes.models import Workfl... | 0.393735 | 0.050988 |
import itertools
import numpy as np
import pytest
import qutip
from qutip.core import data as _data
def expected(qobj, sel):
if qobj.isbra or qobj.isket:
qobj = qobj.proj()
sel = sorted(sel)
dims = [[x for i, x in enumerate(qobj.dims[0]) if i in sel]]*2
new_shape = (np.prod(dims[0]),) * 2
... | qutip/tests/core/test_ptrace.py |
import itertools
import numpy as np
import pytest
import qutip
from qutip.core import data as _data
def expected(qobj, sel):
if qobj.isbra or qobj.isket:
qobj = qobj.proj()
sel = sorted(sel)
dims = [[x for i, x in enumerate(qobj.dims[0]) if i in sel]]*2
new_shape = (np.prod(dims[0]),) * 2
... | 0.539226 | 0.672758 |
from django import forms
from django.forms import widgets
from .models import Product, Supplier, ReceiveGood, DeliveryGood
class DeliveryGoodCreateForm(forms.ModelForm):
class Meta:
model = DeliveryGood
fields = "__all__"
exclude = ["created_by", "updated_by"]
widgets = {
... | app/stores/forms.py | from django import forms
from django.forms import widgets
from .models import Product, Supplier, ReceiveGood, DeliveryGood
class DeliveryGoodCreateForm(forms.ModelForm):
class Meta:
model = DeliveryGood
fields = "__all__"
exclude = ["created_by", "updated_by"]
widgets = {
... | 0.492188 | 0.180269 |
import os
import argparse
from translations import Translations
from framed_image import FramedImage
device_to_frame = {
# All available device_frames can be seen in the device_frames folder
"phone": "pixel2xl",
"sevenInch": "tablet1200x2048",
"tenInch": "tablet1600x2560",
}
def frame_fastlane_scree... | src/frameit.py | import os
import argparse
from translations import Translations
from framed_image import FramedImage
device_to_frame = {
# All available device_frames can be seen in the device_frames folder
"phone": "pixel2xl",
"sevenInch": "tablet1200x2048",
"tenInch": "tablet1600x2560",
}
def frame_fastlane_scree... | 0.451085 | 0.191781 |
def add_filter(bot, update):
from chats_data import chats_data
from filter_dict import filter_dict
chat_id = update.message.chat_id
msg = update.message.text
user = bot.get_chat_member(chat_id, update.message.from_user.id)['status']
if update.message.chat_id in chats_data.keys():
if chats_data[chat_id]['fil... | filters.py | def add_filter(bot, update):
from chats_data import chats_data
from filter_dict import filter_dict
chat_id = update.message.chat_id
msg = update.message.text
user = bot.get_chat_member(chat_id, update.message.from_user.id)['status']
if update.message.chat_id in chats_data.keys():
if chats_data[chat_id]['fil... | 0.153613 | 0.048383 |
from types import SimpleNamespace
from models import SimpleDQN, DuelingDQN
import torch
import warnings
import ptan
import ptan.ignite as ptan_ignite
from ignite.engine import Engine
from ignite.metrics import RunningAverage
from ignite.contrib.handlers import tensorboard_logger as tb_logger
from datetime import time... | Rainbow/config.py | from types import SimpleNamespace
from models import SimpleDQN, DuelingDQN
import torch
import warnings
import ptan
import ptan.ignite as ptan_ignite
from ignite.engine import Engine
from ignite.metrics import RunningAverage
from ignite.contrib.handlers import tensorboard_logger as tb_logger
from datetime import time... | 0.70069 | 0.261687 |
import os
import subprocess
from .interface import AbstractQueue
from ..utils import config
class Queue(AbstractQueue):
mic_script = """#!/bin/sh
ulimit -s unlimited
export PATH={tau_root}/bin:$PATH
export LD_LIBRARY_PATH={ldlibpath}
cd {datadir}/../..
# mark the job as running
echo -n "{exp_name} {insname} mi... | autoperf/queues/mic.py | import os
import subprocess
from .interface import AbstractQueue
from ..utils import config
class Queue(AbstractQueue):
mic_script = """#!/bin/sh
ulimit -s unlimited
export PATH={tau_root}/bin:$PATH
export LD_LIBRARY_PATH={ldlibpath}
cd {datadir}/../..
# mark the job as running
echo -n "{exp_name} {insname} mi... | 0.467089 | 0.118105 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... | pybind/slxos/v16r_1_00b/counts_state/__init__.py | from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... | 0.601008 | 0.074064 |
import unittest
from py_sc_fermi.defect_charge_state import DefectChargeState
from py_sc_fermi.defect_charge_state import FrozenDefectChargeState
class TestDefectChargeStateInit(unittest.TestCase):
def test_defect_charge_state_is_initialised(self):
charge = 1.0
energy = 123.4
degeneracy =... | tests/test_defect_charge_state.py | import unittest
from py_sc_fermi.defect_charge_state import DefectChargeState
from py_sc_fermi.defect_charge_state import FrozenDefectChargeState
class TestDefectChargeStateInit(unittest.TestCase):
def test_defect_charge_state_is_initialised(self):
charge = 1.0
energy = 123.4
degeneracy =... | 0.615203 | 0.65524 |
import sys
import json
import datetime
import requests
import html
import tldextract
from bs4 import BeautifulSoup, Comment
import re
import signal
from urllib.parse import urlparse
from urllib.parse import parse_qs
'''
This contains utilities used by other functions in the YoutubeDataApi class, as well as a few conv... | youtube_api/youtube_api_utils.py | import sys
import json
import datetime
import requests
import html
import tldextract
from bs4 import BeautifulSoup, Comment
import re
import signal
from urllib.parse import urlparse
from urllib.parse import parse_qs
'''
This contains utilities used by other functions in the YoutubeDataApi class, as well as a few conv... | 0.368974 | 0.102799 |
from __future__ import absolute_import
import json
import os
import time
from typing import *
import requests
import six
from .exc import PIXError, PIXLoginError
from .factory import Factory
from .model import PIXProject
from .utils import import_modules
if TYPE_CHECKING:
import requests.cookies
__all__ = [
... | pix/api.py | from __future__ import absolute_import
import json
import os
import time
from typing import *
import requests
import six
from .exc import PIXError, PIXLoginError
from .factory import Factory
from .model import PIXProject
from .utils import import_modules
if TYPE_CHECKING:
import requests.cookies
__all__ = [
... | 0.761095 | 0.122707 |
import sys
import os
PROJECT_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__),
os.pardir)
)
sys.path.append(PROJECT_ROOT)
## Import the relevant Libraries
from RFEM.enums import *
from RFEM.initModel import Model
from RFEM.TypesForMembers.memberHinge import MemberHing... | UnitTests/test_typesForMembers.py |
import sys
import os
PROJECT_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__),
os.pardir)
)
sys.path.append(PROJECT_ROOT)
## Import the relevant Libraries
from RFEM.enums import *
from RFEM.initModel import Model
from RFEM.TypesForMembers.memberHinge import MemberHing... | 0.414662 | 0.285982 |
import base64
from pathlib import Path
import dash_bootstrap_components as dbc
import networkx as nx
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import pydot
from dash import dcc, html
from dash.dependencies import Input, Output, State
from jupyter_dash import J... | app/view.py | import base64
from pathlib import Path
import dash_bootstrap_components as dbc
import networkx as nx
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import pydot
from dash import dcc, html
from dash.dependencies import Input, Output, State
from jupyter_dash import J... | 0.760651 | 0.262245 |
import time
import logging
import sys
import argparse
from decouple import config
import urllib.parse
import re
from utils.qa import grab_qa_for, search_string_in_everything
from utils.levenshtein import levenshtein_ratio_and_distance
from utils.browser_opts import browser_options
from utils.utillities import wait_unti... | linkedin_parser.py | import time
import logging
import sys
import argparse
from decouple import config
import urllib.parse
import re
from utils.qa import grab_qa_for, search_string_in_everything
from utils.levenshtein import levenshtein_ratio_and_distance
from utils.browser_opts import browser_options
from utils.utillities import wait_unti... | 0.072633 | 0.060947 |
import discord
import random
from helpcommands import *
from elo import *
from datetime import datetime
from random import shuffle,randint
client = discord.Client()
busyChannels = []
game = discord.Game(name="Perudo")
diefaces = 6 #Number of faces on a die
startingdice = 5 #H... | Perudo/Perudo.py | import discord
import random
from helpcommands import *
from elo import *
from datetime import datetime
from random import shuffle,randint
client = discord.Client()
busyChannels = []
game = discord.Game(name="Perudo")
diefaces = 6 #Number of faces on a die
startingdice = 5 #H... | 0.310694 | 0.181807 |
from typing import Any
# Local imports
from crawler.services.config import Config
from crawler.services.intervals import TimeInterval
import crawler.communication as communication
def _do_command(command: str, data: Any = None) -> communication.Response:
"""Helper method for passing a command to the scheduler.
... | crawler/crawler/treewalk/scheduler/interface.py | from typing import Any
# Local imports
from crawler.services.config import Config
from crawler.services.intervals import TimeInterval
import crawler.communication as communication
def _do_command(command: str, data: Any = None) -> communication.Response:
"""Helper method for passing a command to the scheduler.
... | 0.941405 | 0.188212 |
import torch
from torch import nn as nn
from torch.nn import functional as F
from .initialized_conv1d import Initialized_Conv1d
from .functional import mask_logits
class SelfAttention(nn.Module):
def __init__(self, d_model, num_head, dropout):
super().__init__()
self.d_model = d_model
sel... | models/qanet2/modules/self_attention.py | import torch
from torch import nn as nn
from torch.nn import functional as F
from .initialized_conv1d import Initialized_Conv1d
from .functional import mask_logits
class SelfAttention(nn.Module):
def __init__(self, d_model, num_head, dropout):
super().__init__()
self.d_model = d_model
sel... | 0.965932 | 0.616359 |
import os
import json
import logging
import requests
logger = logging.Logger('catch_all')
def query_az(query):
json_cis=os.popen(query).read()
return json.loads(json_cis)
def check21():
print("Processing 21...")
return "Check not available with azure CLI"
def check22(subid):
pr... | include/check2.py |
import os
import json
import logging
import requests
logger = logging.Logger('catch_all')
def query_az(query):
json_cis=os.popen(query).read()
return json.loads(json_cis)
def check21():
print("Processing 21...")
return "Check not available with azure CLI"
def check22(subid):
pr... | 0.169612 | 0.064241 |
import numpy as np
import os
import keras
from keras import losses
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras import backend as K
import re
ba... | main.py | import numpy as np
import os
import keras
from keras import losses
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras import backend as K
import re
ba... | 0.811303 | 0.395076 |
import torch
import torch.nn as nn
from torch import sqrt
from torch.distributions.normal import Normal
import sys
sys.path.append("../../")
from popsan_drl.popsan_ppo.popsan import PopSpikeActor
class CriticNet(nn.Module):
"""Critic network: can use for Q Net and V Net"""
def __init__(self, network_shape, s... | popsan_drl/popsan_ppo/core_norm.py | import torch
import torch.nn as nn
from torch import sqrt
from torch.distributions.normal import Normal
import sys
sys.path.append("../../")
from popsan_drl.popsan_ppo.popsan import PopSpikeActor
class CriticNet(nn.Module):
"""Critic network: can use for Q Net and V Net"""
def __init__(self, network_shape, s... | 0.845465 | 0.54468 |
import os
import unittest
from lxml import etree
from corpora.europarl.extractor import EuroparlExtractor, EuroparlPerfectExtractor, EuroparlRecentPastExtractor, \
EuroparlPoSExtractor, EuroparlSinceDurationExtractor, EuroparlFrenchArticleExtractor
from apps.extractor.perfectextractor import PAST
EUROPARL_DATA ... | tests/test_europarl_extractor.py |
import os
import unittest
from lxml import etree
from corpora.europarl.extractor import EuroparlExtractor, EuroparlPerfectExtractor, EuroparlRecentPastExtractor, \
EuroparlPoSExtractor, EuroparlSinceDurationExtractor, EuroparlFrenchArticleExtractor
from apps.extractor.perfectextractor import PAST
EUROPARL_DATA ... | 0.482429 | 0.249617 |
import inspect
class BaseType:
"""Base class for all types.
"""
def valid(self, value):
raise NotImplementedError()
def __or__(self, other):
return OneOf([self, other])
class SimpleType(BaseType):
"""Type class to the simple types like string, integer etc.
"""
def __init__... | hypertype.py | import inspect
class BaseType:
"""Base class for all types.
"""
def valid(self, value):
raise NotImplementedError()
def __or__(self, other):
return OneOf([self, other])
class SimpleType(BaseType):
"""Type class to the simple types like string, integer etc.
"""
def __init__... | 0.744378 | 0.452536 |
from datetime import date, timedelta
from workalendar.core import WesternCalendar, ChristianMixin
from workalendar.core import SUN, MON, THU, SAT
class UnitedStatesCalendar(WesternCalendar, ChristianMixin):
"USA calendar"
FIXED_HOLIDAYS = WesternCalendar.FIXED_HOLIDAYS + (
(7, 4, 'Independence Day'),
... | workalendar/america.py | from datetime import date, timedelta
from workalendar.core import WesternCalendar, ChristianMixin
from workalendar.core import SUN, MON, THU, SAT
class UnitedStatesCalendar(WesternCalendar, ChristianMixin):
"USA calendar"
FIXED_HOLIDAYS = WesternCalendar.FIXED_HOLIDAYS + (
(7, 4, 'Independence Day'),
... | 0.506591 | 0.266715 |
import math
import traceback
from pathlib import Path
from typing import Any, Callable, Iterator, List, NoReturn, Optional, Union
from seutil import IOUtils, LoggingUtils
from tqdm import tqdm
logger = LoggingUtils.get_logger(__name__)
class FilesManager:
"""
Handles the loading/dumping of files in a datase... | roosterize/FilesManager.py | import math
import traceback
from pathlib import Path
from typing import Any, Callable, Iterator, List, NoReturn, Optional, Union
from seutil import IOUtils, LoggingUtils
from tqdm import tqdm
logger = LoggingUtils.get_logger(__name__)
class FilesManager:
"""
Handles the loading/dumping of files in a datase... | 0.78345 | 0.163646 |
import numpy as np
import itertools as it
import random, sys
import scipy.stats as stats
data_dir1 = '/Users/chloe/Documents/Yichen/output_global_compcorr_pc3_v3/'
data_dir2 = '/Users/chloe/Documents/Yichen/output_nondenoise_pc3_v3/'
all_subjects = ['sub-01', 'sub-02', 'sub-04', 'sub-05', 'sub-09', 'sub-15', 'sub-16',... | revision/t_test.py | import numpy as np
import itertools as it
import random, sys
import scipy.stats as stats
data_dir1 = '/Users/chloe/Documents/Yichen/output_global_compcorr_pc3_v3/'
data_dir2 = '/Users/chloe/Documents/Yichen/output_nondenoise_pc3_v3/'
all_subjects = ['sub-01', 'sub-02', 'sub-04', 'sub-05', 'sub-09', 'sub-15', 'sub-16',... | 0.249813 | 0.293009 |
import argparse
import pandas as pd
import shutil, os
import time
def die():
print """Usage: python main.py --gmbrc /home/USER/.config/gmusicbrowser/gmbrc --lastdb /PATH/TO/scrobbles.tsv"""
exit(1)
def backup_gmbrc(gmbrc):
shutil.copy2(gmbrc, os.path.join('.', gmbrc + 'backup' + str(int(time.time()))))
d... | src/main.py | import argparse
import pandas as pd
import shutil, os
import time
def die():
print """Usage: python main.py --gmbrc /home/USER/.config/gmusicbrowser/gmbrc --lastdb /PATH/TO/scrobbles.tsv"""
exit(1)
def backup_gmbrc(gmbrc):
shutil.copy2(gmbrc, os.path.join('.', gmbrc + 'backup' + str(int(time.time()))))
d... | 0.169612 | 0.079567 |
import unittest
import numpy as np
import sympy as sym
import matplotlib
import matplotlib.pyplot as plt
from fractpy.models import NewtonFractal
x = sym.Symbol("x")
i = sym.I
class TestNewtonFractal(unittest.TestCase):
"""Tests for the class Newton Fractal"""
def test_function_init(self):
func =... | tests/test_newton.py |
import unittest
import numpy as np
import sympy as sym
import matplotlib
import matplotlib.pyplot as plt
from fractpy.models import NewtonFractal
x = sym.Symbol("x")
i = sym.I
class TestNewtonFractal(unittest.TestCase):
"""Tests for the class Newton Fractal"""
def test_function_init(self):
func =... | 0.657758 | 0.590514 |
import os
from pxr import Usd, Sdf, UsdGeom
from avalon import io
class ParentPointcacheExporter(object):
def __init__(self, shot_name, parent_subset_name, frame_range=[]):
from reveries.common import get_frame_range
self.output_path = ""
self.children_data = []
self.shot_name = ... | reveries/maya/usd/parent_pointcache_export.py | import os
from pxr import Usd, Sdf, UsdGeom
from avalon import io
class ParentPointcacheExporter(object):
def __init__(self, shot_name, parent_subset_name, frame_range=[]):
from reveries.common import get_frame_range
self.output_path = ""
self.children_data = []
self.shot_name = ... | 0.389082 | 0.153169 |
import json
from OpenstackManager import OpenstackManager
from OpenstackContext import OpenstackContext
from AAIManager import AAIManager
class HeatBridge:
def __init__(self):
pass;
def init_bridge(self, openstack_identity_url, username, password, tenant, region, owner):
self.om = OpenstackMan... | simple-grpc-client/target/test-classes/OpenECOMP_ETE/testsuite/heatbridge/heatbridge/heatbridge/HeatBridge.py | import json
from OpenstackManager import OpenstackManager
from OpenstackContext import OpenstackContext
from AAIManager import AAIManager
class HeatBridge:
def __init__(self):
pass;
def init_bridge(self, openstack_identity_url, username, password, tenant, region, owner):
self.om = OpenstackMan... | 0.169784 | 0.09314 |
import nacl.utils
from nacl.public import PrivateKey, SealedBox
import pytest
import responses
import pandas as pd
import numerbay
from numerbay import API_ENDPOINT_URL
@pytest.fixture(scope="function", name="api")
def api_fixture():
api = numerbay.NumerBay(verbosity="DEBUG")
return api
def test_NumerBay(... | tests/test_numerbay.py | import nacl.utils
from nacl.public import PrivateKey, SealedBox
import pytest
import responses
import pandas as pd
import numerbay
from numerbay import API_ENDPOINT_URL
@pytest.fixture(scope="function", name="api")
def api_fixture():
api = numerbay.NumerBay(verbosity="DEBUG")
return api
def test_NumerBay(... | 0.509032 | 0.322126 |
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.index, name='index'),
path('user/', views.UserView.user, name='user'),
path('user/<int:user_id>', views.UserView.user_profile),
path('user/update/', views.UpdateUserView.update),
... | wao/urls.py | from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.index, name='index'),
path('user/', views.UserView.user, name='user'),
path('user/<int:user_id>', views.UserView.user_profile),
path('user/update/', views.UpdateUserView.update),
... | 0.341473 | 0.0545 |