id
stringlengths
3
8
content
stringlengths
100
981k
1679215
import pytest import pandas as pd from matplotlib.figure import Figure from shapely.geometry import Point, LineString from plotly.graph_objs import Scattermapbox from pam.plot.plans import build_person_df, build_cmap, build_person_travel_geodataframe, build_rgb_travel_cmap, \ plot_travel_plans from pam.plot.stats ...
1679240
from setuptools import setup, find_packages with open('README.md', 'r') as fh: long_desc = fh.read() setup( name='pybbn', version='3.2.1', author='<NAME>', author_email='<EMAIL>', packages=find_packages(exclude=('*.tests', '*.tests.*', 'tests.*', 'tests')), description='Learning and Infere...
1679243
import os import numpy as np import json import random import math import argparse import params import torch import time import torch.utils.data as data from data_utils import * def worker_init(dataset, idx): print ('hello world') #dataset.file_list = [dataset.file_list[idx]] l = len(dataset.file_list) ...
1679264
from magma import wire, compile, EndCircuit from loam.boards.icestick import IceStick from mantle.lattice.ice40.PLB import SB_DFF icestick = IceStick() icestick.Clock.on() icestick.J1[0].rename('D').input().on() icestick.J3[0].rename('Q').output().on() main = icestick.main() dff = SB_DFF() wire(main.D, dff.D) wire(d...
1679287
from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from mayan.apps.rest_api.serializer_mixins import CreateOnlyFieldSerializerMixin from mayan.apps.user_management.serializers import UserSerializer from ..models.favorite_document_models import FavoriteDocument from .docum...
1679374
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' from requests import Session from zeep import Client, Settings from zeep.transports import Transport from requests.auth import AuthBase, HTTPBasicAuth from zeep import helpers from zeep.cache import Sqlit...
1679407
import cv2 from math import ceil import numpy as np def floyd_steinberg_dither(img): '''Applies the Floyd-Steinberf dithering to img, in place. img is expected to be a 8-bit grayscale image. Algorithm borrowed from wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering. ''' h, w = img.shape de...
1679447
from PyObjCTools.TestSupport import * import sys from CoreFoundation import * class TestByteOrder (TestCase): def testConstants(self): self.assertEqual(CFByteOrderUnknown , 0) self.assertEqual(CFByteOrderLittleEndian , 1) self.assertEqual(CFByteOrderBigEndian , 2) def testCurrent(sel...
1679463
from unittest import mock import pytest from h.models import Feature @pytest.mark.usefixtures("features_override", "features_pending_removal_override") class TestFeature: def test_description_returns_hardcoded_description(self): feat = Feature(name="notification") assert feat.description == "A ...
1679486
import boto3 import boto3.session import json from keydra.providers.base import BaseProvider from keydra.providers.base import exponential_backoff_retry from keydra.exceptions import DistributionException from typing import Dict, NamedTuple, Optional from keydra.exceptions import RotationException from keydra.clien...
1679487
from django.test import TestCase, Client from django.contrib.auth.models import User from datetime import datetime from server.models import Computer, Secret, Request class RequestProcess(TestCase): def test_request_passes_correct_data_to_template(self): admin = User.objects.create_superuser("admin", "<EM...
1679503
import asyncio from tracardi.service.singleton import Singleton from tracardi.service.notation.dot_accessor import DotAccessor from tracardi.process_engine.tql.parser import Parser from tracardi.process_engine.tql.transformer.expr_transformer import ExprTransformer class Condition(metaclass=Singleton): def __i...
1679536
import argparse import logging import sys import typing from pdfminer.layout import LAParams from . import __doc__, __version__, process_file from .printer import Printer from .printer.markdown import MarkdownPrinter, GroupedMarkdownPrinter from .printer.json import JsonPrinter MD_FORMAT_ARGS = ['print_filename', '...
1679620
from pyudemy import Udemy from decouple import config client_id = config('CLIENT_ID') client_secret = config('CLIENT_SECRET') udemy = Udemy(client_id, client_secret) print(udemy.courses())
1679635
import json from typing import List, NamedTuple from . import BaseObject class IDNamePair(NamedTuple): """Simple type used to help with unpacking event data""" id: str name: str class InteractiveEvent(BaseObject): response_url: str user: IDNamePair team: IDNamePair channel: IDNamePair ...
1679641
from analyzer.syntax_kind import SyntaxKind class ParenthesizedExpressionSyntax(object): def __init__(self, open_paren_token, expression, close_paren_token): self.kind = SyntaxKind.ParenthesizedExpression self.open_paren_token = open_paren_token self.expression = expression self.cl...
1679722
import unittest import urllib.parse import urllib.request import json import argparse import os parser = argparse.ArgumentParser(description="Autoscorer") parser.add_argument("filename", help="File to submit") parser.add_argument("hash", help="Hash key") args = parser.parse_args() if args.hash: hashkey = args.has...
1679724
from .registry import Registry, build_from_cfg from .flops_counter import get_model_complexity_info __all__ = ['Registry', 'build_from_cfg', 'get_model_complexity_info']
1679790
import logging import configobj # Adapted from click_config_file.configobj_provider so that we can store the # file path that the config was loaded from in order to log it later. log = logging class ConfigProvider: def __init__(self): self.file_path = None def __call__(self, file_path, cmd_name): ...
1679839
import pathlib from time import time import unittest from text_recognizer.datasets.emnist import EmnistDataset from text_recognizer.character_predictor import CharacterPredictor SUPPORT_DIRNAME = pathlib.Path(__file__).parents[0].resolve() / 'support' / 'emnist' class TestEvaluateCharacterPredictor(unittest.TestCa...
1679852
from __future__ import print_function try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages import io import codecs import os import sys import iAnnotateSV here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): enc...
1679909
from __future__ import unicode_literals from django.contrib.gis.db import models class PointField(models.Model): name = models.CharField(max_length=255) location = models.PointField(srid=4326) city = models.PointField(blank=True, null=True, srid=3857) def __unicode__(self): return self.name ...
1680063
del_items(0x8013923C) SetType(0x8013923C, "void PresOnlyTestRoutine__Fv()") del_items(0x80139264) SetType(0x80139264, "void FeInitBuffer__Fv()") del_items(0x8013928C) SetType(0x8013928C, "void FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, unsigned short Str, struct FeTable *MenuPtr, struc...
1680065
import databrewer def test_package_metadata(): assert databrewer.__author__ assert databrewer.__email__ assert databrewer.__version__
1680123
from octopus.engine.explorer import Explorer from requests.exceptions import ConnectionError as RequestsConnectionError import json EOS_DEFAULT_RPC_PORT = 8888 EOS_WALLET_RPC_PORT = 8889 class EosExplorer(Explorer): """ EOS REST RPC client class doc: https://eosio.github.io/eos/group__eosiorpc.html ...
1680151
from brownie import * import time import json import csv import math def main(): thisNetwork = network.show_active() # == Load config ======================================================================================================================= if thisNetwork == "development": acct = acc...
1680164
from model import MusicVAE from loader import load_noteseqs import numpy as np import tensorflow as tf import argparse tf.reset_default_graph() ap = argparse.ArgumentParser() ap.add_argument("-bs", "--batch_size", default=32, type=int) ap.add_argument("-s", "--save_path", default="vae/", type=str) ap.add_argument("-e...
1680172
from django.apps import AppConfig class DemandsConfig(AppConfig): name = 'demands' def ready(self): import demands.signals super(DemandsConfig, self).ready()
1680175
from unittest import TestCase import utils from mock import patch from mock import mock_open from textwrap import dedent from collections import namedtuple from argparse import Namespace class TestUtils(TestCase): @patch('builtins.exit') @patch('os.path.isfile') def test_check_for_files_file_not_existing...
1680216
from gpiozero import LED from time import sleep red = LED(21, active_high=False) # while True: red.on() print('on') sleep(30) # red.off() # print('off') # sleep(4)
1680224
import os import sys import click from ftcli.Lib.Font import Font from ftcli.Lib.utils import getFontsList, makeOutputFileName, guessFamilyName @click.group() def setLineGap(): pass @setLineGap.command() @click.argument('input_path', type=click.Path(exists=True, resolve_path=True)) @click.option('-p', '--perce...
1680231
Compare two version numbers version1 and version2. If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number ...
1680254
import unittest from copy import deepcopy import numpy as np import torch import torch.nn as nn import torchvision from code_soup.ch5 import ZooAttack class TestZooAttack(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.orig_img = torch.tensor( [ [ ...
1680267
from typing import Optional import torch as th def quantile_huber_loss( current_quantiles: th.Tensor, target_quantiles: th.Tensor, cum_prob: Optional[th.Tensor] = None, sum_over_quantiles: bool = True, ) -> th.Tensor: """ The quantile-regression loss, as described in the QR-DQN and TQC papers...
1680283
import numpy as np import scipy.stats import datetime from spodernet.interfaces import IAtIterEndObservable, IAtEpochEndObservable, IAtEpochStartObservable from spodernet.utils.util import Timer from spodernet.utils.global_config import Config, Backends from spodernet.utils.logger import Logger log = Logger('hooks.py...
1680297
import os import sys import time import numpy as np import Pyro4 import select from slam_pkg.utils.map_builder import MapBuilder as mb from slam_pkg.utils import depth_util as du from skimage.morphology import disk, binary_dilation from rich import print Pyro4.config.SERIALIZER = "pickle" Pyro4.config.SERIALIZERS_ACCE...
1680304
from keras.layers import Input, LSTM, Dense, Masking, merge, Dropout from keras.models import Model, load_model from keras.optimizers import adam from keras.utils import to_categorical import numpy as np from numpy import genfromtxt, savetxt from matplotlib import pyplot as plt data_dir = './split2/scene_activity_dat...
1680313
from django.utils.safestring import mark_safe from fluent_pages.extensions import PageTypePlugin, page_type_pool from fluent_pages.pagetypes.flatpage.models import FlatPage @page_type_pool.register class FlatPagePlugin(PageTypePlugin): model = FlatPage sort_priority = 11 def get_render_template(self, re...
1680374
import read_bvh import numpy as np from os import listdir import os def generate_traindata_from_bvh(src_bvh_folder, tar_traindata_folder): print ("Generating training data for "+ src_bvh_folder) if (os.path.exists(tar_traindata_folder)==False): os.makedirs(tar_traindata_folder) bvh_dance...
1680383
import argparse import os import pandas as pd import numpy as np from tqdm import tqdm from sklearn.model_selection import train_test_split tqdm.pandas() parser = argparse.ArgumentParser() parse.add_argument("--mimic_dir", help="The directory contaning all the required MIMIC files (ADMISSIONS, PATIENTS, DIAGNOSES_I...
1680394
from mltoolkit.mldp.steps.transformers import BaseTransformer import numpy as np class InvalidTransformer(BaseTransformer): def _transform(self, data_chunk): return np.random.random((10, 5))
1680428
from typing import Any, Dict, List, Optional, Union import pyspark import pyspark.sql.functions as F from pyspark.ml.linalg import Vectors, VectorUDT from pyspark.sql.functions import udf from pyspark.sql.types import FloatType class SLearnerEstimator: """Estimates treatment effect by training a single model for...
1680457
from __future__ import annotations import contextlib import warnings from abc import ABCMeta, abstractmethod from functools import partial as Partial from types import MethodType from typing import Any, Callable, Iterable, TypeVar import torch from torch import Tensor, nn from torch.optim import Optimizer from torch....
1680459
from unetpp import model as unetpp from unet import model as unet from tensorflow.keras.optimizers import Adam from losses import dice, iou, weighted_loss, cce_iou_dice weights_list = {1: 1.0, 2: 50.0, 3: 70.0} if __name__ == '__main__': optimizer = Adam(lr=0.0005) unet.compile(optimizer=optimizer, loss=weig...
1680518
import abc import json import logging import sys import typing import sh from kubeyard.commands.devel import BaseDevelCommand logger = logging.getLogger(__name__) class TestCommand(BaseDevelCommand): """ Runs tests in docker image built by build command. Can be overridden in <project_dir>/sripts/test. ...
1680584
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init from operations import * from torch.autograd import Variable from genotypes import PRIMITIVES import numpy as np from thop import profile from matplotlib import pyplot as plt from thop import profile from analyti...
1680591
from __future__ import annotations from typing import TYPE_CHECKING, TypeVar from qtpy.QtWidgets import QListView from ._base_item_view import _BaseEventedItemView from .qt_list_model import QtListModel if TYPE_CHECKING: from qtpy.QtWidgets import QWidget from ...utils.events.containers import SelectableEv...
1680596
import logging import math from typing import Dict import numpy as np from pyquaternion import Quaternion from paralleldomain.utilities.transformation import Transformation logger = logging.getLogger(__name__) class CoordinateSystem: _axis_char_map: Dict[str, np.ndarray] = dict( **{character: axis for ...
1680614
from autotabular.pipeline.components.base import AutotabularClassificationAlgorithm, IterativeComponentWithSampleWeight from autotabular.pipeline.constants import DENSE, PREDICTIONS, SPARSE, UNSIGNED_DATA from autotabular.pipeline.implementations.util import softmax from autotabular.util.common import check_for_bool fr...
1680674
class Solution: def arrangeCoins(self, n: int) -> int: return int ((-1 + (1 + 8*n) ** 0.5 ) / 2)
1680687
import os import pickle def save_pkl(instances, pickle_dict, is_training): if is_pickle_dict_valid(pickle_dict): os.makedirs(pickle_dict["path"], exist_ok=True) with open(get_pkl_path(pickle_dict, is_training), "wb") as dataset_file: pickle.dump(instances, dataset_file) def load_pkl(...
1680763
from cypherpunkpay.explorers.bitcoin.bitaps_explorer import BitapsExplorer from cypherpunkpay.explorers.bitcoin.bitaroo_explorer import BitarooExplorer from cypherpunkpay.explorers.bitcoin.blockstream_explorer import BlockstreamExplorer from cypherpunkpay.explorers.bitcoin.emzy_explorer import EmzyExplorer from cypherp...
1680767
def ask_for_stop(use_back): import pydevd if use_back: pydevd.settrace(stop_at_frame=sys._getframe().f_back) else: pydevd.settrace() print('Will stop here if use_back==False.') def outer_method(): ask_for_stop(True) print('will stop here.') ask_for_stop(False) if __name__...
1680811
version_info = (4, 2, 0) # pragma: no cover __version__ = '.'.join(str(v) for v in version_info) # pragma: no cover
1680826
import getpass import logging import sys from django.core.management.base import BaseCommand from django.db import transaction, IntegrityError from django.urls import reverse from django.utils.crypto import get_random_string import requests from zentral.conf import settings from zentral.contrib.okta.models import Event...
1680831
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader from torchvision import datasets, transforms import time import argparse class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.cn1 = ...
1680838
import torch import torch.nn as nn from torch.autograd import Variable from correlation_package.modules.corr import Correlation, Correlation1d from correlation_package.functions.corr import correlation, correlation1d from torch.autograd import gradcheck import numpy as np def test_correlation(): # model = correla...
1680868
from yozuch import logger from yozuch.generators.template import TemplateEntry, TemplateGenerator from yozuch.utils import format_url_from_object class PostItemCollectionGenerator(TemplateGenerator): def __init__(self, collection_name, item_name, url_template, name, template): super().__init__(url_templa...
1680892
from a10sdk.common.A10BaseClass import A10BaseClass class FailMsgCfg(A10BaseClass): """This class does not support CRUD Operations please use parent. :param fail_font_custom: {"description": "Specify custom font", "format": "string-rlx", "minLength": 1, "maxLength": 63, "not": "fail-face", "type": "stri...
1680900
import datetime import logging import re import icalendar import recurring_ical_events _LOGGER = logging.getLogger(__name__) class ICS: def __init__(self, offset=None, regex=None, split_at=None): self._offset = offset self._regex = None if regex is not None: self._regex = re....
1680928
from core.advbase import * class Yoshitsune(Adv): comment = "no counter on s1/dodge" def prerun(self): self.allow_dodge = False class Yoshitsune_COUNTER(Yoshitsune): comment = "always counter on s1/dodge" def prerun(self): super().prerun() self.conf.s1.attr = self.conf.s1.a...
1680950
from .core import StrategyList class FallbackStrategies(StrategyList): """ The StrategyList containing fallback strategies. """ NAME = "fallback" @staticmethod def strategy_override(config, path, base, nxt): """use nxt, and ignore base.""" return nxt @staticmethod de...
1680960
import time from tools.datahelp import flatten_into_set from tools.misc import list_to_hashed_dict class Page(object): data = None def __init__(self): self.data = [] def add_row(self, row): self.data.append(row) class PageFetcher(object): """ Requests pages, handles their recei...
1680970
import datetime import importlib import sys import tempfile import uuid from pathlib import Path from logexp.experiment import Experiment from logexp.metadata.git import get_git_info from logexp.logstore import LogStore from logexp.params import Params from logexp.report import Report from logexp.metadata.platform imp...
1680976
import turicreate as tc #use sframe containing all images data = tc.SFrame('Nolmyra2.sframe') train_set, test_set = data.random_split(0.8) train_set.save("Train_Data.sframe") test_set.save("Test_Data.sframe")
1680987
import torch import numpy as np import os import json default_device = torch.device(f"cuda:0" if torch.cuda.is_available() else "cpu") def test(model, iter, repeats=5, steps=50, device=default_device): res_path = os.path.join(model.model_dir, 'test_results.json') model.eval() accs = [] for _ in rang...
1681025
from demos import bisection_iter, analyze_func, generate_emails # Add domains to list below for additional email extensions list_of_domains = ['yaexample.com','goexample.com','example.com'] # Generate emails emails = generate_emails(10,list_of_domains,1000000) # Test email to add to list of emails, followed by appen...
1681034
from mapping_common import * openflow_tables = { "dmac": OFTable( match_fields = { "ethernet_dstAddr" : OFMatchField(field="OFPXMT_OFB_ETH_DST") }, id = 0 ) }
1681064
import asyncio import pytest import starkware.starknet.testing.objects from starkware.starknet.testing.starknet import Starknet from starkware.starkware_utils.error_handling import StarkException from tests.utils import Signer, str_to_felt, to_uint, uint FALSE, TRUE = 0, 1 signer = Signer(123456789987654321) NONEX...
1681091
class Shield: def __init__(self): self.s7 = 0 self.s6 = 0 self.s5 = 0 self.s4 = 0 self.s3 = 0 self.s2 = 0 self.s1 = 0 self.s0 = 0 def tick(self, inputs): depth7 = inputs[0] depth6 = inputs[1] depth5 = inputs[2] depth4 = inputs[3] depth3 = inputs[4] depth2 = ...
1681102
from django.http import JsonResponse from store.models import Product from django.shortcuts import render, redirect from cart.models import CartItem from .forms import OrderForm from .models import Order, OrderProduct, Payment import datetime from django.contrib import messages import json from django.template.loader i...
1681103
import sys, os, glob, random import time import parser import torch import torch.nn as nn # from AdaAdam import AdaAdam import torch.optim as OPT import numpy as np from copy import deepcopy from tqdm import tqdm, trange import logging from torchtext import data import DataProcessing from DataProcessing.MLTField impor...
1681110
from django.db import models from api.model.restaurant import Restaurant from django.contrib.auth.models import User class RestaurantRate(models.Model): score = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCA...
1681117
from django.test import TestCase from .models import Resource class TestResourceModels(TestCase): """Tests for Resource models.""" def setUp(self): """Sets up the model for testing""" Resource.objects.create( name='Forking', link="https://www.youtube.com/watch?v=HbSjyU...
1681196
from multiprocessing import Pool import time import numpy as np import torch import gym from lagom import Logger from lagom import EpisodeRunner from lagom.transform import describe from lagom.utils import CloudpickleWrapper from lagom.utils import pickle_dump from lagom.utils import tensorify from lagom.utils import ...
1681226
import torch from torch import nn def _conv_block(in_channel, out_channel, kernel_size, stride, padding): block = nn.Sequential( nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, stride=stride, padding=padding), nn.BatchNorm2d(out_channel), nn.LeakyReLU(0.2, True) # TODO: check ...
1681245
import unittest from pony.thirdparty.compiler.transformer import parse from pony.orm.decompiling import Decompiler from pony.orm.asttranslation import ast2src def generate_gens(): patterns = [ '(x * y) * [z * j)', '([x * y) * z) * j', '(x * [y * z)) * j', 'x * ([y * z) * j)', ...
1681264
import sys import unittest from pulsar.utils.exceptions import reraise class TestMiscellaneous(unittest.TestCase): def test_reraise(self): self.assertRaises(RuntimeError, reraise, RuntimeError, RuntimeError()) try: raise RuntimeError('bla') except Exception: exc_i...
1681271
from myapp.views import AuthorCreate, AuthorUpdate, AuthorDelete, AuthorListView, AuthorDetailView from django.conf.urls import url app_name = 'myapp' urlpatterns = [ url(r'^author/$', AuthorListView.as_view(), name='author-list'), url(r'^author/create/$', AuthorCreate.as_view(), name='author-create'), url...
1681349
import os import os.path as osp import sys import pdb import argparse import librosa import numpy as np from tqdm import tqdm import h5py from PIL import Image import subprocess from options.test_options import TestOptions import torchvision.transforms as transforms import torch import torchvision from data.stereo_data...
1681358
import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap def decision_regions(x, y, classifier, test_idx=None, resolution=0.02, plot_support=False, plot_custom_support=False): markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') ...
1681438
from tkinter import * root = Tk() root.geometry("200x200+500+300") label = Label(text=1) label.pack() entryText = StringVar() entryText.set("<NAME>") entry = Entry(textvariable=entryText) entry.pack() button = Button(command=lambda: label.configure(text=label.cget("text") + 1)) button.pack() root.mainloop()
1681443
from TikTokLive import TikTokLiveClient from TikTokLive.types.events import AbstractEvent, GiftEvent # Instantiate the client with debug param as true client: TikTokLiveClient = TikTokLiveClient(unique_id="@best.printer", debug=True) @client.on("gift") async def on_gift(event: GiftEvent): # When gifts are sent ...
1681453
import warnings from typing import Optional, Union from ansys.mapdl.core.mapdl_types import MapdlInt class Style: def cplane(self, key="", **kwargs): """Specifies the cutting plane for section and capped displays. APDL Command: /CPLANE Parameters ---------- key ...
1681548
import boto.rds from datetime import date, timedelta,datetime from dateutil.parser import parse import csv days_counter=45 region="ap-southeast-1" conn = boto.rds.connect_to_region(region) # amis=ec2conn.get_all_images(owners='self') print conn.get_all_dbsnapshots() print type(conn.get_all_dbsnapshots()) # class Am...
1681584
class Solution: def nextGreaterElement(self, n: int) -> int: n = list(str(n)) i = j = len(n) - 1 while i and n[i-1] >= n[i]: i -= 1 if not i: return -1 while n[j] <= n[i-1]: j -= 1 n[i-1], n[j] = n[j], n[i-1] n = int(''.join...
1681585
from a import burn from a import Toaster print 'In b.py, at import time:', burn print 'In b.py, at import time, Toaster:', Toaster def toast(): print 'In b.py, at runtime:', burn print 'In b.py, at runtime, Toaster:', Toaster print 'In b.py, at runtime, Toaster.burn:', Toaster.burn burn() Toaster....
1681601
from city_scrapers_core.constants import ADVISORY_COMMITTEE from city_scrapers_core.spiders import CityScrapersSpider from city_scrapers.mixins import CuyaCountyMixin class CuyaArchivesAdvisorySpider(CuyaCountyMixin, CityScrapersSpider): name = "cuya_archives_advisory" agency = "Cuyahoga County Archives Advi...
1681645
import spacy from initialize import spacy_nlp from interfaces.SentenceOperation import SentenceOperation from interfaces.SentencePairOperation import SentencePairOperation from tasks.TaskTypes import TaskType """ Auxiliary Negation Removal. Remove auxiliary negations generating a sentence with oposite meaning. ""...
1681748
import Orange data = Orange.data.Table("iris.tab") print("Dataset instances:", len(data)) subset = Orange.data.Table(data.domain, [d for d in data if d["petal length"] > 3.0]) print("Subset size:", len(subset))
1681757
from dataclasses import dataclass, field from typing import Optional @dataclass class QvaPayError(Exception): status_code: int status_message: Optional[str] = field(default=None)
1681775
import json import random import re import time from urllib.parse import quote_plus from v2ray_pool import Net import chardet import requests import urllib3 from bs4 import BeautifulSoup from my_fake_useragent import UserAgent class Keywords(Net): '''url:https://www.5118.com/ciku/index#129''' def get_keys_...
1681790
from discord.ext import commands import config class Games(commands.Cog, name="Games"): def __init__(self, bot): self.bot = bot @commands.command(name="gamesuggest", description="Suggest game ideas.") async def _gamesuggest(self, ctx): await ctx.send(f"Use the **{config.prefix}devmsg** c...
1681821
from indicnlp.tokenize import indic_detokenize indic_string='" सुनो , कुछ आवाज़ आ रही है . " , उसने कहा । ' print('Input String: {}'.format(indic_string)) print('Detokenized String: {}'.format(indic_detokenize.trivial_detokenize(indic_string,lang='hi')))
1681824
def insertion_sort(nums): # Start on the second element as we assume the first element is sorted for i in range(1, len(nums)): item_to_insert = nums[i] # And keep a reference of the index of the previous element j = i - 1 # Move all items of the sorted segment forward if they are...
1681842
import flask import requests import os from urllib.parse import urlparse, parse_qs import json app = flask.Flask(__name__) app.config["DEBUG"] = True # TODO: make production buildkite_api_token = os.getenv("BUILDKITE_API_TOKEN", "") @app.route('/', methods=['GET']) def home(): return "Hi LLVM!" @app.route('/bu...
1681866
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def norm_col_init(weights, std=1.0): x = torch.randn(weights.size()) x *= std / torch.sqrt((x**2).sum(1, keepdim=True)) return x def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') !=...
1681917
from BaseComponents.Buttons import Button from SettingComponents.Layouts.ScrollArea import ScrollArea def get_arearect(settings): area_width = settings.default_width area_height = settings.default_height middle_x = settings.default_x + settings.default_width/2 middle_y = settings.default_y + settings.default_hei...
1681924
import argparse from util.torch_util import str_to_bool class ArgumentParser(): def __init__(self,mode='train'): self.parser = argparse.ArgumentParser(description='CNNGeometric PyTorch implementation') self.add_cnn_model_parameters() if mode=='train': self.add_train_par...
1681935
import json import logging import splunk.admin as admin import splunk.rest as rest import log_helper # Setup the handler logger = log_helper.setup(logging.INFO, 'BaseEAIHandler', 'base_handler.log') class BaseEAIHandler(admin.MConfigHandler): def get_param(self, param, default=None): """ Returns v...