id
stringlengths
3
8
content
stringlengths
100
981k
11550828
import discord from .base import BaseRule MAX_WORDS_KEY = "max_words" class MaxWordsRule(BaseRule): def __init__( self, config, ): super().__init__(config) self.name = "MaxWordsRule" async def get_max_words_length( self, guild: discord.Guild, ): """Method to g...
11550884
from .trainer import TOCTrainer from .default_args import ARGS_TOC_TRAIN, ARGS_TOC_EVAl, ARGS_TOC_TEST name = "happytransformer.toc"
11550904
import base64 import json import os from typing import Dict, TypeVar from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import Encoding import const import rogue_ca T = TypeVar('T') C = TypeVar('C') def...
11550926
from gen import Tree, gentree from operator import lt, gt from sys import stdout, maxint minint = -maxint - 1 class DrawTree: def __init__(self, tree, depth=-1): self.x = -1 self.y = depth self.tree = tree self.children = [] self.thread = None self.mod = 0 def l...
11550962
from lego.apps.users.constants import GROUP_COMMITTEE, GROUP_GRADE from lego.apps.users.models import AbakusGroup from lego.utils.functions import insert_abakus_groups # isort:skip """ The structure of the tree is key and a list of two dicts. The first dict is the parameters of the current group and the second dict a...
11550996
import os import numpy as np from nobos_commons.data_structures.constants.dataset_part import DatasetPart from nobos_commons.data_structures.dimension import ImageSize from nobos_commons.utils.file_helper import get_create_path from nobos_torch_lib.datasets.action_recognition_datasets.ehpi_dataset import NormalizeEhpi...
11551065
from collections import Counter import matplotlib import numpy as np from matplotlib import pyplot as plt from .mapview import MapView from sompy.visualization.plot_tools import plot_hex_map class BmuHitsView(MapView): def _set_labels(self, cents, ax, labels, onlyzeros, fontsize, hex=False): for i, tx...
11551095
import os import re import json import tqdm import torch import sqlite3 import converter import argparse import embeddings as E from vocab import Vocab from collections import defaultdict, Counter from transformers import DistilBertTokenizer from eval_scripts import evaluation import editsql_preprocess import editsql_...
11551105
import unittest from solution import findMissing class TestRanges(unittest.TestCase): def test1(self): # Testing input with integer missing other than zero assert findMissing([0,1,2,4]) == 3 def test2(self): # Testing input with zero missing assert findMissing([1,2,3]) == 0 i...
11551120
import tensorflow as tf import numpy as np import random import gym import gym_gazebo import math import matplotlib.pyplot as plt import matplotlib import matplotlib.pyplot as plt env = None class LivePlot(object): def __init__(self, outdir, data_key='episode_rewards', line_color='blue'): """ Livep...
11551127
import numpy import pytest from aydin.analysis.image_metrics import ( mutual_information, joint_information, spectral_mutual_information, spectral_psnr, ) from aydin.io.datasets import camera, add_noise, normalise def test_spectral_psnr(): camera_image = normalise(camera()).astype(numpy.float) ...
11551131
from pathlib import Path from typing import List from asciimatics.exceptions import ResizeScreenError # type: ignore from asciimatics.scene import Scene # type: ignore from asciimatics.screen import Screen # type: ignore from hesiod.cfg.cfghandler import CFG_T from hesiod.ui.tui.baseform import BaseForm from hesio...
11551208
import os, glob import numpy as np import tempfile import tables as tb from pandas.util.testing import assert_frame_equal from flaky import flaky from isochrones.mist import MIST_Isochrone from isochrones import StarModel from isochrones.starfit import starfit from isochrones.logger import getLogger mnest = True try...
11551245
from appdaemontestframework.hass_mocks import HassMocks import datetime class TimeTravelWrapper: """ AppDaemon Test Framework Utility to simulate going forward in time """ def __init__(self, hass_mocks: HassMocks): self._hass_mocks = hass_mocks def fast_forward(self, duration): ""...
11551270
import requests import string import random import base64 import time import json from io import BytesIO from requests_toolbelt import MultipartEncoder ''' <form method="post" action="http://2captcha.com/in.php"> <input type="hidden" name="method" value="base64"> <input type="hidden" name="coordinatescapt...
11551274
from django.forms.forms import BoundField class BaseForm(object): """ This is the main implementation of all the Form logic. Note that this class is different than Form. See the comments by the Form class for more information. Any improvements to the form API should be made to *this* class, not to t...
11551276
def plot_kinematics(signal, background, nbins=100, mass_range=(50., 110.), pt_range=(200., 500.), mass_pad=10, pt_pad=50, linewidth=1, title=None): import numpy as np from matplotlib import pyplot as plt import h5py pt_min, pt_max = pt_range ...
11551288
import ptypes from ptypes import * from ..__base__ import stackable layers = { 2 : 0x0800 } class header(pstruct.type, stackable): _fields_ = [ (pint.littleendian(pint.uint32_t), 'family'), ] def nextlayer_id(self): res = self['family'].li.int() return layers[res]
11551340
balance = 4213 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 monthlyInterestRate = annualInterestRate / 12 annualPayment = 0.0 for month in range(1, 13): minimumMonthlyPayment = monthlyPaymentRate * balance updatedBalanceEachMonth = (balance - minimumMonthlyPayment) * (1 + monthlyInterestRate) annualP...
11551347
from Proceso import Proceso, crea_procesos, medias_procesos, llega_proceso """ Algoritmo de Planificacion SPN """ def genera_lista_procesos(): lista = [] p1 = Proceso(0,3,"A") p2 = Proceso(1,5,"B") p3 = Proceso(3,2,"C") p4 = Proceso(9,5,"D") p5 = Proceso(12,5,"E") lista.append(p1) lista.append(p2) l...
11551356
import unittest from ctree.c.nodes import Constant, String class TestConstants(unittest.TestCase): """Check that all constants convert properly.""" def test_float_00(self): assert str(Constant(0)) == "0" def test_float_01(self): assert str(Constant(1)) == "1" def test_float_02(self...
11551442
from .connection import Connection from .http_connection import HTTPConnection from .lockfile import Lockfile from .websocket import WebSocket
11551462
import os import sys import cv2 from PIL import Image import numpy as np import paddle import torch from reprod_log import ReprodLogger, ReprodDiffHelper def build_paddle_transform(): sys.path.insert(0, "./AlexNet_paddle/") import AlexNet_paddle.presets as presets paddle_transform = presets.Classification...
11551475
from typing import List import time from pathlib import Path from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec from selenium.common.exceptions import TimeoutException as SeleniumTimeoutException ...
11551482
TRAINING_DATA = [ ( "去年アスムテルダムに行った。運河がきれいだった。", {"entities": [(2, 9, "TOURIST_DESTINATION")]}, ), ( "人生で一度はパリに行くべきだけど、エッフェル塔はちょっとつまらないな。", {"entities": [(6, 8, "TOURIST_DESTINATION")]}, ), ("アーカンソーにもパリはあるw", {"entities": []}), ( "ベルリンは夏が最高!公園がたくさんあって、夜遊びが充...
11551504
from kafka import KafkaProducer import json import random from datetime import datetime # BROKERS = "b-1.stocks.8e6izk.c12.kafka.us-east-1.amazonaws.com:9092,b-2.stocks.8e6izk.c12.kafka.us-east-1.amazonaws.com:9092" BROKERS = "localhost:9092" producer = KafkaProducer( bootstrap_servers=BROKERS, value_serialize...
11551536
import abc from typing import Dict import numpy as np from robogym.observation.common import Observation, ObservationProvider class ImageObservationProvider(ObservationProvider, abc.ABC): """ Interface for observation provider which can provide rendered image. """ @property @abc.abstractmethod ...
11551537
saveFrames = False waitForClick = False frameLimit = 1200 n = 20 rings = [] rate = 10 h = 0 class Ring: def __init__(self, centerRadius, thickness, pattern=[1], c=color(255,255,255,128), rotation=0, zoom=0): self.cR = centerRadius self.t = thickness self.pat = pattern self.c = c ...
11551539
import shodan import requests import time import sys from colorama import Fore, Back, Style def vulnscan(host, api_key): try: print(f'[{Fore.YELLOW}?{Style.RESET_ALL}] Vulnerability scanning on {Fore.YELLOW}{host}{Style.RESET_ALL}...') target = host api = shodan.Shodan(api_key) dns...
11551576
import paddle import paddle.nn as nn import paddle.nn.functional as F import x2paddle.torch2paddle as init import pickle import numpy as np import os import time from constants import * """ step4: generate the POI id embedding files for each city. These embeddings are fixed during training. TODO: according to the paper...
11551594
from elasticsearch_dsl import Integer, DocType, Text, Boolean from .index_aliases import tracker_index_alias from search.analyzers import autocomplete, autocomplete_search, text_analyzer, text_search_analyzer @tracker_index_alias.doc_type class AttachmentFileDocType(DocType): id = Integer() crid = Text(analy...
11551602
import sys sys.path.insert(0, "Core") sys.path.insert(0, "unit_Tests") from constants import * import pwmServo as servo import kinematics as ik import time import math from helpers import * import JGpio as gpio import IMU as imu class Quadruped: def __init__(self,servoIndexes=None): servo.init() ...
11551620
import gzip import json import os import shutil import time from pathlib import Path import dns.resolver import geoip2.database import requests from folium import Map, Marker, Popup from core.utils import DOMAIN, Helpers, logger helpers = Helpers() # Working program directories prog_root = Path(os.path.dirname(os.p...
11551635
from datetime import timedelta from backend.common.decorators import cached_public from backend.web.profiled_render import render_template @cached_public(ttl=timedelta(weeks=1)) def apidocs_trusted_v1() -> str: template_values = { "title": "Trusted APIv1", "swagger_url": "/swagger/api_trusted_v1....
11551641
import numpy as np import pandas as pd import torch from torch.utils.data import Dataset, DataLoader # Load all of the BBS data into a DataFrame bbs = pd.merge( pd.read_csv("data/cleaned/bbs.csv"), pd.read_csv("data/cleaned/clean_routes.csv"), how="left", on="route_id", ) # Create dictionaries that ma...
11551676
from pathlib import Path from urllib.parse import urlparse import click import requests import database_connection # noqa: F401 from matrix_connection import get_download_url from schema import Message def download_stem(message, prefer_thumbnails): image_url = (message.thumbnail_url if prefer_thumbnails else N...
11551691
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() async def fake_video_streamer(): for i in range(10): yield b"some fake video bytes" @app.get("/") async def main(): return StreamingResponse(fake_video_streamer())
11551734
from typing import Mapping from colorama import Fore, Style from typing_extensions import Literal SupportedColorName = Literal[ "RED", "YELLOW", "GREEN", "CYAN", "GRAY", "MAGENTA", "RESET", "BLUE" ] class LogColorProvider: def __init__(self): self.is_ci_mode = False def get_color( self,...
11551745
import sys, os curmodulepath = os.path.dirname(os.path.abspath(__file__)) if hasattr(sys, 'pypy_version_info'): sys.path.insert(0, os.path.abspath(os.path.join(curmodulepath, '..', 'pypylib'))) sys.path.insert(0, os.path.abspath(os.path.join(curmodulepath, '..'))) sys.path.insert(0, os.path.abspath(os.path.join(c...
11551753
import os, re import pyric.pyw as pyw ROOT = os.geteuid() == 0 MWINTERFACES = [x for x in pyw.winterfaces() if pyw.modeget(x) == "monitor"] INTERFACES = [x for x in pyw.interfaces()] BAD_MAC = [ "ff:ff:ff:ff:ff:ff", "00:00:00:00:00:00", # Multicast "01:80:c2:00:00:00", # Multicast "01:00:5e", # M...
11551771
from __future__ import absolute_import from __future__ import division from __future__ import print_function from imlib.basic import * from imlib.dtype import * from imlib.encode import * from imlib.transform import *
11551775
import os import tempfile import unittest from io import BytesIO import odil class TestWriter(unittest.TestCase): def test_constructor_1(self): stream = odil.iostream(BytesIO()) writer = odil.Writer(stream, odil.ByteOrdering.LittleEndian, False) self.assertEqual(writer.byte_ordering, odil...
11551784
from waltz_ducktape.services.cli.base_cli import Cli class ClientCli(Cli): """ ClientCli is an utility class to interact with com.wepay.waltz.tools.client.ClientCli. """ def __init__(self, cli_config_path): """ Construct a new 'ClientCli' object. :param cli_config_path: The pa...
11551785
import prettytable from schedule import Schedule from genetic import GeneticOptimize def vis(schedule): """visualization Class Schedule. Arguments: schedule: List, Class Schedule """ col_labels = ['week/slot', '1', '2', '3', '4', '5'] table_vals = [[i + 1, '', '', '', '', ''] for i in r...
11551802
from compileall import compile_dir from ._base import DanubeCloudCommand, CommandOption class Command(DanubeCloudCommand): help = 'Recursively byte-compile all modules in ERIGONES_HOME.' options = ( CommandOption('-q', '--que', '--node', action='store_true', dest='que_only', default=False, ...
11551807
import numpy as np import pytest from pymoo.factory import get_problem from pymoo.indicators.kktpm import KKTPM from pymoo.problems.autodiff import AutomaticDifferentiation from pymoo.problems.bounds_as_constr import BoundariesAsConstraints from tests.util import path_to_test_resource SETUP = { "bnh": {'utopian_e...
11551831
from globals import * from percent_change import percent_change def current_pattern(average_line, pattern_for_recognition: list): """ Create a pattern that will be compared to in-memory patterns formed by the last dots_for_pattern entries of the data """ # This pattern will be based on the last 10 elem...
11551839
from random import choice, random, sample import numpy as np import networkx as nx from BanditAlg.BanditAlgorithms import ArmBaseStruct import datetime class LinUCBUserStruct: def __init__(self, featureDimension,lambda_, userID, RankoneInverse = False): self.userID = userID self.d = featureDimension self.A = la...
11551852
import asyncio from typing import AsyncGenerator, Any, Type, List from datetime import timedelta from deepdiff import DeepDiff from pytest import fixture, mark from core.message_bus import MessageBus, Message, Event, Action, ActionDone, ActionError from core.model.typed_model import to_js, from_js from core.util impo...
11551861
import torch from torch import nn from torch.nn import functional as F from detectron2.layers import Conv2d, ShapeSpec, cat, get_norm from detectron2.utils.registry import Registry import numpy as np import fvcore.nn.weight_init as weight_init from .cross_fetaure_affinity_pooling import CrossFeatureAffinityPooling f...
11551862
from selenium import webdriver import requests import os import hashlib from PIL import Image import time import io def get_image_urls(wd:webdriver, search_url): def scroll_to_end(wd): wd.execute_script("window.scrollTo(0, document.body.scrollHeight);") wd.get(search_url) time.sleep(2) image_...
11551872
import nbformat def empty_notebook(fname): with open(fname, 'r', encoding='utf-8') as fp: nb = nbformat.read(fp, as_version=4) for cell in nb.cells: if cell['cell_type'] == 'code': source = cell['source'] if '# aeropython: preserve' in source: continue ...
11551890
import os import random, math import torch import numpy as np import glob import cv2 from tqdm import tqdm from skimage import io from ISP_implement import ISP if __name__ == '__main__': isp = ISP() source_dir = './source/' target_dir = './target/' if not os.path.isdir(target_dir): os.makedirs(target_dir) ...
11551924
from django.test import TestCase from django.core.exceptions import ValidationError from wagtail.core.models import Site from wagtailmenus.tests.models import LinkPage class TestLinkPage(TestCase): fixtures = ['test.json'] def setUp(self): # Create a few of link pages for testing site = Site...
11551948
import numpy as np import tensorflow as tf def deepfuse_triple_untied(inp1, inp2, inp3): layers = tf.layers leaky_relu=tf.nn.leaky_relu with tf.variable_scope('DeepFuse'): prepooled_feats = [[],[],[]] num_downsample_layers = 4 branch_enc = [] num_feats = [32,64,128,256] ...
11552008
from . import encode import numpy def pygame_play(data, rate=44100): ''' Send audio array to pygame for playback ''' import pygame pygame.mixer.init(rate, -16, 1, 1024) sound = pygame.sndarray.numpysnd.make_sound(encode.as_int16(data)) length = sound.get_length() sound.play() pygame.ti...
11552019
import numpy as np def print_array(data): datas = [] for i in data: datas.append(i) print(datas) x = np.array([1, 2, 3]) print_array(x) y = np.copy(x) print_array(y) x[0] = 10 print_array(x) print_array(y)
11552030
from .base import * import os import sys DEBUG = False ADMINS = (("ch1huizong", "<EMAIL>"),) allowed_hosts = os.get('ALLOWED_HOSTS') if allowed_hosts: ALLOWED_HOSTS = allowed_hosts.split(",") else: print("ERROR ! Please Input ALLOWED_HOSTS env settings !") sys.exit(1) db_host = os.getenv("DB_HOST") db_...
11552053
import copy from typing import Any, Iterator, List, Union import numpy as np import torch from detectron2.layers.roi_align import ROIAlign from torchvision.ops import RoIPool class MyMaps(object): """# NOTE: This class stores the maps (NOCS, coordinates map, pvnet vector maps, offset maps, heatmaps) for all...
11552070
import asyncio import dragonfly as df import title_menu, menu_utils, server, df_utils, game, letters LOAD_GAME_MENU = 'loadGameMenu' def validate_load_game_menu(menu): return title_menu.get_submenu(menu, LOAD_GAME_MENU) async def load_game(menu, game_idx: int): button_index = game_idx try: btn = ...
11552097
from typing import Any, Dict, List, Optional from dirty_models import ModelField, HashMapField, ArrayField, IntegerField, StringIdField from . import BaseModelManager, BaseCollectionManager from .contact import Contact, ContactManager from ..models import BaseModel, DateTimeField from ..driver import BaseWhalesongDriv...
11552181
import os import pytest import pandas as pd from unittest.mock import patch, ANY from pyrestcli.exceptions import ServerErrorException from cartoframes.auth import Credentials from cartoframes.data.observatory.catalog.entity import CatalogList from cartoframes.data.observatory.catalog.dataset import Dataset from car...
11552186
import _plotly_utils.basevalidators class TypeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="type", parent_name="layout.updatemenu", **kwargs): super(TypeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
11552217
import base64 import hashlib import logging import random from django.conf import settings from django.contrib.auth import authenticate, login from django.urls import reverse from accounts.events import post_group_membership_updates from . import SESSION_KEY logger = logging.getLogger("zentral.realms.utils") try: ...
11552227
from .response import Response from .driver import Driver __all__ = ["Response", "Driver"] __version__ = "0.2.2"
11552286
import numpy as np from dataset_specifications.real_dataset import RealDataset from sklearn import preprocessing as skpp import sklearn.datasets as skl_ds class HousingSet(RealDataset): def __init__(self): super().__init__() self.name = "housing" self.requires_path = False self.x_...
11552301
hyper = { "GCN": { "model": { "name": "GCN", "inputs": [ {"shape": [None, 8710], "name": "node_attributes", "dtype": "float32", "ragged": True}, {"shape": [None, 1], "name": "edge_weights", "dtype": "float32", "ragged": True}, {"shape":...
11552312
import lemoncheesecake.api as lcc @lcc.suite("Suite 2") class suite_2: @lcc.test("Test 1") @lcc.prop("priority", "low") def test_1(self, fixt_7): pass @lcc.test("Test 2") @lcc.prop("priority", "low") def test_2(self, fixt_4): pass @lcc.test("Test 3") @lcc.prop("priorit...
11552386
load("@bazel_skylib//:lib.bzl", "asserts", "unittest") load("//lib:json_parser.bzl", "json_parse") load(":json_parse_test_data.bzl", "get_pkg_jsons") def _valid_json_parse_test(ctx): env = unittest.begin(ctx) asserts.equals(env, json_parse("[]"), []) asserts.equals( env, json_parse('["x", ...
11552466
class Solution: def minAddToMakeValid(self, S: str) -> int: stack = [] # Creating a stack if len(S)==0: return 0 stack = [S[0]] for i in range(1,len(S)): # Updating stacks according to the input if stack and stack[-1]=='(' an...
11552469
import unittest from pynYNAB.schema import BudgetVersion, MasterCategory, SubCategory, Payee from tests.common_mock import factory, MockConnection class TestCommonMock(unittest.TestCase): def setUp(self): self.client = factory.create_client(budget_name='TestBudget', ...
11552477
import numpy as np import math import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import backend as K import gpflow import pickle from sklearn.pipeline import make_pipeline from sklearn.ensemble import RandomForestRegressor from sklearn.decomposition import N...
11552522
import asyncio import json from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Type, Union import aiohttp import requests API = 'https://api.zhconvert.org' class FanhuajiEngine(): """繁化姬轉換引擎""" def _request(self, endpoint: str, payload: dict): with requests.get(f'{API}{endpoint}', da...
11552539
from dataclasses import dataclass, field from typing import Optional import os from dotenv import load_dotenv, find_dotenv @dataclass(frozen=True) class Env: """Loads all environment variables into a predefined set of properties """ dotenv_path = find_dotenv() print(f"find_dotenv returns: {dotenv_pat...
11552595
from __future__ import absolute_import from django.db import models from .. import exc class ProtocolType(models.Model): """ Representation of protocol types (e.g. bgp, is-is, ospf, etc.) """ name = models.CharField( max_length=16, db_index=True, help_text='Name of this type of protoc...
11552606
from django.contrib.auth.models import User from nose.tools import ok_, eq_ from airmozilla.base.tests.testbase import DjangoTestCase from airmozilla.search.models import SavedSearch from airmozilla.main.models import Event, Tag, Channel class SavedSearchTestCase(DjangoTestCase): def test_get_events(self): ...
11552631
from cloudinary.forms import CloudinaryFileField from django import forms integerfields = { 'max_quantity_available': True, 'original_price': True, 'quorum': True, 'current_price': True, } class DealForm(forms.Form): """ Handles verification of form inputs """ active = forms.BooleanF...
11552635
from datasets.base.storage_engine.memory_mapped import ListMemoryMapped from datasets.types.incompatible_error import IncompatibleError from datasets.base.common.operator.filters import filter_list_deserialize from datasets.base.common.dataset_context_dao import DatasetContextDAO from datasets.types.data_split import D...
11552645
from discord.ext.commands import Context, check from discord.ext.commands.errors import CheckFailure class NotModerator(CheckFailure): """Exception raised when the command invoker isn't on the moderator list.""" def __init__(self): super().__init__( "You are not a moderator on this server...
11552651
from typing import List, Dict, Optional from src.metrics.partial_match_eval.utils import get_recursively, flatten class JSQLReader: @staticmethod def parse_sql_to_parsed_body(parsed_sql: Dict, anonymize_values: bool, parse_on_clause: bool) -> Dict: select_bodies = [] for key, value in parsed_...
11552675
import os import threading import warnings from collections import OrderedDict from io import BytesIO import matplotlib.pyplot as plt import numpy as np from PIL import Image from matplotlib.backends.backend_pdf import PdfPages class Collect(object): """ Collect figures and export to a file Args: ar...
11552678
import os import subprocess import pandas as pd import copy import yaml import copy from .factories.mysql import MySqlFactory from .factories.pandas import PandasFactory from .factories.postgres import PostgresFactory from .factories.spark import SparkFactory from .factories.sqlserver import SqlServerFactory root_url...
11552714
import time import pytest from dockupdater.lib.config import OptionRegex from dockupdater.update.container import Container from dockupdater.update.service import Service def prepare_containers(scanner): print("creating containers and services") if not scanner.client.swarm.attrs: scanner.client.swa...
11552718
import os, tempfile, time from os import getenv as _ from utils import uploader from dotenv import load_dotenv load_dotenv() os.environ['UPLOAD_DRIVE'] = os.sys.argv[1] handle, params = uploader().handle, uploader().params() def upload(size): fd, path = tempfile.mkstemp() with open(path, 'wb') as f: f.write(o...
11552844
import re, nltk, sys from nltk.tokenize import StanfordTokenizer tokenizer = StanfordTokenizer(r'../common/stanford-postagger-2015-04-20/stanford-postagger.jar') for line in open("TEST_FILE.txt"): m = re.match(r'^([0-9]+)\s"(.+)"$', line.strip()) if m is not None: txtfile = open("test/%s.txt" % m.group...
11552857
from misc.utils import * from misc.priority_queue import PriorityQueue Node = namedtuple('Node', ['cost', 'operators']) """ class Node(Set, object): def __init__(self, operators): self.operators = operators self.cost = self._cost() def __contains__(self, operator): return operator in self.operators ...
11552875
from crudlfap import shortcuts as crudlfap from .models import Post class AuthBackend: def authenticate(self, *args): return None # prevent auth from this backend def has_perm(self, user_obj, perm, obj=None): view = obj if view.model != Post: return False user ...
11552889
from reaction_filters import ReactionFiltersEnum from reaction_filters.base_reaction_filter import BaseReactionFilter from reaction_filters.non_selective_filter import NonSelectiveFilter from reaction_filters.selective_filter import SelectiveFilter from running_modes.configurations.reaction_filter_configuration import ...
11552965
import fire import os import re import torch from models import * from utils.audio import * from utils.display import simple_table from hparams import hparams use_cuda = torch.cuda.is_available() batch_size = 1 def _pad_2d(x, max_len, constant_values=0): x = np.pad(x, [(0, max_len - len(x)), (0, 0)], ...
11552978
from nipype.interfaces.base import (TraitedSpec, File, traits, InputMultiPath, BaseInterface, OutputMultiPath, BaseInterfaceInputSpec, isdefined) from nipype.interfaces.ants import registration, segmentation from nipype.interfaces.ants.segmentation import Atropos from nipype.interfaces.ants import Registration...
11552991
import logging from fcntl import ioctl import v4l2 class V4L2Ctrls: def __init__(self, device, fd): self.device = device self.fd = fd self.get_device_cap() self.get_device_controls() def setup_v4l2_ctrls(self, params): for k, v in params.items(): if k in [...
11552994
import sys import os sys.path.insert(0, os.path.abspath('..')) # from pprint import pprint as p # p(sys.path) from exploredata.order import ExploreOrder from exploredata.traffic import ExploreTraffic from exploredata.weather import ExploreWeather from prepareholdoutset import PrepareHoldoutSet from utility.datafilep...
11553037
from os import path from os.path import dirname, abspath import sys import numpy as np from math import pi from scipy.stats import norm from sklearn.mixture import GaussianMixture import matplotlib.pyplot as plt try: sys.path.append(dirname(dirname(dirname(abspath(__file__))))) except IndexError: pass from ag...
11553060
from securityheaders.models import Keyword class FeaturePolicyKeyword(Keyword): SELF = "'self'" NONE = "'none'" STAR = "*" @staticmethod def isKeyword(keyword): """ Checks whether a given string is a FeaturePolicyKeyword. Args: keyword (str): the string to validate ...
11553072
import re from collections import OrderedDict def _replace_end(string, end, new_end): if string == end: return new_end if string.endswith('.' + end): return string[:-len('.' + end)] + '.' + new_end return string def zip_th_tf_parameters(torch_module, tf_module, permute_torch=False): ...
11553076
from capnpy.util import extend from capnpy.enum import BaseEnum @extend(nullable) class nullable: def check(self, m): field = self.target assert field.is_group() name = m.py_field_name(field) def error(msg): raise ValueError('%s: %s' % (name, msg)) # gro...
11553108
import os import sys try: flac_dir = sys.argv[1] output_wav_dir = sys.argv[2] except IndexError: print("Need two command line parameters.") list = os.listdir(flac_dir) for sub_dir in list: if sub_dir == ".DS_Store": continue for s_sub_dir in os.listdir(os.path.join(flac_dir, sub_dir)): ...
11553148
from . import openmath as om from lxml.etree import QName openmath_ns = "http://www.openmath.org/OpenMath" omtags = { "OMOBJ": om.OMObject, "OMR": om.OMReference, "OMI": om.OMInteger, "OMF": om.OMFloat, "OMSTR": om.OMString, "OMB": om.OMBytes, "OMS": om.OMSymbol, "OMV": om.OMVariable, ...
11553171
from bilibiliuploader.bilibiliuploader import BilibiliUploader from bilibiliuploader.core import VideoPart import datetime import os import glob import json import time from moviepy.editor import * # change MD5 value def fileAppend(filename): myfile = open(filename,'a') myfile.write("###&&&&#&&&&########&&&&&"...
11553190
from collections import defaultdict import numpy as np import pandas as pd from hypothesis import given from hypothesis.extra.numpy import arrays as h_arrays from hypothesis.strategies import characters as h_char from hypothesis.strategies import floats as h_float from iglovikov_helper_functions.utils.tabular_utils i...