text
stringlengths
2
999k
# -*- coding: utf-8 -*- import staticconf import sphinx_rtd_theme # -- General configuration ----------------------------------------------------- extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', ] templates_path = ['...
import json, subprocess, os from enum import Enum class Medium: """ Stores metadata for movie and audio files. """ class Type(Enum): AUDIO = 1 VIDEO = 2 def __init__(self, type): """ :param type: Type of the medium, see the Type enum. """ self.raw_json = None ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path import os import shlex from subprocess import Popen from generic_config import (central_node_name, prefix_client_node) from misp_instances import MISPInstances root_misps = Path('misps') # Start all the instances cur_dir = os.getcwd() os.chdir(r...
from package import redact_ex from package import dkf EXERCISE_01 = """\ Make a program that is able to compute the numerical k-order derivative of a given function using the method of undetermined coefficients. Apply that to the case f(x) = x**3 - 3*x**2 - x + 3 on x0 = 1.2.\ """ redact_ex(EXERCISE_01, 1) def f(...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
import random from couchbase.bucket import Bucket class TestDataset: def __init__(self): self.limit = 2000 def _shuffle_and_cut(self, fpath, limit=500): f = open(fpath) l = list(f) random.shuffle(l) l = l[:limit] f.close() return l def combine_2(s...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Popularity Contest (popcontest) parser.""" import unittest from plaso.lib import definitions from plaso.parsers import popcontest from tests.parsers import test_lib class PopularityContestUnitTest(test_lib.ParserTestCase): """Tests for the popcontes...
from backend.common_tile import CommonTile class SolarFarm(CommonTile): def __init__(self): super().__init__() self.production = 1 self.gold = 1 self.power = 2 self.acceptable_terrain = [ 'grassland', 'plains', 'tundra', 'des...
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import os import unittest import numpy as np from pymatgen.analysis.defects.core import DefectEntry, Vacancy from pymatgen.analysis.defects.corrections import ( BandEdgeShiftingCorrection, BandFillingCorrection, ...
import os from nltk import word_tokenize as WT from nltk import pos_tag import sqlite3 # Only backlash: Name of the person must appear before job description file = open("temp.txt", "r") content = file.read().strip() file.close() os.remove("temp.txt") tempList = list(content) tempList[0] = tempList[0].lower() con...
import csv import logging import os from typing import Any, Dict, List, Tuple, Union from rotkehlchen.assets.asset import Asset from rotkehlchen.constants import ( EV_ASSET_MOVE, EV_BUY, EV_INTEREST_PAYMENT, EV_LOAN_SETTLE, EV_MARGIN_CLOSE, EV_SELL, EV_TX_GAS_COST, S_EMPTYSTR, ZERO,...
#!/usr/bin/env python2.7 # Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
import dsl from . import FixtureTest class EarlyFootway(FixtureTest): def test_footway_unnamed_national(self): # highway=footway, no name, route national (Pacific Crest Trail) self.generate_fixtures( dsl.way(83076573, dsl.tile_diagonal(14, 2760, 6326), { 'source': 'op...
class Solution: """ @param: A: An integer array. @return: nothing """ def rerange(self, A): # write your code here k = 0 for i in range(len(A)): if A[i] < 0: A[i], A[k] = A[k], A[i] k += 1 neg_count...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
n =int(input()) print(2**((n+1)//2)% 16769023)
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Style for IPython Console """ # Local imports from spyder.config.gui import get_color_scheme # Third party imports from pygments.style import Style from pygment...
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('scores.db') print("[Database] Opened scores.db") conn.execute('''CREATE TABLE SCORES (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, SCORE INT NOT NULL);''') print("[Database] Created tables") conn.close()...
# os import sys, os, time, logging # CPU DS stack import pandas as pd import numpy as np import sklearn # GPU DS stack [ rapids ] import gcsfs # scaling library import dask # data ingestion [ CPU ] from pyarrow import orc as pyarrow_orc # ML models from sklearn import ensemble import xgboost # data set splits fro...
import contextlib import ir_measures from ir_measures import providers, measures, Metric from ir_measures.providers.base import Any, Choices, NOT_PROVIDED from ir_measures.bin import msmarco_eval import sys class MsMarcoProvider(providers.Provider): """ MS MARCO's implementation of RR """ NAME = 'msmar...
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python # coding: utf-8 # # Self-Driving Car Engineer Nanodegree # # # ## Project: **Finding Lane Lines on the Road** # *** # In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and...
import sys sys.path.append('../G26/Reportes') from graphviz import Graph class Grafo(): def __init__(self, index): self.index = index self.dot = Graph() self.dot.attr(splines='false') self.dot.node_attr.update(shape = 'circle') self.dot.edge_attr.update(color = 'blue4') ...
#!/usr/bin/env python import os, shutil import sys import subprocess import yaml from copy import deepcopy import time estims = [('dem','dem_vvs', 'dem_lm'),('p4p',),('upnp','upnp_vvs','upnp_lm')] exp_dir = 'rose_noNoise' trans_error = 'te.yaml' pose_gt = 'cMs.yaml' pose_raw = 'iMs.yaml' pose_final = 'ceMs.yaml' def...
""" load dataset """ import torch from torch.utils.data import DataLoader from .build import build_dataset def construct_loader(mode,cfg,): """ consturct data loader :param cfg: :param mode: :return: """ assert mode in ["train","test","update_epoch"] if mode in ["train"]: dat...
from django.core import serializers from django.core.management.base import BaseCommand, CommandError from django.conf import settings from vendors.models import Vendor from contract.models import Contract class Command(BaseCommand): def handle(self, *args, **kwargs): vendors = Vendor.objects.filter(duns_...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Application Compatibility Cache key Windows Registry plugin.""" from __future__ import unicode_literals import unittest from dfdatetime import filetime as dfdatetime_filetime from dfvfs.path import fake_path_spec from dfwinreg import definitions as dfwin...
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest class AppTestFlagsObj(BaseNumpyAppTest): def test_init(self): import numpy as np a = np.array([1,2,3]) assert a.flags['C'] is True b = type(a.flags)() assert b is not a.flags assert b['C'] is True ...
#!/usr/bin/env python import urllib import xml.etree.cElementTree as ET import os import sys if len(sys.argv) < 2: print("Usage: site-index.py $output-file [[ROOT] K]") sys.exit(-1) OUTFILE = sys.argv[1] if len(sys.argv) > 2: ROOT = sys.argv[2] else: ROOT="/x1/mail-archives/mod_mbox" # allow for blanks at ...
from dataclasses import dataclass @dataclass class Command: pass
from sympy import symbols, sin, cos from sympy.polys import QQ, ZZ from sympy.polys.polytools import Poly from sympy.polys.polyerrors import NotInvertible from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.domainmatrix import DomainMatrix from sympy.testing.pytest import raises from sympy.abc im...
""" 1572. Matrix Diagonal Sum https://leetcode.com/problems/matrix-diagonal-sum/ Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example: Input...
from .sampling import *
from .ProblemDC import Problem3D_CC, Problem3D_N, BaseDCProblem from .ProblemDC_2D import Problem2D_CC, Problem2D_N from .SurveyDC import Survey, Survey_ky from . import SrcDC as Src # Pole from . import RxDC as Rx from .FieldsDC import FieldsDC, Fields_CC, Fields_N from .FieldsDC_2D import Fields_ky, Fields_ky_CC, Fi...
#!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # # Copyright (c) 2018 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # from sm_client.common import base class SmcNode(base.Resource): def __repr__(self): return "<SmcNode %s>" % self._info class SmcNodeManager(base...
from django.apps import AppConfig class ChatConfig(AppConfig): """Config for chat django application""" name = "chat"
import csv from re import sub class FormatColumns: _colors: dict = {} def format(self, data: str, colors: list=[]) -> str: data = self.__remove_blank_lines(data) table = [list(map(str.strip, row.split('\t'))) for row in data.strip().split("\n")] max_column_lengths = [max(len(str(cell))...
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
""" Add column to metadata to denote 'focal' samples based on supplied region Rewrite location, division and country for non-focal samples to be region Rewrite division_exposure and country_exposure for non-focal samples to be region_exposure """ import argparse import pandas as pd if __name__ == '__main__':...
_base_ = ['../singan/singan_balloons.py'] model = dict( type='PESinGAN', generator=dict( type='SinGANMSGeneratorPE', interp_pad=True, noise_with_pad=True)) train_cfg = dict(fixed_noise_with_pad=True) dist_params = dict(backend='nccl', port=23019)
# -*- coding: utf-8 -*- """ This module """ import attr import typing from ..core.model import ( Property, Resource, Tag, GetAtt, TypeHint, TypeCheck, ) from ..core.constant import AttrMeta #--- Property declaration --- @attr.s class PropMulticastGroupLoRaWAN(Property): """ AWS Object Type = "AWS::IoTW...
import argparse from abc import ( ABC, abstractmethod, ) class ParseArgs(ABC): @abstractmethod def __call__(self, args: argparse.Namespace): ...
""" VoteNow development configuration """ # Root of this application, useful if it doesn't occupy an entire domain APPLICATION_ROOT = '/'
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. """Unit test class for RigAnalyzer. This class subclasses the DepTest class, which provides some utility fun...
# Copyright 2019 École Polytechnique # # Authorship # Luciano Di Palma <luciano.di-palma@polytechnique.edu> # Enhui Huang <enhui.huang@polytechnique.edu> # Le Ha Vy Nguyen <nguyenlehavy@gmail.com> # Laurent Cetinsoy <laurent.cetinsoy@gmail.com> # # Disclaimer # THE SOFTWARE IS PROVIDED "AS IS", WITHOU...
from tetrimino import * class Tetrimino_L( Tetrimino ): # TASK 1: # # Constructor function of Tetrimino_L. # This function sets self.coordinates with the initial values. # # If self.tetris_window.num_blocks_x is odd: # The tetrimino should be perfectly in the center column # Else: ...
import numpy as np import visgeom as vg import matplotlib import matplotlib.pyplot as plt import scipy.linalg from pylie import SO3, SE3 from optim import gauss_newton """Example 2 - MAP estimation""" class NoisyPointAlignmentBasedPoseEstimatorObjective: """Implements linearisation of the covariance weighted obj...
from abc import ABC, abstractmethod from bs4 import BeautifulSoup import requests import scriptures from html2text import html2text import re class BibleSource(ABC): @abstractmethod def get_text(self): pass @abstractmethod def get_html(self): pass @abstractmethod def get_head...
from datetime import datetime from django.core import mail from django.core.mail import EmailMessage from src.rooms.models import Donation, Room def send_email(data): message = EmailMessage(data['subject'], data['message'], to=data['to']) return message.send() def send_mass_email(email_message_list): ...
# -*- coding:utf-8 -*- ''' # ========================= # YouCompeleteMe 配置文件 # 位置: ~/.ycm_extra_conf.py # 备注: 由newycm_extra_conf.py 生成 # https://github.com/robturtle/newycm_extra_conf.py ''' # This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license ...
""" The main DBM class """ __authors__ = ["Ian Goodfellow", "Vincent Dumoulin"] __copyright__ = "Copyright 2012-2013, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" import functools import logging import operator import numpy as np from theano.compat....
from typing import List, Dict from pyhcl.ir.low_ir import * from pyhcl.ir.low_prim import * from pyhcl.passes._pass import Pass @dataclass class Optimize(Pass): def run(self, c: Circuit): def get_name(e: Expression) -> str: if isinstance(e, (SubField, SubIndex, SubAccess)): retu...
import pytest def test_simple_unittest(testdir): testpath = testdir.makepyfile(""" import unittest class MyTestCase(unittest.TestCase): def testpassing(self): self.assertEquals('foo', 'foo') def test_failing(self): self.assertEquals('foo', 'ba...
""" Prompt: Given a non-negative number, N, return the last digit of the factorial of N. The factorial of N, which is written as N!, is defined as the product of all of the integers from 1 to N. Given 3 as N, the factorial is 1 x 2 x 3 = 6 Given 6 as N, the factorial is 1 x 2 x 3 x 4 x 5 x 6 = 720 Given 9 as N, the...
"""Tests for anonapi.cli.select_commands""" from functools import partialmethod from pathlib import Path from tqdm import tqdm import pytest from fileselection.fileselection import FileSelectionFolder, FileSelectionFile from anonapi.cli.select_commands import main, SelectCommandContext, CLIMessages from anonapi.select...
import csv, collections import pandas as pd import numpy as np import nltk import sys pos = pd.read_csv('positive.gz',sep=',',header=0) neg = pd.read_csv('negative.gz',sep=',',header=0) pos_text = pos['Summary'] + " " + pos['Text'] neg_text = neg['Summary'] + " " + neg['Text'] def load_sentiwordnet(): print 'loa...
import os import shutil import sys import tempfile import threading import time import unittest from datetime import datetime, timedelta from io import StringIO from pathlib import Path from urllib.request import urlopen from django.core.cache import cache from django.core.exceptions import SuspiciousFileOperation fro...
def topological_sort(propagation_end_node): """A utility function to perform a topological sort on a DAG starting from the node to perform backpropagation. Parameters ---------- propagation_end_node : Node The node to perform backpropagation. Returns ------- List[Node] ...
from typing import List, TYPE_CHECKING from .bulk_update_cost_center_input_params import BulkUpdateCostCenterInputParams from travelperk_python_api_types.cost_centers.cost_centers.bulk_update_response import ( BulkUpdateResponse, ) from travelperk_http_python.dataclass_wrapper.dataclass_wrapper import DataclassWrap...
from __future__ import absolute_import, division, print_function, unicode_literals import unittest import requests_mock import warnings from canvasapi.canvas import Canvas from canvasapi.course import Course from canvasapi.group import Group from canvasapi.page import Page, PageRevision from tests import settings fro...
""" WSGI config for project_app_v1_31865 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault(...
import os import tarfile import tempfile import logging import importlib from distutils import dir_util import yaml import ulid from h1st.model_repository.storage.s3 import S3Storage from h1st.model_repository.storage.local import LocalStorage SEP = "::" logger = logging.getLogger(__name__) class ModelSerDe: S...
# Copyright 2020 CRS4 (http://www.crs4.it/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
# # Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
def sum_irregular(data): """ Sums all elements in passed sequence. Sequence can contain plain numbers as well as other sequences with numbers >>> sum_irregular([3, 6, 9]) 18 >>> sum_irregular([3, [6, 9]]) 18 >>> sum_irregular([3, [6, [9]]]) 18 >>> sum_irregular(range(10)) 45...
""" System wide credentials functionality These modules accepts user credentials on first use. Depending on your os the credentials are stored in the proper credentials directory and encrypted with the users native os password encryption algorithm. This script requires that `keyring` be installed within the Python en...
# # Copyright (c) 2013, Battelle Memorial Institute # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list o...
from evennia.utils.utils import class_from_module from evennia.utils.logger import log_trace import athanor.messages.themes as tmsg from athanor.gamedb.scripts import AthanorGlobalScript from athanor.utils.text import partial_match from athanor.gamedb.models import ThemeBridge from athanor.gamedb.themes import Athanor...
from django.db import models, transaction from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Group from django.utils.functional import cached_property __all__ = ['Dataset'] class DatasetManager(models.Manager): '''Manager that optimize the queries by selecting the forei...
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
import eventlet from eventlet.hubs import get_hub from eventlet.queue import _NONE, Empty, Queue, Waiter class PeekableQueue(Queue): def get(self, *args, **kwargs): """ Return and remove the first item from the queue. """ return self.__call_when_item_available(self._get, *args, **k...
__author__ = 'Martijn Berger' import OpenGL.GL as gl import numpy as np import ctypes import glfw NULL = ctypes.c_void_p(0) vertex_data = np.array([-1,-1, -1,+1, +1,-1, +1,+1 ], dtype=np.float32) color_data = np.array([1,0,0,1, 0,1,0,1, 0,0,1,1, 1,1,0,1], dtype=np.float32) def main(): # Initialize the library...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2020, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above...
# -*- coding: utf-8 -*- import datetime def add_gigasecond(birthdate): return birthdate + datetime.timedelta(seconds=10**9)
#!/usr/bin/env python # encoding: utf-8 from __future__ import print_function from collections import namedtuple from simplesqlite import SimpleSQLite table_name = "sample_table" con = SimpleSQLite("sample.sqlite", "w") con.create_table_from_data_matrix( table_name, ["attr_a", "attr_b", "attr_c", "attr_d", "at...
def extractNoorcnWordpressCom(item): ''' Parser for 'noorcn.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('The Ming Dynasty\'s Prodigal Son', 'The Ming Dynasty\'s Prodigal ...
from datetime import timedelta import operator from sys import getsizeof from typing import Optional, Union import warnings import numpy as np from pandas._libs import index as libindex import pandas.compat as compat from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, cache_re...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np from sklearn import linear_model from sklearn import metrics import sys if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO # In[2]: DATA="""Timestamp, ID, Temperature(celsius), Targ...
from distutils.core import setup setup( name = 'pyodin', packages = ['pyodin'], version = '0.2.0', license='MIT', description = 'A python package for gathering information in odin jobs', url = 'https://github.com/theycallmemac/odin/', author = 'James McDermott', author_email = 'james.mcdermott7@mail.dcu...
import argparse, sys from svtools.bedpe import Bedpe from svtools.cluster import Cluster import svtools.utils as su class Pruner(object): def __init__(self, max_distance, eval_param): self.max_distance = max_distance self.eval_param = eval_param self.min_cluster_size = 1 self.bedpe_...
from typing import List from django.shortcuts import get_object_or_404 from django.urls.base import resolve from ninja import Router from character_api import models from character_api.schemas import CharacterOut, CharacterIn from ninja.security import django_auth character_router = Router() # Api to get list of all...
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
r""" Custom PDE class: SIR model =========================== This example implements a `spatially coupled SIR model <https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology>`_ with the following dynamics for the density of susceptible, infected, and recovered individuals: .. math:: \partial_t s &= D...
import os import seaborn as sns import pandas as pd from dplypy.dplyframe import * from dplypy.pipeline import * def test_pipeline(): df = DplyFrame(sns.load_dataset("titanic")) test_df_1 = df + head(5) test_df_2 = df + tail(5) test_df_3 = DplyFrame( test_df_1.pandas_df.loc[:, ["survived", ...
from manticore.ethereum import ManticoreEVM, Plugin from manticore.core.smtlib import solver from manticore.core.smtlib.visitors import arithmetic_simplifier, pretty_print, constant_folder ################ Script ####################### m = ManticoreEVM() m.verbosity(0) #And now make the contract account to analyze # ...
# Time: O(n) # Space: O(1) # 413 # A sequence of number is called arithmetic if it consists of at least three elements # and if the difference between any two consecutive elements is the same. # # For example, these are arithmetic sequence: # # 1, 3, 5, 7, 9 # 7, 7, 7, 7 # 3, -1, -5, -9 # The following sequence is no...
# Generated by Django 3.1.6 on 2021-02-22 12:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authapp', '0007_auto_20210222_1556'), ('travelapp', '0017_auto_20210222_1249'), ('ordersapp', '0006_auto_20210222_1550'), ] operatio...
# -*- coding: utf-8 -*- # # Imagine documentation build configuration file, created by # sphinx-quickstart on Wed Apr 6 00:20:22 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
import json import os from tqdm import tqdm from transformers.tokenization_roberta import RobertaTokenizer HEAD_TOKEN = "[HEAD]" TAIL_TOKEN = "[TAIL]" class InputExample(object): def __init__(self, id_, text, span_a, span_b, type_a, type_b, label): self.id = id_ self.text = text self.spa...
import unittest from models.monitors.mock import MockEvent from models.monitors.pagination import paginate, PAGE_SIZE from commands.poll.poller import Poller, DEFAULT_RETRY_COUNT import requests class MockPaginator: def __init__(self): self.offset = 1 def poll_func(self): events = [] ...
""" Handling for the tags from calendar events. """ import pandas as pd def explode(df, min_support_count=None): """ Given a dataframe with a tags column that contains an iterable of tags, creates a new dataframe containing the (sparse) binary columns for each tag. The index is the same. Also, g...
import pytest from birgitta.dataframesource.sources.localsource import LocalSource from birgitta.recipetest.localtest import assertion from tests.datasets import fixtures_schema @pytest.fixture() def dataframe_source(tmpdir): return LocalSource(dataset_dir=tmpdir.strpath) @pytest.fixture() def fixtures_data(): ...
from nltk import ngrams from unidecode import unidecode def jc_similarity(title1, title2, n=3, boolean=False, threshold=0.8): ''' Computes titles similarity according to section 2.6 of https://arxiv.org/pdf/1911.02782.pdf Parameters ---------- title1 : str text to compare title2 :...
""" Copyright (c) 2020, Battelle Memorial Institute All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions a...
from typing import Any, List, Optional from django.db import models, transaction from django.utils import timezone from posthog.models.utils import UUIDT class PersonManager(models.Manager): def create(self, *args: Any, **kwargs: Any): with transaction.atomic(): if not kwargs.get("distinct_i...
#!python # coding=utf-8 # Profile from .profile.im import IncompleteMultidimensionalProfile from .profile.om import OrthogonalMultidimensionalProfile # Trajectory from .trajectory.cr import ContiguousRaggedTrajectory from .trajectory.ir import IndexedRaggedTrajectory from .trajectory.im import IncompleteMultidimensio...
from proso.rand import roulette import abc import random class Strategy(metaclass=abc.ABCMeta): @abc.abstractmethod def assign_setups(self, user_id, setups_by_experiment): pass class RandomStrategy(Strategy): def assign_setups(self, user_id, setups_by_experiment): random.seed(user_id) ...
#!/usr/bin/env python import RPi.GPIO as GPIO import time LED1 = 25 SW1 = 24 def my_callback(channel): global ledState if channel == SW1: ledState = not ledState if ledState == GPIO.HIGH: GPIO.output(LED1, GPIO.HIGH) else: GPIO.output(LED1, GPIO.LOW) GPIO.setmode(GPIO.BCM) GPIO.setup(L...