text
stringlengths
1
927k
import re def is_number(s): try: float(s) if "." in s else int(s) return True except ValueError: return False def load_stop_words(stop_word_file, regex): with open(stop_word_file, "r") as stop_word_file: stop_words = re.split(regex, stop_word_file.read()) return [ ...
#!/usr/bin/env python3 # coding: utf-8 """The game logic. This should be independent of media used to interact with player.""" from typing import Tuple, List, Set, Dict from const import PLAYER_SHIFT, LAST_ON_PATH, END_PROGRESS from piece import Piece from player import Player from util import progress_to_positio...
from bokeh.plotting import output_notebook, figure, ColumnDataSource, show from bokeh.io import push_notebook from timeit import default_timer import math from collections import deque class CostVisCallback(object): """ Callback providing a live updating console based progress bar. """ def __init__(se...
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..preprocess import DWIBiasCorrect def test_DWIBiasCorrect_inputs(): input_map = dict( args=dict(argstr='%s', ), bias=dict( argstr='-bias %s', extensions=None, ), ...
from src.base.test_cases import TestCases from src.utility.constants import INSERT, REMOVE, GET_RANDOM class InsDelRandConstTestCases(TestCases): def __init__(self): super(InsDelRandConstTestCases, self).__init__() self.__add_test_case__('Test Insert 1', (INSERT, 1), True) self.__add_test_...
# -*- coding: utf-8 -*- """ Copyright 2019 eBay 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 to in...
""" An extension to retry failed requests that are potentially caused by temporary problems such as a connection timeout or HTTP 500 error. You can change the behaviour of this middleware by modifing the scraping settings: RETRY_TIMES - how many times to retry a failed page RETRY_HTTP_CODES - which HTTP response codes...
# -*- coding: utf-8 -*- """Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal...
from ast import literal_eval import copy from importlib import import_module import json import numpy as np import pandas as pd from sklearn.pipeline import Pipeline from typhon.utils import to_array __all__ = [ 'RetrievalProduct', ] class NotTrainedError(Exception): """Should be raised if someone runs a no...
import os import random from . import imager, conf, animator from .qt import BaseDialog, QtWidgets, QtCore, QtGui class MainWidget(BaseDialog): CELL_SELECTED_SIGNAL = QtCore.Signal(tuple) CELL_FLAGGED_SIGNAL = QtCore.Signal(tuple) NEW_GAME_SIGNAL = QtCore.Signal(tuple) def __init__(self, parent=Non...
# Lint as: python3 # Copyright 2020 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 ag...
import os import pytest import re import subprocess import time from afdko.fdkutils import ( get_temp_file_path, get_temp_dir_path, ) from test_utils import ( get_input_path, get_bad_input_path, get_expected_path, generate_ps_dump, ) from runner import main as runner from differ import main as ...
#!/usr/bin/env python3 # 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 in writing, softwar...
from __future__ import absolute_import, unicode_literals from case import Mock from kombu.exceptions import HttpError class test_HttpError: def test_str(self): assert str(HttpError(200, 'msg', Mock(name='response')))
"""Configure package.""" import os from setuptools import setup, find_packages # ----------------------------------------------------------------------------- # For information on this file, see: # https://packaging.python.org/distributing/#setup-args # # For examples, look here: # https://gitlab.pixsystem.net/groups/...
# # 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...
import commonExample import math import sys sys.path.insert(0,'..') import generate import constants from numpy import random import intersection from PIL import Image, ImageDraw, ImageFont gif_file="example7" xcoords = [constants.width,constants.width,constants.width,100,400,700,1000,1300] ycoords = [50,350,700,con...
from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="markdowndocs", version="0.1.0", author="ngoet", author_email="ndgoet@gmail.com", description="A light-weight markdown code documentation generator", install_requires=[ ...
import pytest from array import array from game_map import GameMap from tests.conftest import get_relative_path sample_map_data = tuple( reversed( ( array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)), array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0...
from typing import NamedTuple import aiohttp as _aiohttp Number = int | float class ShortLong(NamedTuple): """Represents shorthand and longhand of a unit.""" short: str """Shorthand form, eg '°C'""" long: str """Longhandform, eg 'Celsius'""" class _AutomaticClient: client: _aiohttp.Client...
# -*- coding: utf-8 -*- """ Import Modules Configure the Database Instantiate Classes """ if settings.get_L10n_languages_readonly(): # Make the Language files read-only for improved performance T.is_writable = False get_vars = request.get_vars # Are we running in debug mode? settings.check_debug...
#!/usr/bin/env python # # Azure Linux extension # # Copyright (c) Microsoft Corporation # All rights reserved. # MIT License # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the ""Software""), to deal in the Software without restrictio...
import unittest import pebble from libpebble2.protocol import AppMessageACK, AppMessageNACK from mock import Mock, patch, MagicMock from libpebble2.services.appmessage import AppMessageService from libpebble2.communication.transports import BaseTransport from libpebble2.communication.transports.serial import Seri...
import os import pandas as pd from matplotlib import pyplot as plt import rclpy import numpy as np from rclpy.node import Node from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from std_srvs.srv import Empty from logger.utils import convert_ros2_time_to_float from logger.create_graphs import build...
import os import re import sys import copy import logging import warnings import subprocess import shutil import uuid import tempfile import asyncio from collections import OrderedDict from pprint import pformat from yggdrasil import platform, tools, languages, multitasking, constants from yggdrasil.components import i...
# 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 in writing, software # distributed under the...
import datetime import itertools import sqlalchemy as sa from sqlalchemy import Boolean from sqlalchemy import cast from sqlalchemy import DateTime from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import literal from sqlalchemy impo...
# -*- coding: utf-8 -*- # # Copyright (c) 2020, Honda Research Institute Europe GmbH. # 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 abo...
from django.apps import AppConfig class FilestorageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'filestorage'
# -*- coding: utf-8 -*- import unittest.mock import pytest import pycamunda.task from tests.mock import raise_requests_exception_mock, not_ok_response_mock def test_claim_params(engine_url): claim_task = pycamunda.task.Claim(url=engine_url, id_='anId', user_id='anUserId') assert claim_task.url == engine_u...
import math import re from typing import Dict, List import numpy as np from ..physical_constants import constants def distance_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray: """Euclidean distance matrix between rows of arrays `a` and `b`. Equivalent to `scipy.spatial.distance.cdist(a, b, 'euclidean')`....
# Copyright (c) OpenMMLab. All rights reserved. import argparse from collections import OrderedDict import paddle def convert_stem(model_key, model_weight, state_dict, converted_names): new_key = model_key.replace('stem.conv', 'conv1') new_key = new_key.replace('stem.bn', 'bn1') state_dict[new_key] = mod...
from py_mplus.objects import MPObject LANGUAGES = ['ENGLISH', 'SPANISH'] class Title(MPObject): def _decode(self, buffer, category, skip): if category == 1: self.title_id = buffer.uint32() elif category == 2: self.name = buffer.string() elif category == 3: ...
from .montecarlo import generate_move_montecarlo as generate_move
"""Zhang Gradient Projection Debiasing Baseline Model.""" from __future__ import annotations from typing import NamedTuple, cast import ethicml as em from kit import implements from kit.torch import CrossEntropyLoss, TrainingMode import pandas as pd import pytorch_lightning as pl from pytorch_lightning.utilities.types...
#!/usr/bin/env python import sys, rospy, tf, moveit_commander, random from geometry_msgs.msg import Pose, Point, Quaternion import pgn class R2ChessboardPGN: def __init__(self): self.left_arm = moveit_commander.MoveGroupCommander("left_arm") self.left_hand = moveit_commander.MoveGroupCommander("left_hand") ...
import tkinter as tk class MyEntry: def __init__(self, root, **kwargs): self.root = root self.value = None self.frame = tk.Frame(self.root) self.frame.pack(anchor="nw") self.kwargs = kwargs self.title_label = tk.Label(self.frame, text=self.parse_title(), anchor='w...
import pandas as pd from zipfile import ZipFile import numpy as np import re import os def year_identifier(file_name): ''' Abstrait: identify the year of the file ''' folder_regex = re.compile(r'20\d\d') match = folder_regex.search(str(file_name)) year = match.group() return year def d...
# -*- coding: utf-8 -*- """ Python FAT filesystem module with :doc:`PyFilesystem2 <pyfilesystem2:index>` \ compatibility. pyfatfs allows interaction with FAT12/16/32 filesystems, either via :doc:`PyFilesystem2 <pyfilesystem2:index>` for file-level abstraction or direct interaction with the filesystem for low-level ac...
#------------------------------------------------------------------------------ # Copyright (c) 2010, Kurt W. Smith # All rights reserved. See LICENSE.txt. #------------------------------------------------------------------------------ #!/usr/bin/env python # encoding: utf-8 import os import sys __all__ = []
from django.urls import path from . import views urlpatterns = [ path('', views.contact_page, name='contact'), ]
import enum class OutputArch(enum.Enum): """Machine architecture""" X86_64 = enum.auto() I386 = enum.auto() NONE = enum.auto() def to_string(self) -> str: if self == OutputArch.X86_64: return "i386:x86-64" elif self == OutputArch.I386: return "i386" ...
from __future__ import absolute_import, unicode_literals from future.builtins import chr, int, str try: from html.parser import HTMLParser, HTMLParseError from html.entities import name2codepoint except ImportError: # Python 2 from HTMLParser import HTMLParser, HTMLParseError from htmlentitydefs impor...
""" package.text2story.core.annotator META-annotator """ from text2story.annotators import ACTOR_EXTRACTION_TOOLS, TIME_EXTRACTION_TOOLS, OBJECTAL_LINKS_RESOLUTION_TOOLS from text2story.annotators import EVENT_EXTRACTION_TOOLS, SEMANTIC_ROLE_LABELLING_TOOLS from text2story.annotators import extract_actors, extract_...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
""" 正規表現のサンプルです。 最長一致と最短一致について """ import re from trypython.common.commoncls import SampleBase from trypython.stdlib.re_ import util class Sample(SampleBase): def exec(self): # --------------------------------------------- # 正規表現 (最長一致と最短一致) # # 正規表現はデフォルトで閉包を表すメタキャラクタ「*」は ...
from collections import Counter S=Counter(input()) T=Counter(input()) s=S.values() t=T.values() print("Yes" if sorted(s)==sorted(t) else "No")
### functions for reading from and writing to input files def read_books(books_file='data/input/books.txt'): # reads the file containing the books # ('books.txt' by default) # and returns the list of tuples: # [(author, title), ...] books = [] try: with open(books_file) as file: ...
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class FCoEGIET(Base): __slots__ = () _SDM_NAME = 'fCoEGIET' _SDM_ATT_MAP = { 'FcoeHeaderVersion': 'fCoEGIET.header.fcoeHeader.version-1', 'FcoeHeaderReserved': 'fCoEGIET.header.fcoeHeader.reserved-2', '...
#!/usr/bin/python # Copyright 2012. Jurko Gospodnetic # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE.txt or copy at # https://www.bfgroup.xyz/b2/LICENSE.txt) # Tests that variables in actions get expanded but double quote characters # get treated as regular characters ...
import setuptools import os # Conditionally include additional modules for docs on_rtd = os.environ.get('READTHEDOCS', None) == 'True' requirements = list() if on_rtd: requirements.append('gevent') requirements.append('tornado') requirements.append('twisted') long_description = ('Pika is a pure-Python imp...
# Copyright (c) 2021 Advanced Micro Devices, Inc. # All rights reserved. # # For use for simulation and test purposes only # # 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 retai...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
import numpy as np import matplotlib.pyplot as plt x = np.arange(1, 6) y = 3 * x + 2 print(x) print(y) # 시각화 plt.plot(x, y) plt.title('y = 3x + 2') plt.show()
# ----------------------------------------------------------------------------- # Functions for parsing args # ----------------------------------------------------------------------------- import yaml import os from ast import literal_eval import copy class CfgNode(dict): """ CfgNode represents an internal no...
#!/usr/bin/python # coding=UTF-8 # -*- coding: UTF-8 -*- # This file is part of the StructureMapper algorithm. # Please cite the authors if you find this software useful # # https://academic.oup.com/bioinformatics/advance-article/doi/10.1093/bioinformatics/bty086/4857361 # MIT License # # Copyright 2018 Anssi Nurmin...
class Order(): def __init__(self, pair, direction, amount, price): if direction.upper() not in ['BUY', 'SELL']: raise ValueError("{} is not a valid direction".format(direction)) self.pair = pair self.direction = direction self.amount = float(amount) self.price = f...
import os from argparse import ArgumentParser import paddle def main(): parser = ArgumentParser() parser.add_argument( '--model_dir', help='the directory where checkpoints are saved',default="output/swa_test") parser.add_argument( '--starting_model_id', default=0, type=int...
# # PySNMP MIB module COSINE-GLOBAL-REG (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COSINE-GLOBAL-REG # Produced by pysmi-0.3.4 at Wed May 1 12:27:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
# -*- coding: utf-8 -*- import os import arrow from django.core.management.base import BaseCommand from printto.models import UploadedFileModel class Command(BaseCommand): help = 'Clean all printed docs after 3 minutes' def handle(self, *args, **options): now_time = arrow.now() now_time = no...
#Linear Module to use with ZeRO Stage 3 to allow for parameter memory release #after the module execution during forward #Instead of saving variables using save_for_backward, we save variable ids #Allowing us to retrieve the variable without creating pointer to it #Which allows for underlying tensor to be garbage colle...
from openforcefield.typing.engines import smirnoff from simtk import unit force_field = smirnoff.ForceField('smirnoff99Frosst_experimental.offxml') # t9 # [#1:1]-[#6X4:2]-[#6X4:3]-[#8X2:4] # H1-C1-C2-O2 # GAFF v2.1 # k = 0.16 per = 3 # SMIRNOFF99Frosst # k = 0.25 per = 1 # k = 0.00 per = 3 # # < Prope...
#!/home/zhangzhengde/bin/bin/python3 #coding=utf-8 import os import argparse import VaspCZ.zzdlib as zzd def modify_vasp_sh(jobname, nodes, ppn): with open('./Vasp.sh', 'r') as f: data = f.readlines() new_data = [] for line in data: if ' #PBS -N' in line: new_data.append(f' #PBS -N {jobname}\n') elif ' #P...
import logging from io import BytesIO from lxml import etree from lxml.builder import E from sciencebeam_gym.inference_model.extract_to_xml import ( XmlPaths, create_node_recursive, rsplit_xml_path ) from .grobid_service import ( grobid_service, GrobidApiPaths ) TEI_NS = 'http://www.tei-c.org/ns...
# Copyright 2017,2018,2019,2020,2021 Sony Corporation. # # 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...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import operator import collections import math import time import os import random import zipfile import time import numpy as np import sys from six.moves import urllib from six.moves import xrange # pylint: di...
# Connect to the internet (webpage) import urllib.request as request import json ########################################################################################## # Set Proxy for Urllib proxy="https://llm234:85167787887Ss!@proxy.ha.org.hk:8080" proxy_support=request.ProxyHandler({'https':proxy}) # Build Prox...
"""Модуль со вспомогательными функциями.""" from argparse import ArgumentTypeError from random import choice from string import ascii_letters from typing import Optional, Tuple, Union from graphql_relay import from_global_id def gid2int(gid: Union[str, int]) -> Optional[int]: try: return int(gid) ex...
import os import sys import time from django.conf import settings from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver # could use Chrome, Firefox, etc... here BROWSER = os.environ.get('TEST_BROWSER', 'PhantomJS') class BrowserTest(StaticLiveServerTestCase): de...
from __future__ import absolute_import, division, print_function import torch from pyro.distributions.torch import RelaxedOneHotCategorical, RelaxedBernoulli from pyro.distributions.util import copy_docs_from from torch.distributions.utils import clamp_probs @copy_docs_from(RelaxedOneHotCategorical) class RelaxedOn...
from django.conf.urls import url #import cas.middleware from . import views app_name = 'appauth' urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^login/$', views.user_login, name='login'), url(r'^login/forgetpassword/$', views.forgetPassword, name='forgetpassword'), url(r'^...
#!/usr/bin/env python #-*- coding:utf-8 -*- import click import os #import json import pandas as pd import numpy as np import pyproj import matplotlib.pyplot as plt from geodesic import plot_geodesic @click.command() @click.argument('xls_filename') @click.option('--outdir', default='', help="Output directory - d...
# Generated by Django 2.1.15 on 2021-04-08 16:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', ...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/space/weapon/missile/shared_countermeasure_decoy_launcher.i...
# Copyright The PyTorch Lightning team. # # 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 i...
from .random_transform import RandomTransform __all__ = [ 'RandomTransform', ]
# -*- coding: utf-8 -*- import os import sys import random sourceDir = '/data/deresute-face' trFile = 'train.txt' teFile = 'test.txt' mapFile = 'config/classes.py' if len(sys.argv) != 3: print ("usage %s trainNum testNum" % (sys.argv[0])) exit() datanum = int(sys.argv[1]) testnum = int(sys.argv[2]) def lis...
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
import tempfile import os from PIL import Image from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.models import Recipe, Tag, Ingredient from recipe.serializers import ...
import os import os.path import torch import numpy as np import pandas import csv import random from collections import OrderedDict from .base_video_dataset import BaseVideoDataset from ltr.data.image_loader import jpeg4py_loader from ltr.admin.environment import env_settings class Lasot(BaseVideoDataset): """ La...
""" Copyright (C) 2018-2020 Intel Corporation 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 i...
""" WSGI config for shopping_mall_server 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.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault(...
import pytest import redis from mock import Mock from distutils.version import StrictVersion REDIS_INFO = {} default_redis_host = "localhost" default_redis_port = "6379" default_cluster_master_host = "127.0.0.1" default_cluster_master_port = "6379" def pytest_addoption(parser): parser.addoption('--redis-host',...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'bot_update', 'gclient', 'gerrit', 'tryserver', 'recipe_engine/buildbucket', 'recipe_engine/json', 'recipe_engine/path', 'recipe_eng...
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
""" This test is only for Chrome! (Verify that your chromedriver is compatible with your version of Chrome.) """ import colorama from seleniumbase import BaseCase class ChromedriverTests(BaseCase): def test_chromedriver_matches_chrome(self): if self.browser != "chrome": print("\n This test is...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class ArgMinOptions(object): __slots__ = ['_tab'] @classmethod def GetRootAsArgMinOptions(cls, buf, offset): n = flatbuffers...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy...
import os import re import io import numpy as np import PIL.Image import typing from pynger.types import Image, Mask, Field from pynger.fingerprint.tuning_lro import LROEstimator from pynger.fingerprint.sampling import convert_to_full, subsample from pynger.field.manipulation import polar2cart from pynger.misc import r...
class FSM: def __init__(self,states,alphabet,transitionmatrix,currstate): self.S=states self.A=alphabet self.TM=transitionmatrix self.currstate=currstate def accept(self,sym): if sym not in self.A: return symi=self.A.index(sym) if self.TM[...
# yaml_same_ids.py import yaml interfaces = dict( Ethernet1=dict(description="Uplink to core-1", speed=1000, mtu=9000), Ethernet2=dict(description="Uplink to core-2", speed=1000, mtu=9000), ) prop_vals = ["pim", "ptp", "lldp"] interfaces["Ethernet1"]["properties"] = prop_vals interfaces["Ethernet2"]["proper...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ cand = 0 mindis = 9999 nl = len(nums) if nl == 3: return sum(nums) ...
import time import RPi.GPIO as GPIO import sys from pynput import keyboard import csv ##from termios import tcflush, TCIOFLUSH, TCIFLUSH from multiprocessing import Process from datetime import datetime GPIO.cleanup() Forward = 17 Backward = 27 Left = 23 Right = 24 sleeptime = 0.25 speed = 0.5 mode=GPIO.getmode() G...
import sys import math input = sys.stdin.readline def eratosthenes(limit): if limit == 1: return [] A = [i for i in range(2, limit + 1)] P = [] for i in range(limit): prime = min(A) if prime > math.sqrt(limit): break P.append(prime) for j in range...
# Module to search for and get data on SSWs # Using the definition of Charlton and Polvani (2007): # Author rachel.white@cantab.net # Created July 2017 import numpy as np import xarray as xr import math import sys def adddays(U,itime,ndays): # Find ndays consecutive days with easterlies numcons = 0 toru...
import datetime from django.conf import settings from django.conf.urls import url from django.http import HttpResponse import piston.resource from piston.emitters import Emitter from billy.web.api import handlers from billy.web.api.emitters import BillyJSONEmitter class CORSResource(piston.resource.Resource): d...
#!/usr/bin/python # -*- coding: utf-8 -*- # This file was generated from setuptools.command.test import test as test_command from setuptools import setup class PyTest(test_command): def finalize_options(self): test_command.finalize_options(self) self.test_args = [] self.test_suite = True...
import torch import numpy as np from tqdm import tqdm from torch.utils.data import DataLoader from experiments.data_model.image_denoising.noise_dataset import NoiseDataSet from experiments.models_architecture.camera_nlf_flow import generate_nlf_flow def train_step(in_noise, in_cond_vector): opt.zero_grad() lo...
#!/usr/bin/env/python3 # Copyright (c) Facebook, Inc. and its affiliates. # 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. """Metrics API **Overview**: The metrics API in torchelastic is used to publish telemet...
import logging import os from torch.utils.data import DataLoader from locator import Locator class DatasetBuilder: def __init__(self, val_data, dataset_factory_name, tokenisor_factory_name, train_data=None, num_workers=None, batch_size=8, addition_args_dict=None): self._addition_args_d...