text
stringlengths
8
6.05M
N = int(input()) for i in range(N): a = input().split() r, s = int(a[0]), a[1] ans = '' for k in s: ans += k*r print(ans) # Done
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT...
def tarjan(grafo): '''Restituisce il vettore delle componenti fortemente connesse del grafo diretto fornito come parametro, in tempo O(n + m).''' def dfs(nodo): nonlocal tempo, componente tempo += 1 componenti[nodo] = -tempo stack.append(nodo) min_nodo = tempo ...
# import the necessary packages from optparse import OptionParser from scipy.spatial import distance as dist import matplotlib.pyplot as plt import numpy as np import argparse import glob import cv2 import sys import pickle ########################### def image_match_histogram( all_files, options ): histograms = {...
import re #Check if the string starts with "The" and ends with "Spain": txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) if (x): print("YES! We have a match!") else: print("No match") import re str = "The rain in Spain" #Check if the string starts with "The": x = re.findall("\AThe", str) print(x)...
import os from PIL import Image from numpy.ma import cos, sin, arccos from pylab import * from scipy.constants import pi def process_image(imagename,resultname,params="--edge-thresh 10 --peak-thresh 5"): """ Process an image using sift and save the results in a file. """ if imagename[-3:] != 'pgm': #...
# ############################### # Michael Vassernis - 319582888 # ################################# import nn_model as nn_mdl from helper_functions import load_mnist, accuracy_on_dataset, load_model, save_model import numpy as np import matplotlib.pyplot as plt import sys import time def train_classifier(train_se...
#!/usr/bin/env python ''' Expermiental Python Server backend test ''' import os import sys root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(root_dir) sys.pycache_prefix = os.path.join(root_dir, 'dist', '__pycache__') netron = __import__('source') test_data_dir = os.path.join(ro...
from panda3d.core import Point3, Vec3, NodePath, LineSegs, Vec4, \ CollisionTraverser, CollisionHandlerQueue, CollisionBox, CollisionNode, \ BitMask32, KeyboardButton from .BoxTool import BoxAction, ResizeHandle from .ToolOptions import ToolOptions from bsp.leveleditor.selection.SelectionType import SelectionM...
import time val = [3, 34, 4, 12, 5, 2] #wt = [10, 20, 30] summ = 9 n = len(val) # by Dynamic programing def knapsack(val,W,n): array = [[-1 for j in range(W+1)]for i in range(n+1)] #print("array",array) if W == 0 or n == 0: return 0 if array[n][W] != -1: return array[n][W] if val[n-1] <= W: array[...
""" # 哈希表 1. 使用链表解决哈希表的冲突 2. 使用哈希表+链表实现LRU cache查询复杂度为O(1) 哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构。 也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。 这个映射函数叫做散列函数,存放记录的数组叫做散列表。 """ import os import logging logger = logging.getLogger(__name__) class Dict(object): """hash table --- 类似位于字典数据结构""" def ...
def func(): print("I imported v2 of surf")
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, JsonResponse from models import GenericTask import json import datetime
class Seller: username: str password: str token: str goodsId: str orderId:str
""" У вас есть 2 компании с людьми. Одна из компаний пусть будет это global_logic была поглощена компанией toshiba. Отобразите это в коде. Учитывайте что люди с одинаковыми именами могут быть в обеих компаниях """ global_logic = ['John Dow', 'John Snow', 'Arya Stark'] toshiba = ['Robin Williams', 'John Snow', 'Taylor ...
import nltk from jiwer import wer import sys evaluation_data = {'ted': 'data/translated-ted/valid', 'asistent': 'data/asistent-testset/asistent_testset', 'general': 'data/translated-general/valid'} base_translation_path = "data/translated-" def evaluate_one(translation_path, valid_path): hypoth...
import xml.etree.ElementTree as ET import os import math cwd = '/media/zs/wisin_linkdata/mk/shadowk/Annotations/' # newcwd = 'newAnnotations/' newcwd = '/media/zs/wisin_linkdata/mk/shadowk/Annotations/' for path,d,filelist in os.walk(cwd): for xmlname in filelist: if xmlname.endswith('xml'): ...
""" 当父类方法无法满足子类需要时,就可以重写父类方法 如何重写? 就是在子类中重新定义一个和字类同名的方法并且实现它 """ class Dog: def bark(self): print("汪汪。。。") class Xiaotianquan(Dog): def bark(self): print("叫的和神一样") def fly(self): print("i can fly。。。") xtq = Xiaotianquan() xtq.bark()
from fractions import Fraction from math import factorial import random import itertools def cross(A, B): "O conjunto de formas de concatenar os itens de A e B (produto cartesiano)" return {a + b for a in A for b in B } def combos(items, n): "Todas as combinações de n items; cada co...
from nastran.analysis import AnalysisModel class BCType: def __init__(self, label, ids, desc): self.label = label self.ids = ids self.desc = desc class PanelBC: def __init__(self, bcs, label): self.bcs = bcs self.label = label def get_b...
import numpy as np import matplotlib.pyplot as plt import sys, os import keras import tensorflow from keras.models import Sequential, Model, model_from_json from keras.layers import Input, Dense, Activation import h5py import random import pprint import pickle import sklearn scalerfile = 'transformer_frontend_y_imgs....
#encoding=UTF8 ''' 典型的工厂模式,通过函数名直接调用实例 使用函数名调用函数实例用getattr() ''' import global_setting from conf import shell_get def get_cpu(): data=shell_get.get_cpu() print data return data def get_load(): data=shell_get.get_load() print data return data
import pandas as pd l1 = [{'name': 'John', 'job': "teacher"}, {'name': 'Nate', 'job': "student"}, {'name': 'Fred', 'job': "developer"}] l2 = [{'name': 'Ed', 'job': "dentist"}, {'name': 'Jack', 'job': "farmer"}, {'name': 'Ted', 'job': "designer"}] df1 = pd.DataFrame(l1, columns=['nam...
__author__ = 'apple' import os from osgeo import ogr daShapefile = r"/Users/apple/PycharmProjects/Shapefile/Shapefile/rice_ne-sim.shp" # Path Your Shapefile driver = ogr.GetDriverByName('ESRI Shapefile') dataSource = driver.Open(daShapefile, 0) # 0 means read-only. 1 means writeable. # Check to see if shapefile ...
from main.activity.activity_login import * from main.page.people.pe_people import * from main.page.setting.pe_user import * from main.page.setting.pe_user_notif import * from selenium import webdriver import time import unittest class TestEditPeople(unittest.TestCase): _site = "beta" # dictionary user di...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.naive_bayes import MultinomialNB from sklearn.ensemble import RandomForestClassifier fro...
from itertools import permutations max = 0 trazeni = set('123456789') for k in xrange(1, 5): for it in permutations('123456789', k): s = ''.join(it) n, i = int(s), 2 while len(s) < 9: s, i = s + str(n * i), i + 1 if len(s) == 9 and set(s) == trazeni and int(s) > max: max = int(s) ...
# reverse an array # using the minus index a = [1,2,3,4,5,6] b = [] for i in a: b.append(a[-i]) print b # string array using the loop x = ['Ankit','Jasmeet','Sandip','Ganesan','Balaji'] y = [] for i in range(len(x)): y.append(x[len(x) - 1- i]) print y # string array using string inbuilt fun...
from django.shortcuts import render from django.views.generic import ListView from .models import SavedBooks # Create your views here. class SavedBooksView(ListView): model = SavedBooks template_name = 'saves.html'
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class CfeBindings(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017615',...
import pyautogui import cv2, numpy as np from PIL import Image import BoardSolver topLeftLocation = pyautogui.locateCenterOnScreen("TopLeft.png") bottomRightLocation = pyautogui.locateCenterOnScreen("BottomRight.png") sudokuGrid = [[0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0...
import pandas as pd import numpy as np site_id = 1058 df = pd.read_csv('/Users/coralietouati/PycharmProjects/Project1/' + str(site_id) + '_risk.csv') df_filtered = df[(df['operating year'] == 1)] percentile = df_filtered.ess_kW_savings.quantile(0.5) df_filtered['Delta_percentile'] = df.apply( lambda row: row['ess_kW...
def get_size(w, h, d): return [2 * (w * h) + 2 * (w * d) + 2 * (h * d), w * h * d]
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################## ## This script uses vaex and dask for fast subsetting of ranges from QTLtools nominal output files. ################################################## ## Author: Heini M. Natri ## Date: Nov 15 2019 ## Email: heini.natri@gmail...
# Generated by Django 2.2.6 on 2019-12-01 22:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0025_auto_20191201_2141'), ] operations = [ migrations.AlterField( model_name='routine', name='day', ...
# -*- coding: utf-8 -*- class Solution: def countPoints(self, rings: str) -> int: red, green, blue = set(), set(), set() for i in range(0, len(rings), 2): color, rod = rings[i], int(rings[i + 1]) if color == "R": red.add(rod) elif color == "G": ...
#Name: Eoin Stankard #Date: 24/04/2019 #Description: Project on the Iris Data Set #****************************************************************************** #References: # https://gist.github.com/curran/a08a1080b88344b0c8a7 # https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html # https://s...
import pylab as pl import numpy as np from scipy import ndimage from scipy.stats import multivariate_normal import sys #img2 = pl.imread("converse2.jpg") #img2 = pl.imread("obraz.png") img2 = pl.imread(sys.argv[1]) s = img2.shape print ("Min: {}, max: {}".format(np.min(img2),np.max(img2))) for i in range(0, s[0]): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models import sys class UnicodePython2e3(object): if sys.version_info[0] >= 3: # Python 3 def __str__(self): return self.__unicode__() else: # Python 2 def __str__(self): ...
''' zhuliwen: liwenzhu@pku.edu.cn October 24,2019 ref: https://github.com/weiaicunzai/pytorch-cifar100 ''' from AI_homework_1 import * import torch def test(pth_file): net = ResNet(BasicBlock, [2, 2, 2, 2]) net.load_state_dict(torch.load(pth_file)) net.cuda() print(net) net.eval() correct_1 = ...
#Leap Year def is_leap_year(year): if(year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)): return True else: return False is_leap_year(1996) is_leap_year(1900) is_leap_year(2444)
import requests from tqdm import tqdm # GET /delete {"id":'int', "modifier":'str'} # GET /update {"note_id":'int', "note":'str', "modifier":'str'} # GET /insert {"note_id":'int', "note":'str', "modifier":'str'} # GET /notes {"id":'int'} # GET /search {"database_search":'str'} [database_search, column_search, ...
from __future__ import print_function, absolute_import import logging import re import json import requests import uuid import time import os import argparse import uuid import datetime import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText from apache_beam.io.filesy...
"""If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile). """ km=float(input("Enter the kilometer: ")) time=float(input("enter the time in decimal: ")) op=((km/1.61)/(time/60)) print("t...
# Copyright (c) 2020. Yul HR Kang. hk2699 at caa dot columbia dot edu. import numpy as np from scipy.io import loadmat import h5py import os import pprint import pandas as pd #%% from lib.pylabyk import zipPickle as zpkl from lib.pylabyk.matlab2py import unpackarray, structlist2df from lib.pylabyk.np2 import dict_sh...
# -*- coding: utf-8 -*- """ Move data from ingestion to production """ ################# # IMPORTS from b2stage.apis.commons.cluster import ClusterContainerEndpoint # from b2stage.apis.commons.endpoint import EudatEndpoint from b2stage.apis.commons.b2handle import B2HandleEndpoint # from restapi.rest.definition impor...
#!/usr/bin/env python from __future__ import print_function import sys import argparse import rospy import mavros import time import math from tf.transformations import quaternion_from_euler from tf.transformations import euler_from_quaternion import tf from sensor_msgs.msg import Joy from std_msgs.msg import Header...
import logging import time from time import sleep from Acspy.Clients.SimpleClient import PySimpleClient client = PySimpleClient() supervisor = None logging.basicConfig() log = logging.getLogger() while True: try: supervisor = client.getComponent("ArraySupervisor") except Exception as e: log.i...
import unittest import sys import os sys.path.append(os.path.join('..', 'Src')) from Tagging import PartOfSpeechTagging from Tokenization import TextTokenization class TextTaggingTestCase(unittest.TestCase): def testTagging(self): sents = "Tom thinks John is terrible. John thinks Tom is great." speech...
""" A dynamic microsimulation framework"; """ from __future__ import annotations import typing import datetime import numpy as np import numpy.typing as npt import df # type: ignore import mpi # type: ignore from . import time import stats # type: ignore from .domain import * date_t = datetime.datetime | datetime.da...
import gevent from gevent import monkey import requests import time start_time = time() monkey.patch_all() urls = ['http://www.dictionary.com/browse/sit', 'http://phrasefinder.io/search?corpus=eng-us&query=The cat perched'] def print_head(url): print('Starting %s' % url) data = requests.get(url).text p...
from __future__ import division from __future__ import print_function import time import os import json # Train on CPU (hide GPU) due to memory constraints os.environ['CUDA_VISIBLE_DEVICES'] = "" import tensorflow as tf import numpy as np import scipy.sparse as sp import matplotlib.pyplot as plt from s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import os import sys import subprocess import cgruutils def processMovie( i_file): out = dict() out['infile'] = i_file if not os.path.isfile( out['infile']): out['error'] = 'Input file does not exist.' return out params = {...
#!/usr/bin/python # TODO: # Send multiple ping requests for each neighbor and then take the average # Update the return message format import sys import os import subprocess from neighbors import my_neighbors from process_topology import ip_prefix2site_prefix interest = sys.argv[1] site = interest.split("/script")[0...
import unittest from katas.kyu_7.greatest_common_divisor import mygcd class MyGCDTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(mygcd(30, 12), 6) def test_equals_2(self): self.assertEqual(mygcd(8, 9), 1) def test_equals_3(self): self.assertEqual(mygcd(1, 1)...
from TxtVenture.tools.implementations import * from TxtVenture.generic.worldspace import WorldSpace class TestRoom(WorldSpace): """ A test room to play around with. """ def __init__(self, id, temp): super(TestRoom, self).__init__(id, temp) def main(self): respond(self.description) ...
import sys import os import shutil import subprocess import functools sys.path.insert(0, 'scripts') sys.path.insert(0, 'tools/families') sys.path.insert(0, 'tools/trees') import experiments as exp import fam import create_random_tree from ete3 import Tree import re def treat_amalgamation(amalgamation, datadir, family...
# -*- coding: utf-8 -*- # Copyright 2013-2020 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later common_globals = {} execfile_('common.py', common_globals) MODEL_VERSIONS = { u'CP920': u'78.84.0.125', u'CP960': u'73.84.0.25', u'T19P_E2': u'53.84.0.125', # 53.84.0.90 ver...
# -*- coding: utf-8 -*- import importlib from django.dispatch import receiver from django.conf import settings from django.test.signals import setting_changed from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ from crispy_forms.helper import FormHelper fr...
#!/usr/bin/env python # script for drawing algorithm result import argparse from math import ceil, floor import random import warnings # drawing shapes import turtle as t # save turtle to file import Tkinter as tk parser = argparse.ArgumentParser(description = 'Draw layout of small boards on big board.') parser.a...
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse # Create your views here. def index(request): return render(request, "personal/index.ht...
# Copyright (c) 2015 Mellanox 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 # # U...
import werobot from werobot.session.filestorage import FileStorage import sys robot = werobot.WeRoBot(token='ZeroAI') @robot.text def hello(message): return '维护中,预计北京时间2022-12-11 23点恢复。' robot.config['HOST'] = '0.0.0.0' robot.config['PORT'] = 80 robot.run()
import pandas_datareader.data as webdata from datetime import date import numpy as np from scipy import signal import matplotlib.pyplot as plt from scipy import fftpack from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator from dateutil.relativedelt...
#!/proj/sot/ska3/flight/bin/python # #--- this script fix wrong temperature limit #--- #--- May 10, 2021 #--- import os import sys import re import string import time import numpy import astropy.io.fits as pyfits from astropy.io.fits import Column import Chandra.Time # #--- reading directory list # path = '/da...
import json import marshmallow as ma from datetime import datetime from webargs import fields __all__ = [ 'Str', 'Int', 'Bool', 'List', 'DelimitedList', 'Nested', 'Timestamp' ] Str = fields.Str Float = fields.Float Int = fields.Int Bool = fields.Bool List = fields.List DelimitedList = fields.DelimitedList Nested ...
from django.db import models # Create your models here. class Category(models.Model): name=models.CharField(max_length=64) def __str__(self): return f"{self.name}" class Regular_pizza(models.Model): name=models.CharField(max_length=64) small=models.DecimalField(max_digits=4,decimal_places=2) ...
from knowledge_graph import app import json from json import dumps, load from flask import request, make_response, abort, Response from knowledge_graph.Mind import Mind value_id_map = { 1 : "conformity", 2 : "tradition", 3 : "benevolence", 4 : "universalism", 5 : "self-direction", 6 : "sti...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2015-2018 Shenzhen Auto-link world Information Technology Co., Ltd. All Rights Reserved Name: Config.py Purpose: Created By: Clive Lau <liuxusheng@auto-link.com.cn> Created Date: 2017-01-01 Changelog: Date Desc 2017-01-01 ...
import cv2 import sys #import pygame #i'm using pygame beacause he is too cute but nobody likes him. I feel sad about that cute python library cascPath = sys.argv[1] eyecaspath = sys.argv[2] faceCascade = cv2.CascadeClassifier(cascPath) eye_cascade = cv2.CascadeClassifier(eyecaspath) video_capture = cv2.VideoCapture(0...
# sudo CFLAGS=-stdlib=libc++ python3 maml.py import argparse import random import pandas as pd import pickle import numpy as np import torch from torch import nn, optim from torch.nn import functional as F from torch.utils.data import DataLoader import learn2learn as l2l import torchtext from torchtext.datasets imp...
# -*- coding: utf-8 -*- """Tests for utmp files.""" import unittest from dtformats import utmp from tests import test_lib class LinuxLibc6UtmpFileTest(test_lib.BaseTestCase): """Linux libc6 utmp file tests.""" # pylint: disable=protected-access def testDebugPrintEntry(self): """Tests the _DebugPrintEnt...
# Generated by Django 2.1.7 on 2019-04-20 06:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('amazon', '0007_auto_20190420_1209'), ] operations = [ migrations.RenameField( model_name='women_shops_clothes', old_name='pr...
import sys import os f = open("C:/Users/user/Documents/python/ant/import.txt","r") sys.stdin = f # -*- coding: utf-8 -*- MAX_N = 100000 N = int(input()) S = list(map(int,input().split())) T = list(map(int,input().split())) itv = [0] * N for i in range(N): itv[i] = (T[i],S[i]) itv.sort() ans...
################################################# #Introduction to Python Programming Constructs # #Csci 1913 # #Author(s): # #Date: # # # ####################...
import tensorflow as tf def lstm(input_feature=1000, output_feature = 46): model = tf.keras.Sequential([ tf.keras.layers.Embedding(input_feature, 80), tf.keras.layers.LSTM(80), tf.keras.layers.Dense(output_feature, activation='sigmoid') ]) model.compile(loss='categorical_crossentr...
for x in range(1, 11): for y in range(1, 11): if y <= x: print(x*y, end = ' ') print("\r")
import os import sys sys.path.append('..') sys.path.append('../..') import argparse import utils from student_utils import * """ ====================================================================== Complete the following function. ====================================================================== """ import ...
from image_diet.test_diet import DietTest from image_diet.test_commands import DietCommandTest
tabela = ('Atlético-PR', 'Atlético-GO', 'Atlético-MG', 'Bahia', 'Botafogo', 'Ceará SC', 'Corinthinas', 'Coritiba', 'Flamengo', 'Fluminense', 'Fortaleza', 'Goiás', 'Grêmio', 'Internacional', 'Palmeiras', 'Bragantino-SP', 'Santos', 'Sport Recife', 'São Paulo', 'Vasco da Gama') print('-=' * 1...
# -*- mode: python -*- import os import shutil for root, dirs, _ in os.walk("."): for d in dirs: if d == '__pycache__' and os.path.isdir(os.path.join(root, d)): shutil.rmtree(os.path.join(root, d)) block_cipher = None a = Analysis( ['ACExplorer.py'], pathex=['D:\\Programs\\AC-Explorer'], binaries=[], datas=...
import json import responses from changes import packaging, vcs from . import context, setup, teardown def test_commit_version_change(): vcs.commit_version_change(context) def test_tag_and_push(): vcs.tag_and_push(context) @responses.activate def test_github_release(): responses.add( responses...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class VinciaToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f01761...
from django.db import models from taggit.managers import TaggableManager # Create your models here. # Blog Post Model class Blogpost(models.Model): title = models.CharField(max_length=250) tags = TaggableManager() image = models.ImageField(upload_to='post/', blank=True, null=True) description = models...
from dataclasses import dataclass, astuple from copy import deepcopy @dataclass class Pos: y: int x: int def __hash__(self): return hash(astuple(self)) def __add__(self, other): return Pos(y=self.y + other.y, x=self.x + other.x) def __lt__(self, other): return astuple(sel...
import os import pickle class ConfigKeyError(Exception): def __init__(self, this, key): self._key = key self._keys = this.keys() def __str__(self): return "Key \"{}\" not found. Available Keys : {}".format(self._key, self._keys) class ConfigDict(dict): config_dir...
from django.contrib import admin from .models import Roaster # Register your models here. admin.site.register(Roaster)
import pandas as pd import numpy as np import matplotlib.pyplot as plt import pylab as pl import seaborn as sns #load page_views and page_edits df_edits = pd.read_csv('pageedits_agg_subset.txt', sep="\t", header=None, names=["article","article_id","page_size","num_revisions", ...
DEFAULT_DISCOUNT_PERCENT = 5 # Процент скидки по бонусной карте BONUS_CARD_NUMBER_LEN = 15 BONUS_CARD_EMBOSSED_LEN = 6 CARD_SEARCH_MAP = { BONUS_CARD_EMBOSSED_LEN: 'embossed_number', BONUS_CARD_NUMBER_LEN: 'number', } LOGGER_NAME = 'errors' CEILING = 50 # Рублей - кратность, до которой необходимо округлять
import os import sys import re class Worker: def __init__(self): self.job = "." self.timeRemaining = 0 def setup(): global fileHandle, fileData filename = input("Enter an input file name (default input2.txt): ") if filename == "": filename = "input2.txt" exists = os.path....
''' Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must be unique. The result can be in any order. ''' class Solution: def inter...
# 递归,写好伴随条件 # 0需要特殊处理一下 # 直接a class Solution: def restoreIpAddresses(self, s: str) -> List[str]: self.res = [] if len(s) > 12: return self.res def recur(s:str, cnt:int, temp:str): # 此次划分不合要求,加快收敛 if len(s) > (4-cnt)*3: return ...
#!/usr/bin/env python # coding: utf-8 # # Assignment 4 Day 4 # Q.1 Find all occurences of substring in given string and print index. # # Input String: " what we think we become; we are python programmer" # In[10]: mainStr = 'what we think we become; we are python programmer' substring = 'we' print('substring is...
import exceptions import os import time import datetime from wnodes.utils import utils class MessageStoreError(exceptions.Exception): pass class MessageFormat(object): header = 'APEL-cloud-message: v0.1' def __init__(self, records_list = []): self.records_list = records_list[:] def add_rec...
import numpy as np import pandas as pd import datetime import data_examples import feature_engineering import pipeline if __name__ == '__main__': print(pipeline.predict_cao( data_examples.CHARGE_CHEMISTRY, data_examples.LIMESTONE_CONSUMPTIONS, data_examples.CHARGE_CONSUMPTIONS, dat...
import requests import re from config import * from requests.packages import urllib3 urllib3.disable_warnings() def get_status_response(ip_addr): url = 'https://' + ip_addr + ':2004/web/dynamic.php' data = dict(ref='/header', autostart=0, target='refreshAlarm', r=0) try: response = requests.get(...
# Generated by Django 2.2.7 on 2019-11-23 23:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('info', '0007_auto_20191123_1902'), ] operations = [ migrations.AlterField( model_name='compensa...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from typing import Any, Callable, Mapping from pants.base.parse_context import ParseContext from pants.util.frozendic...
from django.test import TestCase from elections.models import ElectedRole from elections.utils import ElectionBuilder from organisations.tests.factories import OrganisationFactory from .base_tests import BaseElectionCreatorMixIn class TestElectoralSystems(BaseElectionCreatorMixIn, TestCase): def test_scotland_lo...
from .drivers.driverchrome import DriverChrome from .drivers.driver import IDriver