content
stringlengths
5
1.05M
# # PySNMP MIB module WL400-GLOBAL-REG (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WL400-GLOBAL-REG # Produced by pysmi-0.3.4 at Mon Apr 29 21:29:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
# -*- encoding: utf-8 -*- """ @File : testpyandatic.py @Time : 2020/12/6 12:28 @Author : chise @Email : chise123@live.com @Software: PyCharm @info : """ from pydantic import Field from pydantic.main import BaseModel class A(BaseModel): a: str = Field( ..., ) a = A(a="4") class B(A): ...
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: ''' T: O(n) and S: O(1) ''' currMax = -1 for i in range(len(arr) - 1, -1, -1): currVal = arr[i] arr[i] = currMax currMax = max(currMax, currVal) return arr
from dateutil.parser import parse import datetime import json from six.moves import ( configparser, input, ) import sys import twitter USAGE = '''Usage: python adiaux.py archive before_date archive - the JSON file from your downloaded twitter archive before_date - the cut-off date for tweets; tweets post...
""" CacheItem interface: '_id': string, 'url': string, 'response_url': string, 'body': string, 'head': string, 'response_code': int, 'cookies': None,#grab.response.cookies, TODO: WTF with cookies??? """ from hashlib import sha1 import zlib import logging import MySQLdb import marshal import time from weblib.encoding i...
from vk_api.longpoll import VkLongPoll, VkEventType from vk_api import VkUpload import vk_api token = "YOUR_TOKEN" def write_msg(user_id, message, random_id): vk.messages.send( user_id=user_id, random_id=0, message=message, ) def write_k_msg(user_id, message, random_id, keyboard): ...
from rest_framework.views import APIView from django.shortcuts import render from .models import Lecturer, Publication from .serializers import PublicationSerializer, LecturerSerializer from rest_framework import filters from .pagination import PostPageNumberPagination from rest_framework.renderers import TemplateHTMLR...
#Encrypted with Crypton #Created by R 4 U F import marshal,zlib,base64 exec(marshal.loads(zlib.decompress(base64.b32decode("PCOO2OLLKMNVS5VXEVAIBQIGNSBW33DR3PRQP5QYXVADZ3DBHTRGLM5WQFVLA4PECBK2HPQSRVNN24W7S2AQSTVKY2U6Z3FHMSZ2S7NEU3ZCLFIPTPFOOVHFV5WFKUS37YF4TN2UNVZM5OL5UULMNTTMH2SPEIJNXB657Z64OPH3WSZMPQ5OD73L7ALX7WGBTACX...
from django.urls import path from blog import views from blog.feeds import LatestArticlesFeed app_name = 'blog' urlpatterns = [ path('', views.article_list, name='article_list'), path('search/', views.article_search, name='article_search'), path('<int:year>/<int:month>/<int:day>/<slug:article_slug>/', ...
#!/usr/bin/env python """ .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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 ...
# Copyright (c) 2021 Oleg Polakow. All rights reserved. # This code is licensed under Apache 2.0 with Commons Clause license (see LICENSE.md for details) """Ultimate Python library for time series analysis and backtesting at scale. While there are many great backtesting packages for Python, vectorbt combines an extre...
# Copyright (c) 2018 RedHat, Inc. # 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...
""" Problem: stockprices Link: https://open.kattis.com/problems/stockprices Source: NWERC 2010 """ import queue import sys def runTest(): N = int(input()) buyHeap = queue.PriorityQueue() # MinHeap sellHeap = queue.PriorityQueue() # MinHeap stockPrice = None for i in range(N): ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import math import networkx as nx import functools import scipy.stats import random import sys import copy import numpy as np import torch import utils sys.path.append('../../build') import MatterSim class ShortestPathOracle(object):...
from typing import Callable, Dict, Tuple import jax import jax.numpy as np import numpy as onp def loss1_fn(x: np.ndarray) -> np.ndarray: """Compute first biobjective loss function.""" return 1 - np.exp(-np.linalg.norm(x - 1 / np.sqrt(x.shape[-1]), axis=-1) ** 2) def loss2_fn(x: np.ndarray) -> np.ndarray: ...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "echopy", version = "1.1.0", author = "EchoPY", author_email = "echopy@protonmail.com", description= "Fisheries acoustic data processing in Python", long_description = long_descriptio...
# -*- coding: utf-8 -*- """Manages custom event formatter helpers.""" class FormattersManager(object): """Custom event formatter helpers manager.""" _custom_formatter_helpers = {} @classmethod def GetEventFormatterHelper(cls, identifier): """Retrieves a custom event formatter helper. Args: id...
import collections from typing import Callable from typing import List from typing import Optional from typing import Sequence import warnings import optuna from optuna._experimental import experimental from optuna.study import Study from optuna.trial import FrozenTrial from optuna.trial import TrialState from optuna....
import random import numpy as np from sum_tree import SumTree class Memory: def __init__(self, tree_memory_length, error_multiplier=0.01, alpha=0.6, beta=0.4, beta_increment_per_sample=0.001): self.tree = SumTree(tree_memory_length) self.tree_memory_length = tree_memory_length self.error_m...
import os import csv import config import random import argparse # Returns a number of reference and decoded text pairs along with scores from specified data. parser = argparse.ArgumentParser() parser.add_argument("-d", dest="data_name", required=False, default="data_T50...
#! /usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter from ResNetBlocks import * def gem(x, p=3, eps=1e-6): return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p) # return F.lp_pool2d(F.threshol...
import hypothesis from src.schemas import RawData, ProcessedData from src.process_data import process_data from src.train_model import train_model @hypothesis.given(RawData.strategy(size=10)) @hypothesis.settings(max_examples=100) def test_process_data(raw_data): process_data(raw_data) @hypothesis.given(Proces...
from controller import Robot class Spot (Robot): NUMBER_OF_LEDS = 8 NUMBER_OF_JOINTS = 12 NUMBER_OF_CAMERAS = 5 def __init__(self): Robot.__init__(self) self.time_step = int(self.getBasicTimeStep()) # keyboard self.keyboard = self.getKeyboard() self.keyboard....
# Copyright (c) 2021 NVIDIA Corporation. All rights reserved. # This work is licensed under the NVIDIA Source Code License - Non-commercial. # Full text can be found in LICENSE.md """ Create videos from image sequences (in json_save) """ import glob import subprocess import numpy as np import os import json import tq...
import os import torch import torchvision.transforms as transforms import pytest import pytorch_lightning as pl import shutil import imgaug.augmenters as iaa def test_heatmap_dataset(): from pose_est_nets.datasets.datasets import BaseTrackingDataset, HeatmapDataset data_transform = [] data_transform.appe...
import csv, json, os from collections import defaultdict from glob import glob import numpy as np import torch import scipy.io as sio from PIL import Image import cv2 from im_utils import read_keypoints, cropout_openpose_one_third, crop infant_root = r'/home/groups/syyeung/zzweng/code/Infant-Pose-Estimation/data/coco...
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from ..user import * from ..conekta_utils import * import os import jwt import json import requests import conekta import base64 from PIL import Image import StringIO conekta.api_key = 'key_ReaoWd2MyxP5QdUWKSuXBQ' conekta.api_version = "2.0.0" conekta.loc...
import numpy as np import scipy.sparse as sp import warnings import itertools from sklearn.model_selection import StratifiedShuffleSplit from sklearn.linear_model import LogisticRegressionCV from sklearn.metrics import roc_auc_score, average_precision_score, f1_score from sklearn.preprocessing import normalize def e...
import itertools from tensorboardX import SummaryWriter import Config from Buffer import Buffer from AgentControl import AgentControl from mlagents_envs.base_env import ActionTuple from collections import deque import numpy as np from TestAgent import TestAgent class Agent: def __init__(self, env, beh...
WAV_FROM_MP3_TYPE = T.StructType( [ T.StructField("audio_name", T.StringType()), T.StructField("audio", T.BinaryType()), ] ) @F.pandas_udf(WAV_FROM_MP3_TYPE) def wav_from_mp3_udf( audio_bytes_series: pd.Series, audio_type_series: pd.Series, audio_name_series: pd.Series, ) -> pd.Dat...
import os.path import random import numpy as np import cv2 import torch import dataops.common as util import dataops.augmentations as augmentations from dataops.debug import tmp_vis, describe_numpy, describe_tensor from data.base_dataset import BaseDataset, get_dataroots_paths class LRHRDataset(BaseDataset): '''...
import mock from django.test import TestCase from django.template import RequestContext from fancypages.test import factories class TestTextBlock(TestCase): def setUp(self): super(TestTextBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestConte...
# # Generated with EnvelopeCurveSpecificationBlueprint from dmt.blueprint import Blueprint from dmt.dimension import Dimension from dmt.attribute import Attribute from dmt.enum_attribute import EnumAttribute from dmt.blueprint_attribute import BlueprintAttribute from sima.sima.blueprints.moao import MOAOBlueprint cla...
# Будь ласка, не змінюйте версію навіть якщо ви створюєте своє програмне забезпечення на основі цього навчального коду! __version__ = 1.2
# -*- coding: utf-8 -*- """ shellstreaming.ostream.null ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :synopsis: ignore output records (for performance evaluation purpose) """ from shellstreaming.ostream.base import Base class Null(Base): """""" def __init__(self, **kw): """""" Base.__init__(self,...
""" Copyright 2019 Islam Elnabarawy 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 ...
from dataclasses import dataclass from typing import List from diamond_miner.defaults import UNIVERSE_SUBSET from diamond_miner.queries import GetInvalidPrefixes from diamond_miner.queries.query import LinksQuery, links_table from diamond_miner.typing import IPNetwork from diamond_miner.utilities import common_paramet...
import nep import time import sys msg_type = "string" # Message type to listen. node = nep.node("publisher_sample","ROS") # Create a new node pub = node.new_pub("pub_sub_test",msg_type) # Set the topic and the configuration of the publisher # Publish a message each second while True: ...
# # A convenient, gym-like wrapper for pybullet # https://github.com/liusida/PyBulletWrapper # # Author of this file: # 2020 Sida Liu (learner.sida.liu@gmail.com) # License: # MIT # Description: # This wrapper is the base of all other wrappers, it takes some Python tricks create a class interface for a module. # ...
#!/usr/bin/env python3 ''' This is a slow one, but works. ''' import scholarly import pandas as pd from csv import DictWriter def get_author_data(author): ''' Gets metadata for a single author. ''' author_data = [] print('Looking up:', author) try: a = scholarly.search_author(au...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. 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/LICEN...
# Generated by Django 2.2.13 on 2021-09-09 14:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('characters', '0046_journal_stats'), ] operations = [ migrations.AlterField( model_name='character', name='num_games...
# -*- coding: utf-8 -*- import os import time from app import librusec from flask import render_template, request, abort, send_file, g from models import Authors, Books, Genre from readlib import extract_book RUSSIAN_LETTERS = u'АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЭЮЯ' def get_author_by_id(id_author): author = Authors.quer...
"""Add include_in_timeline field Revision ID: 51e93ee3ed38 Revises: 1cdc1050b92f Create Date: 2021-04-23 15:05:01.944535+00:00 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "51e93ee3ed38" down_revision = "1cdc1050b92f" branch_labels = None depends_on = None ...
import pyodbc from mysql import * from sqlalchemy import create_engine def mssql_121(): cstr = "Driver={SQL Server};SERVER=192.168.88.121;DATABASE=SOC_Roster;UID=sa;PWD=Robi456&" conn = pyodbc.connect(cstr) return conn def mssql(): cstr = "Driver={SQL Server};SERVER=192.168.0.108;DATABASE=SOC_Roster;...
""" """ import os from keras import backend as K from keras.layers import Embedding from ._mixin_common import mixedomatic if K.backend() == 'tensorflow': import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector from keras.callbacks import TensorBoard __all__ = ('TensorBoard...
import ftplib def connect(host,user,password): try: ftp = ftplib.FTP(host) ftp.login(user,password) ftp.quit() return True except: return False def main(): # Variables targetHostAddress = '192.168.0.103' userName = 'kuntu' passwordsFilePath = 'passwords.txt' # try to connect using a...
#!/usr/bin/python ################## # AndorCam.py # # Copyright David Baddeley, 2009 # d.baddeley@auckland.ac.nz # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
import tensorflow as tf def convolutional_layer(name, inputs, filters: int, kernel_size: int, downsample: bool, batch_norm: bool, activation: str): """ An implementation of the yolov3 custom convolutional layer. Parameters ---------- name : string The name of the tensor to be used in Tens...
from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_201_CREATED, HTTP_404_NOT_FOUND from rest_framework.views import APIView from .custom_exceptions import RecordNotFound from .models import Product from . import util from shared import wra...
"""Tooling.""" import redis from django.conf import settings from . import constants def get_redis_connection(): """Return a client connection to Redis server.""" rclient = redis.Redis( host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_QUOTA_DB ) rclient....
# 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 = [ 'chromium', 'depot_tools/gclient', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', ]...
import matplotlib # matplotlib.use('Qt5Agg') import copy import glob import os import numpy as np import torch import json import algo from arguments import get_args from model import Policy from storage import RolloutStorage from osim.env import L2RunEnv from torchrunner import TorchRunner args = get_args() asser...
# Generated by Django 3.2.5 on 2021-07-15 20:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0006_auto_20210715_1454'), ] operations = [ migrations.AlterField( model_name='recipe', name='name', ...
x = input() y = input() z = input() print(int(x) + int(y) + int(z))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Publish random similar poses to /ardrone/pose. """ from __future__ import division import numpy as np import rospy import tf2_ros from geometry_msgs.msg import PoseStamped, TransformStamped from helpers import Pose class PoseGenerator(object): """ A pose g...
import pandas as pd from bert_clf.src.pandas_dataset.PandasDataset import PandasDataset from bert_clf.src.pandas_dataset.SimpleDataFrame import SimpleDataFrame from typing import Dict, Any, List, Tuple, Optional, Union from transformers.tokenization_utils_base import PreTrainedTokenizerBase from bert_clf.src.dataset im...
"""Poisson solver to calculate the electron density self-interaction contribution to the potential in the DFT formalism. """ import numpy as np def phi(basis, n, cell=None, fast=True): """Solves the Poisson equation using the given basis and density vector. Args: basis (str): one of the *modules* i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created: Aug 2017 @author: D34D9001@9R0GR4M13 """ import kerri import math import sys ########################## # MATHEMATICAL FUNCTIONS # ########################## class Math(object): """ This class controls mathimatical opperations. Most of t...
from armulator.armv6.opcodes.abstract_opcodes.wfi import Wfi from armulator.armv6.opcodes.opcode import Opcode class WfiT1(Wfi, Opcode): def __init__(self, instruction): Opcode.__init__(self, instruction) Wfi.__init__(self) def is_pc_changing_opcode(self): return False @staticmet...
#!/usr/bin/env python3 import unittest from unittest.mock import patch import re from tmc import points from tmc.utils import load, get_out, patch_helper module_name="src.file_listing" file_listing = load(module_name, "file_listing") ph = patch_helper(module_name) @points('p02-02.1') class FileListing(unittest.Test...
"""cisco lldp neighbour command output parser """ # ------------------------------------------------------------------------------ from facts_finder.common import remove_domain from facts_finder.common import verifid_output from facts_finder.cisco.common import standardize_if # ----------------------------------...
import json import logging import os from pathlib import Path from subprocess import Popen from flask import Flask, redirect from werkzeug.routing import PathConverter my_dir = Path(os.path.abspath(__file__)).parent STATIC_FOLDER = os.path.abspath(str(my_dir / '..' / 'static')) INNER_STATIC_FOLDER = os.path.abspath(s...
from django.conf.urls import url import datasets.views as datasets_views urlpatterns = [ url(r'^$', datasets_views.datasets_list), url(r'^reload$', datasets_views.dataset_reload), url(r'^create$', datasets_views.dataset_create), url(r'^delete$', datasets_views.dataset_delete), url(r'^dump$', dataset...
import io from unittest import TestCase from followthemoney import model from followthemoney.types import registry from followthemoney.export.graph import NXGraphExporter ENTITIES = [ { 'id': 'person', 'schema': 'Person', 'properties': { 'name': 'Ralph Tester', 'bir...
# Generated by Django 3.2.4 on 2021-08-30 13:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='teste', field=mod...
import base64 import binascii import time from collections import UserDict from datetime import datetime from enum import Enum from functools import wraps from nanolib import ( InvalidSeed, nbase32_to_bytes, bytes_to_nbase32, get_account_id ) from .secret import Secret __all__ = ( "WalletSerializable", "Time...
# Authors: Zhaoshuo Li, Xingtong Liu, Francis X. Creighton, Russell H. Taylor, and Mathias Unberath # # Copyright (c) 2020. Johns Hopkins University - All rights reserved. import copy import numpy as np import torch import torch.nn as nn class NestedTensor(object): def __init__(self, left, right, disp=None, s...
from talon import Module, app from ..csv_overrides import init_csv_and_watch_changes mod = Module() mod.list("cursorless_scope_type", desc="Supported scope types") # NOTE: Please do not change these dicts. Use the CSVs for customization. # See https://github.com/pokey/cursorless-talon/blob/main/docs/customization....
import __main__ __main__.pymol_argv = ['pymol','-qc'] # Pymol: quiet and no GUI from time import sleep import pymol pymol.finish_launching()
# Copyright 2013-2021 Aerospike, 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 writ...
#CODE_REVISION(2020/11/2) from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys import MySQLdb import datetime from datetime import datetime from datetime import timedelta from PyQt5.uic import loadUiType ui,_ = loadUiType('library.ui') class MainApp(QMainW...
conta = 0 n1 = int(input('primeiro termo :')) n2 = int(input('razão PA :')) print(n1, end=' ') while not conta == 10: conta += 1 n1 += n2 print(n1, end=" ") print('\nse n quiser mostrar mais nada e so digitar 0') pergunta1 = 1 while not pergunta1 == 0: pergunta1 = int(input('\nvc quer mostrar mais quant...
import os import pandas as pd def is_sas_table(path): """ Evaluates if a file is a sas table :param path: file to evaluate :return: True if file is a csv, False otherwise """ if path[-9:] == '.sas7bdat': return True return False def get_all_sas_tables(path): """ Returns a...
# Meadowlark_LCVR.py qtlab driver for Meadowlark LCVR # Device manual at http://www.zaber.com/wiki/Manuals/T-NM # # Reinier Heeres <reinier@heeres.eu>, 2009 # Umberto Perinetti <umberto.perinetti@gmail.com>, 2009 # # This program is free software; you can redistribute it and/or modify # it under the terms of the...
from rtl.tasks.regression import regression from dummy_data import KWARGS, CONTENTS3 def test_linearRegression(): KWARGS = { 'operations': [ { 'x': 'a', 'y': 'b', 'space': 'linear', 'model': 'Linear' }, ] } ...
m = float(input('Uma distância em metros: ')) dm = m * 10 cm = m * 100 mm = m * 1000 dam = m / 10 hm = m / 100 km = m / 1000 print('A medida de {}m corresponde a \n{}km, \n{}hm, \n{}dam, \n{:.0f}dm, \n{:.0f}cm, \n{:.0f}mm.'.format(m, km,hm, dam, dm, cm, mm))
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser from InventoryFilter import InventoryFilter class BeakerInventory(InventoryFilter): def get_hostnames(self, topology): hostnames = [] if not ('beaker_res' in topology): return ...
import numpy as np def step_gradient_descent(params, grad, alpha): """Single iteration of gradient descent. Args: params (ndarray[1, n]): parameters for current step grad (ndarray[1, n]): gradient for current step alpha (float): learning rate Returns: p...
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 10:04:57 2019 @author: Dominic """ import numpy as np from numba import njit, float64, int64 from enum import Enum from ...finutils.FinError import FinError from ...finutils.FinGlobalVariables import gDaysInYear from ...products.equity.FinEquityVanillaOption import ...
#!/usr/bin/env python import os from atizer import * from atizer.dbase import * class pyatizer(autoprog): def __init__( self, srcdir=None ): super( pyatizer, self ).__init__( "atizer", srcdir ) self.copyright_holder = "Timothy J. Giese" if len(self.sources) > 0 or len(self.headers) > 0: ...
""" 1) Import the random function and generate both a random number between 0 and 1 as well as a random number between 1 and 10. 2) Use the datetime library together with the random number to generate a random, unique value. """ import random from datetime import datetime import time rand_num1 = ra...
import datetime import json from django.shortcuts import render, redirect, reverse from django.views.generic import View from stock.models import Stock from stock.module_stock import TradingData from howdimain.utils.min_max import get_min, get_max from howdimain.utils.get_ip import get_client_ip from howdimain.howdimai...
import functools import inspect import sys __version__ = "0.1.3" __all__ = "Plugin Injector inject".split() py32 = sys.version_info >= (3, 2, 0) def _makelist(data): if isinstance(data, (tuple, list, set)): return list(data) elif data: return [data] else: return [] class Inject...
""" link: https://leetcode.com/problems/jump-game problem: 定义nums为,位于nums[k],可跳到[k-nums[k],k+nums[k]],问第n-1是否可达 solution: 45题的简化版,更新最远距离即可 """ class Solution: def canJump(self, nums: List[int]) -> bool: bound = 0 for i in range(0, len(nums)): if bound < i: return Fal...
""" Utilities for dealing with data Borrows from: https://github.com/guillaumegenthial/sequence_tagging """ import numpy as np import tensorflow as tf from collections import OrderedDict # shared global variables UNK = "$UNK$" NUM = "$NUM$" NONE = "o" # special error message class MyIOError(Exception): def __ini...
from bs4 import BeautifulSoup import re from urllib.parse import urljoin import os import urllib class HtmlParser(object): def _get_new_urls(self, soup): sets = set() # /view/123.htm #<a target="_blank" href="/item/%E6%9D%8E%C2%B7%E5%A1%94%E7%8E%9B%E9%9C%8D%E7%91%9E/5486870" data-lemmaid="5...
from setuptools import setup setup( name = "magpie", author = "Nicholas FitzRoy-Dale", description = "Interface compiler for the L4 microkernel", version = '11', packages = ['magpie'] )
import manage_server import sys manage_server.main(sys.argv)
import torch import numpy as np from torch.utils.data import Dataset class UNet3DDataset(Dataset): def __init__(self, scans_segs, size= None): self.img_dir = [] for s in scans_segs: # if each image is different sized, we need to get w, h here _, width, height = s[0].shape ...
"""Asynchronous Python client for the Geocaching API.""" import asyncio from geocachingapi import GeocachingApi async def main(): """Show example of using the Geocaching API""" async with GeocachingApi() as api: print("test") if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_...
from .dynamic import Dynamic from .single_integrator import SingleIntegrator from .double_integrator import DoubleIntegrator from .unicycle import Unicycle from .linear import Linear
# see https://www.codewars.com/kata/51e056fe544cf36c410000fb/train/python def top_3_words(text): retDict = {} text = "".join(x if x.isalpha() or x == "'" else " " for x in text) # print(text) for word in text.split(" "): if "".join(x for x in word if x.isalpha()).isalpha(): word = "".join(x for x in ...
# # Copyright 2019 Google LLC # # 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 ...
# Example preprocessing images for training in my application. # Scenario: # 1. I have the folder with all images, many subjects together # 2. The images are named with some pattern # 3. We know which original name of image matches to which personality # 4. In result, with specify pattern, for example "subjec...
__version__ = __import__("paka.cmark", fromlist=["cmark"]).get_version() + "dev" from .func import ( markdown_to_commonmark, markdown_to_html, markdown_to_latex, markdown_to_man, markdown_to_xml, ) from .iter import NodeIter from .node import Node from .parser import MarkdownParser __all__ = [ ...
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' CNN+BiGRU @author Sean @last modified 2017.09.06 17:14 ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torch.autograd import Variable import numpy as np import rando...
from flask_admin import Admin from pagetags import login_manager from pagetags.models import db from pagetags.authentication import (load_user, authenticate, identity, payload_handler, request_handler) from pagetags import jwt from pagetags.admin import (UserModelView, Authenticate...
import logging logger = logging.getLogger(__name__) from core import Link import glob import serial import time GLOBS = [ '/dev/tty.usb*', '/dev/ttyUSB*' ] def scan( ): """scan all ports, retuns a list of device names.""" r = [ ] for pat in GLOBS: r.extend(glob.glob(pat)) return r def usable_response(re...
# Generated by Django 2.1 on 2018-09-16 13:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('demand', '0001_initial'), ] operations = [ migrations.AddField( model_name='demand', name='description', f...