content
stringlengths
5
1.05M
numbers = [2, 9, 7, 5, 3, 4, 1, 6, 8] def cocktail_sort(array): n = len(array) m = -1 swapped = True while n > 0 and swapped == True: swapped = False #Back to front for index in range (m+1, n): if array[index] < array[index-1]: array[index], array[index-1] = array[index-1], array[i...
from .country_views import CountryListAPIView, CountryDetailAPIView from .city_views import CityListAPIView, CityDetailAPIView from .district_views import DistrictListAPIView
# encoding: utf-8 import pandas as pd import numpy as np # 二、Pandas 常见的基本方法 # # 2.1 数据读取与存储 # # Pandas 支持大部分常见数据文件读取与存储。一般清楚下,读取文件的方法以 pd.read_ 开头,而写入文件的方法以 pd.to_ 开头。详细的表格如下。 # # 此处输入图片的描述 # # 拿刚刚下载好的数据文件举例,如果没有下载,请看 1.5 小节。 df = pd.read_csv("los_census.csv") #读取 csv 文件 print df # 可以看到,文件已经读取出来了。由于列数太多,所以分段显示了。输出...
#!/usr/bin/env python # MIT LICENSE DO WHATEVER YOU WANT # Author: Calvin Ference # Data will come in as in the following input data = ''' ''' def main(): global data f = open("asgore.txt", "r") data = f.readlines() class Block(object): def __init__(self, data): self.data = data def __i...
import unittest class TestFilePass(unittest.TestCase): def test_pass(self): self.assertTrue(True)
# Copyright (c) Xavier Figueroa # 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, sof...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayCreditAutofinanceLoanApplyResponse(AlipayResponse): def __init__(self): super(AlipayCreditAutofinanceLoanApplyResponse, self).__init__() self._app...
""" This module provides a traceset implementation based on Python's pickle format. This implementation of the traceset is thus very generic. """ import pickle from io import BufferedIOBase, RawIOBase from pathlib import Path from typing import Union, BinaryIO from public import public from .base import TraceSet @p...
import json import os from core.AbstractConfig import AbstractConfig __author__ = 'sweet' # rootDir = os.path.join(os.path.split(os.path.realpath(__file__))[0], '..') # config_path = os.path.join(rootDir, 'config', 'autosign.conf') class JsonConfig(AbstractConfig): def __init__(self, config_path): sel...
import gym import numpy as np import torch import random import pybullet_envs import time from sklearn.metrics import roc_curve, auc from sklearn import datasets, manifold import matplotlib.pyplot as plt import copy import os from deep_rl import * from hyperparameter_test import * from sklearn.ensemble import Isola...
from hybrid.resource import WindResource, SolarResource # California Site # lat = 33.907295 # lon = -116.555588 # year = 2012 # hubheight = 80 # Texas Site # lat = 34.212257 # lon = -101.361160 # year = 2012 # hubheight = 91.5 # Maine Site lat = 44.766171 lon = -68.157669 year = 2012 hubheight = 116.5 WindResource...
import os # # Important! You need to run this file when installing the database # and after anysequent database flushes # # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BusinessSimulator.settings') import django from django.core.files import File django.setup() from djan...
import plyvel from binascii import hexlify, unhexlify import ujson import json from math import ceil from copy import deepcopy #from bitcoin_tools.analysis.status import * from utils import change_endianness, encode_varint #from bitcoin_tools.core.script import OutputScript #from bitcoin_tools.core.keys import get_unco...
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import unittest import xml.etree.ElementTree as ET from textwrap import dedent from pants.base.build_environment import get_buildroot from pants.util.collections import assert_s...
def cria_conta(numero, titular, saldo, limite): conta = {"numero": numero, "titular": titular, "saldo": saldo, "limite": limite} return conta def deposita(conta, valor): conta["saldo"] += valor def sacar(conta, valor): conta["saldo"] -= valor def extrato(conta): print(f"Saldo é {conta['saldo']}")...
from . import pandas, xarray # noqa (API import) try: import dask as _dask # noqa (Test dask installed) from . import dask # noqa (API import) except ImportError: pass try: import cudf as _cudf # noqa (Test cudf installed) import cupy as _cupy # noqa (Test cupy installed) from . import ...
# Copyright © 2019 Province of British Columbia # # 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 agr...
#!/usr/bin/env python2 import sqlite3 def write_header(_f): _f.write("/* Generated by codegen.py\n") _f.write(" * DO NOT EDIT\n") _f.write(" */\n\n\n") db = sqlite3.connect("bulkdata.db") f = open("src/cache_types.h", "w") write_header(f) f.write("#ifndef __CACHE_TYPES__H__\n") f.write("#define __CACH...
__author__ = 'distro' import sys import re import pandas as pd import nltk MODEL_PATH="model/" MODEL_FILE="classifier.pkl" TFIDF_FILE="tfidf.pkl" QUESLE_FILE="quesle.pkl" ValidQuesWords=['A', 'About', 'Can', 'Define', 'For', 'Give', 'How', 'In', 'Name', 'On', 'Tell', 'The', 'To', 'What', 'Whats', 'When', 'Where', 'Whe...
# import sys # gym_dir='/home/joaomano/.local/lib/python3.6/site-packages' # sys.path.append(gym_dir) import gym import matplotlib.pyplot as plt import numpy as np from q_learning_agent import Agent if __name__ == '__main__': env = gym.make('FrozenLake-v0') n_games = 10000 scores = [] win_pct_list =...
from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.core.context_processors import csrf import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import StringIO from qmpy import INSTALL_PATH from qmpy.models import ...
''' Python is a Object Oriented Programming Language it supports object oreinted approach to solve problems
#Copyright (c) 2019 Renaud Guillon. All rights reserved. # #This work is licensed under the terms of the MIT license. #For a copy, see <https://opensource.org/licenses/MIT>. from pwm_out_itf import pwm_out_itf class pwm_out(pwm_out_itf): def __init__(self): pass def set(self, value: float): ...
from src import app, request, ValidationError, CustomerSchema, json, InterviewSoapClient @app.route("/customer/<int:id>", methods=['GET', 'PATCH', 'DELETE']) def customer(id): if request.method == 'GET': soap_client = InterviewSoapClient() res = soap_client.call( service='CustomerSe...
import boto.emr from boto.emr.connection import EmrConnection from boto.emr.step import StreamingStep from boto.emr.step import InstallPigStep from boto.emr.step import PigStep import threading access_key_id = <access key id> secret_key = <secret key> pig_file = 's3://kagglesenta/pig/convert2fann.pig' INPUT = 's3://k...
eula = ( "PyWitch Client is a GUI interface to PyWitch library combined " "with a Web Application Framework (Flask).\n\n" "Its main purpose is to provide HTTP endpoint to get the lastest " "Twitch events captured with PyWitch.\n\n" "To do so, PyWitch requires OAuth token authentication. " "PyWit...
# # PySNMP MIB module AT-XEM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-XEM-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:30:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
from confluent_kafka import Consumer from config_handler import ConnectionConfig from error_handler import ErrorHandler class ConsumerConnectionManager: """ Initializes KafkaConsumer with connection details from main config file""" @classmethod def initialize_kafka_consumer(cls, environment): tr...
name = "pymum" version = "2" requires = ["pydad-2"]
import os from pathlib import Path import numpy as np storage_dir = Path(Path(__file__).parent, "data") if not storage_dir.is_dir(): os.mkdir(str(storage_dir)) arts = [] splitters = [] color_specs = [] def _save_art(art_str, splitter_str, colors_map, art_name): lines = [line.strip() for line in art_str.s...
# -*- coding: utf-8 -*- """ @contact: lishulong.never@gmail.com @time: 2018/4/8 下午2:22 """ import atexit import sys from signal import * from pymongo import * from config import * def _init_client(mongo_config, **kwargs): """ 初始化 Mongo Client 全局针对一个db只需要生成一次就行 每个 MongoClient 自带线程池 :return: """ ...
"""Various and generic stuff.""" from inspect import getsource from math import log, e import re def clamp(x, inf=0, sup=1): """Clamps x in the range [inf, sup].""" return inf if x < inf else sup if x > sup else x def replace_patterns(string, patterns): """Replaces multiple patterns in a string. -...
from PIL import Image, ImageDraw from utils.endpoint import Endpoint, setup from utils.textutils import wrap, render_text_with_emoji @setup class Facts(Endpoint): def generate(self, kwargs): text = kwargs['text'] base = Image.open(self.get_asset('facts.bmp')) # We need to create an image ...
#Código que prevê o peso do usuário caso ele(a) engorde ou emagreça peso=float(input("Informe seu peso atual:")) engordarUm = peso +(peso * 0.15) engordarDois = peso +(peso * 0.20) diferencaAcrescimo = engordarDois - engordarUm print("Caso você engorde 15%% ficara com: %.2f"% round(engordarUm,2)," KG") print("Caso...
## Copyright (c) 2020 mangalbhaskar. """FastAPI static files. https://fastapi.tiangolo.com/tutorial/static-files/ https://www.starlette.io/staticfiles/ https://fastapi.tiangolo.com/tutorial/static-files/#use-staticfiles https://github.com/tiangolo/fastapi/issues/130 pip install aiofiles "Mounting" means adding a co...
#!/usr/bin/python # To be deprecated and replaced by webify_models_v2.py # A script to update gazebo models to be web-friendly. # It converts all textures to png format and make sure they are # stored in the [model_name]/meshes/ directory alongside the # dae files. import os import subprocess import sys import shuti...
from django.db import models from django.contrib.auth.models import User class Note(models.Model): text = models.CharField(max_length=255) owner = models.ForeignKey(User, related_name="notes", on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add...
import numba import numpy _multiprocessing_worker_fourier_var_dict = {} def _init_worker_fourier_smoothing(X, X_shape): _multiprocessing_worker_fourier_var_dict['X'] = X _multiprocessing_worker_fourier_var_dict['X_shape'] = X_shape def _worker_function_fourier_smoothing(i, threshold, window): x = i % _...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Zeyuan Shang # @Date: 2016-01-05 10:01:17 # @Last Modified by: Zeyuan Shang # @Last Modified time: 2016-01-05 10:01:27 class Solution(object): def maxNumber(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] ...
from splunk_eventgen.lib.outputplugin import OutputPlugin from splunk_eventgen.lib.logging_config import logger import logging import requests import time import sys import os import requests from requests import Session from requests_futures.sessions import FuturesSession from concurrent.futures import ThreadPoolExe...
from .cleanupmodule import * from .SubModules.commitscleaner import *
import calendar import csv import datetime import glob import io import json import os import zipfile from time import sleep from bs4 import BeautifulSoup from selenium.common.exceptions import NoAlertPresentException, NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.common.ke...
#!/usr/bin/python # python scraper.py <# files you want to download> # import modules import urllib2 import re import os def main(): res = urllib2.urlopen("http://www.free-midi.org/midi/g/green-day/pg4/") html = res.read() for match in re.findall(r'<a href="(http://www.free-midi.org/song/green.*)" itemprop=', htm...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import requests import json import getpass import hashlib from optparse import OptionParser from time import time import OpenSSL import six import _cffi_backend import os.path def get_md5(content): try: m2 = hashlib.md5() m2.updat...
''' file: mosh_dataloader.py author: zhangxiong(1025679612@qq.com) date: 2018_05_09 purpose: load COCO 2017 keypoint dataset ''' import sys from torch.utils.data import Dataset, DataLoader import scipy.io as scio import os import glob import numpy as np import random import cv2 import json im...
######## # Copyright (c) 2015 GigaSpaces Technologies Ltd. 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...
import discord from discord.ext import commands from Systems.levelsys import levelling import os from Systems.gettext_init import GettextInit import distutils.util # Set up environment variables: ANTISPAM_SYSTEM = bool(distutils.util.strtobool(os.environ["BOT_ANTISPAM_SYSTEM"])) PREFIX = os.environ["BOT_PREFIX"] ERROR...
# -*- coding: utf-8 -*- """Job model""" from .job_status import JobStatus class Job: def __init__( self, id_, created_on, status, completed_on=None, name=None, callback_url=None, metadata=None, media_url=None, failure=None, ...
# CPU: 0.06 s photos = [] for _ in range(int(input())): photos.append(list(map(int, input().split()))) speeds = [] for idx in range(1, len(photos)): speeds.append((photos[idx][1] - photos[idx - 1][1]) / (photos[idx][0] - photos[idx - 1][0])) print(int(max(speeds)))
from Malt.PipelineParameters import Parameter, Type import bpy from BlenderMalt.MaltProperties import MaltPropertyGroup COLUMN_TYPES = ['Texture','sampler','Material'] class MaltNode(): malt_parameters : bpy.props.PointerProperty(type=MaltPropertyGroup) disable_updates : bpy.props.BoolProperty(name="Dis...
# Copyright (c) 2015 Nicolas JOUANIN # # See the file license.txt for copying permission. from fullyconnect.errors import fullyconnectException from fullyconnect.mqtt.packet import ( CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, PINGREQ, PINGRESP, DISCONNE...
from localstack.services.cloudformation.service_models import GenericBaseModel from localstack.utils.aws import aws_stack from localstack.utils.common import select_attributes class Route53RecordSet(GenericBaseModel): @staticmethod def cloudformation_type(): return "AWS::Route53::RecordSet" def g...
import io import math import geopandas as gpd import numpy as np import pandas as pd import rasterio from pyproj import Transformer from pyproj.crs import CRS from rasterio.windows import Window from shapely.geometry import Point class MapUtils: def __init__(self, area: int): self.area = area sel...
from distutils.core import setup setup( name='OMSTD-hh-001', version='0.1.2', packages=['omstd_hh_001', 'omstd_hh_001.lib'], url='https://github.com/cr0hn/OMSTD/tree/master/examples/hacking/hh-001', license='BSD', entry_points={ 'console_scripts': [ 'omstd-hh-001 = omstd_hh_0...
#!/usr/bin/env python # Fit proper motion and parallax using ra/dec/mjd data # Most of this code was taken from here: # https://github.com/ctheissen/WISE_Parallaxes/blob/master/WISE_Parallax.py import os, sys import numpy as np from astropy.table import Table, vstack, join #import matplotlib.pyplot as plt from astro...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Extract the parameters from the database to a parameter file. The parameter file can be used to add a new equal simulation, but more usefully modified to run a slightly different simulation. """ # Copyright (C) 2017-2019 Håkon Austlid Taskén <hakon.tasken@gmail.com> # ...
""" 학습된 모델을 서비스로 활용하기 위해 로더 사용 """ # Keras .h5 모델 로더 from aicentro.loader.keras_loader import KerasLoader loader = KerasLoader( model_filename='filename' # 저장된 모델파일명 ( .h5 제외 ) ) """ 모델 온라인 서비스를 위한 BaseServing 클래스 """ from flask import jsonify, request from aicentro.serving.base_serving import BaseS...
""" PyGeM init """ # __all__ = [ # 'affine', 'filehandler', 'freeform', 'radial', 'openfhandler', 'elmerhandler', # 'stlhandler', 'unvhandler', 'vtkhandler', 'nurbshandler', 'stephandler', # 'igeshandler', 'utils', 'gui', 'khandler', 'idw' # ] from .affine import * from .freeform import FFD from .radial im...
import torch from settings import constants, arg from game import card_to_string class CardTools(): def __init__(self): pass def get_second_round_boards(self): out = torch.empty([constants.card_count, constants.board_card_count[1]], dtype=arg.int_dtype).to(arg.device) for i in range(c...
#from typing import ChainMap #4- Crear una clase que represente al perfil usuario que ademas tenga una relacion (herencia) con estas dos clases: #administrador y reportero (solo tiene lectura de datos).El usuario tiene objeto carrito de compras.El administrador puede ver # a todos los usuarios y lo que tenga adentro....
from django.conf.urls import url from ems import views app_name = 'ems' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login/$', views.user_login, name="login"), url(r'^logout/$', views.user_logout, name='logout'), url(r'^events_select/$', views.events_select, name='events_select'), url(r'^event_ho...
from os import path this_dir = path.dirname(path.realpath(__file__)) input_file = path.join(this_dir, "input.txt") def calc(math_tokens, op_order): answer = 0 for op_group in op_order: i = 1 while i < len(math_tokens): first, op, second = math_tokens[i-1], math_tokens[i], math_t...
""" Communications Discpline for CADRE """ import os from six.moves import range import numpy as np import scipy.sparse from MBI import MBI from openmdao.core.explicitcomponent import ExplicitComponent from CADRE.kinematics import fixangles, computepositionspherical, \ computepositionsphericaljacobian, computep...
from microbit import * # Please tag us if used! # We'd love to see what you make: # @ScienceOxford # Line-following robot code for microbit with L9110s motor driver # Thanks to MultiWingSpan, whose code for the Bit:Bot was a great starting point # http://www.multiwingspan.co.uk/micro.php?page=botline LF = pin14 LB =...
from namedtensor import ntorch nn = ntorch.nn import torch, math class Attention(nn.Module): "Scaled dot product attention" def __init__(self, p, scale): super(Attention, self).__init__() self.dropout = nn.Dropout(p) self.scale = scale def spec(self, dim_query, dim_keys): ...
# __init__.py # # The packages under experiments should be installation- or lab-specific # experiment scripts that are used for stimulus importing, stimulus selection, # jsPsych timeline specification, data analysis, and any other # experiment-specific functionality that the user wishes to enable. # Experiments are n...
from majorkirby import GlobalConfigNode from vpc import VPC from leader import MesosLeader from follower import MesosFollower from privatehostedzone import R53PrivateHostedZone def build_graph(aws_profile, gt_config): """ Builds graphs for mesos follower and mesos leader stacks Args: aws_profile ...
from django.urls import path from . import views from . import AmendViews app_name = 'polls' # urlpatterns = [ # path('', views.index, name = 'index'), # # path('<int:question_id>/', views.detail, name='detail'), # # path('<int:question_id>/results/', views.results, name='results'), # # path(...
import tornado.ioloop import tornado.options import tornado.httpserver import tornado.web from tornado.options import options, define import os import pymongo from pymongo import MongoClient # dbIp = 'localhost' class MONGODBHANDLER: def connectDB(self, dbName, dbIp, port): self._connection = MongoCli...
from decimal import * import timeit from basicPrime import basicPrime from fermatPrime import fermatPrime def main(algo): tic = timeit.default_timer() #store e to 1000 digits getcontext().prec = 1000 e = Decimal(1).exp() e = str(e).replace('.','') #Remove decimal from string prime = False ...
""" Based on https://en.wikipedia.org/wiki/Piano_key_frequencies and ATtiny13A datasheet Task: Calculate best-fit frequencies for ATtiny13A MCU that should match piano tones (according to wiki page) having (according to datasheet) only one 8-bit timer and 8, 64, 256 and 1024 prescaler. """ from io imp...
import requests class RaiderIoApiError(Exception): ''' Exception thrown when we get an bad return code from Blizzard API ''' class RaiderIoThrottlingError(Exception): ''' Exception thrown when we make too many requests ''' class RaiderIoApiRequest: ''' Wrapper for RaiderIO API calls. ...
""" Similar to the Approval Inbox but it makes it possible to put these together in an email. """ import datetime import collections import urlparse from django.utils import timezone from django.core.cache import cache from django.conf import settings from django.contrib.sites.models import Site from django.template.l...
def encode(json, schema): payload = schema.Main() payload.optimizations = [ schema.Optimization() ] payload.optimizations[0].includes = json['optimizations'][0]['includes'] payload.optimizations[0].excludes = json['optimizations'][0]['excludes'] payload.optimizations[0].lossy = json['optimizations']...
"""This file contains transform functions for electrode numbering. If want to apply custom electrode renumbering, use these functions as starting points to design your own. """ class transform_electrodes_roll_along(object): """This function shifts all electrode numbers by a fixed offset, as commonly encounter...
""" Train and test the onset detector CNN """ import numpy as np import database import generator import eda import os from glob import glob import keras from keras.layers import Conv2D, MaxPooling2D from keras.layers import Dropout, Flatten, Dense from keras.models import Sequential from keras.callbacks import Mode...
from random import randint # For simpler reading x is red, o is green class game(object): # Print msgs and errors if cout is True, players is a list of two players def __init__(self, players, cout=True): # (0,0) is top left corner self.slots = [['-' for i in range(6)] for i in range(7)] ...
from polygon import * import pytest def test_polygon(): abs_tol = 0.001 rel_tol = 0.001 try: p = Polygon(2, 10) assert False, ('Creating a Polygon with 2 sides: ' ' Exception expected, not received') except ValueError: pass ...
import types import string import io def format_value ( _value ): ''' >>> format_value ( "dette er en test" ) u'"dette er en test"' >>> format_value ( 'dette "er en" test' ) u'"dette \\\\"er en\\\\" test"' >>> format_value ( 123 ) u'123' >>> format_value ( 34.5 ) u'34.5' >>>...
"""Digraph module.""" import re from .key import Key from .util import Singleton, getchar, int2char DIGRAPH_PATTERN = re.compile(r'(\S{2})\s+(\S)+\s+\d+') """A digraph pattern used to find digraphs in digraph buffer.""" class Digraph(metaclass=Singleton): """A digraph registry singleton class. Note: ...
""" File: chapter14/tree_api_service/servo_controller.py Receives and processes PyPubSub messages for controlling Servo. Built and tested with Python 3.7 on Raspberry Pi 4 Model B Dependencies: pip3 install pypubsub paho-mqtt """ from time import sleep from pubsub import pub import logging import config logger = ...
from unittest import mock from unittest.mock import call import pytest from cognite.client.data_classes import * from cognite.client.experimental import CogniteClient c = CogniteClient() @pytest.mark.dsl class TestRepr: def test_repr_html(self): for cls in [Asset, Datapoints, Sequence, FileMetadata, Ro...
#statisticsFilesWords.py import glob files = glob.glob(r'needToStatistcs\*.txt') def fromFilesToText(files): text = '' for i in range(len(files)): aFile = files[i] with open(aFile,'r',encoding='ansi') as f: text = text + f.read() return text def sortWords(text): for i in ...
from aws_cdk import ( aws_ecr as _ecr, aws_iam as _iam, core, ) class EcrENV(core.Construct): def getRepositories(self,repo_name): return self.repositories[repo_name] def getRepositoriesList(self): return self.repositories.keys() def __init__(self, scope:...
class A: def __init__(self,name): self.name=name def display(self): print(self.name) a = A('www') a.display() class Complex: def __init__(self,real,img): self.real=real self.img=img def display(self): print(self.real,self.img) c = Complex(3,4) c.display()
import io import warnings from typing import TYPE_CHECKING, List, Tuple, Iterator, IO from pkg_resources import DistributionNotFound, get_distribution from . import errors, lfs from .lfs import __LFS_DISK_VERSION__, __LFS_VERSION__ from .errors import LittleFSError try: __version__ = get_distribution('littlefs-...
""" This file is used purely during debugging """ import logging import pdf2txtev import sberbankPDFtext2Excel # import os # path =r"C:\_code\py\Sberbank2Excel_no_github" # # pdf_files = [os.path.abspath(os.path.join(path, f)) for f in os.listdir(path) if f.endswith('.pdf')] # # print(pdf_files) # # for file in pdf...
# ------------------------------------------------------------------------ # * This program illustrates an array-based algorithm for tallying a # * continuous-data histogram for data read from standard input (stdin). # * Like program uvs, a compiled version of this program supports file # * redirection. # * # * The MI...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, unicode_literals) """ ================ Generic File I/O ================ :Authors: Moritz Emanuel Beber :Date: 2012-06-03 :Copyright: Copyright(c) 2012 Jacobs University of Bremen. All rights reserved. :File: generic.py """ __all__ ...
# Test that an AGM command properly generates a list of requests import pytest from agm import agm, exceptions stdin = None valid1 = ["directory", "users", "list"] invalid1 = ["directory", "users", "lisadfst"] invalid2 = ["directory", "users", "list", "extra"] valid = [valid1] invalid = [invalid1, invalid2] def te...
#!/usr/bin/env python3 # encoding: utf-8 import numpy as np import torch as th import torch.distributions as td from rls.algorithms.base.sarl_on_policy import SarlOnPolicy from rls.common.data import Data from rls.common.decorator import iton from rls.nn.models import ActorDct, ActorMuLogstd, CriticValue from rls.nn....
from django.urls import path from happy_dogs.dogs.views import BoardingView, BoardingDayView, DogCreateView, \ BoardingVisitCreateView, CreateBoardingTestDataView, BoardingAPIView, BoardingDayAPIView app_name = "dogs" urlpatterns = [ path("add-dog/", DogCreateView.as_view(), name="add-dog"), path("add-vis...
# https://programmers.co.kr/learn/courses/30/lessons/12899?language=python3 def solution(n): answer = '' my_dict = ['4','1','2'] r = n while r>0: r,q = divmod(r,3) answer += my_dict[q] if q== 0: r -= 1 return answer[::-1]
#!/usr/bin/env python3 import numpy as np import os import struct import time import torch import copy import imageio import auxiliary.fusion_lidar as fl from auxiliary.np_ioueval import iouEval from auxiliary.tools import get_mpl_colormap, convert_range class LaserScan: """Class that contains LaserScan with x,y,z,...
n = int(input()) t = 0 h_list = [] g_list = [] for i in range(n): h, g = map(int, input().split()) h_list.append(h) g_list.append(g) for x in h_list: t += g_list.count(x) print(t)
import click def print_all_warning(ctx, param, all): if all: r = click.confirm( ( "This will scrape all discussions from the forum.\n" "Are you sure you want to continue?" ), default=False, show_default=True, ) ...
from pulsar.api import Http404 from pulsar.apps.wsgi import handle_wsgi_error from .utils import wait class GreenWSGI: '''Wraps a WSGI application to be executed on a :class:`.GreenPool` ''' def __init__(self, middleware, pool, response_middleware=None): if not isinstance(middleware, (list, tuple...
from .siren import *
from bob.ami import AMI, STOPPED import time class AmiManager(AMI): def __init__(self, **args): self.AMIs = {} # Map<TAG,AMI> super(AmiManager, self).__init__(interval=0.1, **args) def onInterval(self): self.__cleanDeadThreads() def onStop(self): threadNames = self.AMIs...
import logging try: import beanstalkc except (ImportError, SyntaxError): # Hey, we're on python 3, let's load our fixed version! import azuki.beanstalkc as beanstalkc from functools import wraps import json from collections import defaultdict import os beanstalks = {'default': {'host': '127.0.0.1', 'port':...