text
stringlengths
38
1.54M
# !/usr/bin/python # Finalized group 1 code # COMPILED BY HANG and ANDRES # # # STEP 1: YUN TAO # This step is independent from STEP 1 and STEP 2 # Blasts the ebola genome against the human genome # Return hits for STEP 4 import os def ebola_conservative_regions (infile, outfile): current_region =0 for line...
from ..advans import * from ..core.shader import calc_viewdir @ti.data_oriented class SSR: def __init__(self, res, norm, coor, mtlid, mtltab, taa=False): self.res = tovector(res) self.img = ti.Vector.field(4, float, self.res) self.nsamples = ti.field(int, ()) self.nsteps = ti.field...
from analytics.lib.counts import CountStat from analytics.lib.fixtures import generate_time_series_data from zerver.lib.test_classes import ZulipTestCase # A very light test suite; the code being tested is not run in production. class TestFixtures(ZulipTestCase): def test_deterministic_settings(self) -> None: ...
import random import sys def check_if_player_is_dead(): if Current_hit_point == 0: print("You have died.") sys.exit() def skeleton_damage(skeleton_hitpoints): player_damage = random.randint(1, int(potential_attack_damage)) print("You deal " + str(player_damage) + " damage towards the ske...
#Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial. Exemplo: #5! = 5 x 4 x 3 x 2 x 1 = 120 from math import sqrt fatorial f = factorial(x) x = int(input('\033[1;34mDigite um número para calcular seu Fatorial:\033[m ')) print('Calculando {}! = '.format(x), end='') total = x whi...
import numpy as np from sklearn import metrics import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os.path import numba class RBFN(object): def __init__(self, experiment_id, in_dim, basis_fxns): self.id = "{}.txt".format(experiment_id) self.in_dim = in_...
#!/usr/bin/python import sys import os # import time import fcntl import struct import socket import subprocess # These modules will be loaded later after downloading iniparse = None psutil = None def kill_process(process_name): for proc in psutil.process_iter(): if proc.name == process_name: ...
from data_generator.tokenizer_wo_tf import EncoderUnitOld class EncoderForNLI(EncoderUnitOld): def __init__(self, max_sequence, voca_path): super(EncoderForNLI, self).__init__(max_sequence, voca_path) CLS_ID = self.encoder.ft.convert_tokens_to_ids(["[CLS]"])[0] SEP_ID = self.encoder.ft.con...
from django.shortcuts import render from rest_framework import viewsets from restapp.serializers import TaskSerializers from restapp.models import Task from rest_framework import filters # Create your views here. class TaskViewSet(viewsets.ModelViewSet): # replaced by filters queryset = Task.objects.all().orde...
import core.ffmpeg_decoder as fd import core.sub_generator as sg import core.spectrum as sp from core.naive_vad2 import * import VLC.vlc_wx as vlc_wx import sys import wx class MainFrame(vlc_wx.MyFrame): def __init__(self,title): fram=vlc_wx.MyFrame.__init__(self,title) self.subtitle=None ...
# -*- coding: utf-8 -*- """ Purpose ======= ogs5py is A python-API for the OpenGeoSys 5 scientific modeling package. The following functionalities are directly provided on module-level. Subpackages =========== .. autosummary:: :toctree: api fileclasses reader tools Classes ======= OGS model Base Clas...
s = input() V = ['a','e','i','o','u'] l = [] for x in s: if x in V: s = s.replace(x,'') print(s)
from __future__ import absolute_import from __future__ import division from __future__ import print_function import ops import data import utils import models import argparse import numpy as np import tensorflow as tf import image_utils as im from glob import glob """ param """ parser = argparse.ArgumentParser(descr...
''' By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles. Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution. ''' def countRectangles(x, y): x, y = x+1, y+1 totalCombos = 0 ...
class FifoQueue(list): capacity = 20 def enqueue(self, item): if len(self) < self.capacity: self.append(item) def dequeue(self): if self: result = self.pop(0) else: result = None return result @property def available_spots(self)...
import os from flask import Flask, jsonify, request from flask_restful import Api, Resource from Train import train_model from sklearn.externals import joblib app = Flask(__name__) api = Api(app) if not os.path.isfile('pcod1final.model'): train_model() model = joblib.load('pcod1final.model') class MakePrediction...
from flask import Flask, jsonify, json, request from cryptography.fernet import Fernet app = Flask(__name__) #create a key in python #key = Fernet.generate_key() key = "MZ8Z4I6XHzd_jx1M8hMs6K8WS2SIGCsrMSMK5oZkKnw=" crypto = Fernet(key) def encrypt(plain_text): # convert plain_text to string string_text = str(plain...
# -*- coding: utf-8 -*- """ Created on Mon May 30 18:31:06 2016 @author: marioromero """ import areas lados = [1,2,3,4,10,100,500] for lado in lados: print("Area del cuadrado de lado {} es {}".format(lado,areas.cuadrado(lado))) for radio in lados: print("Area del cirulo de radio {} es {}".format(radio,a...
# Read an integer . For all non-negative integers i < N , print i2. See the sample for details. if __name__ == '__main__': n = int(input()) for x in range(n): print(x*x)
#functions in python #dont repeat code #cleans up code #can be reused elsewhere def say_hi(): print('Hi!') say_hi() print() #return values from functions def say_hi2(): return 'Hi!' greeting = say_hi2() print(greeting) print() #create function that returns list of even numbers from 1 to 50 (not including 50...
import os import random from shutil import copyfile """ """ def getDirAndFileDict(imgDir): # Get subdirectories dirTree = list(os.walk(imgDir)) subDirs = dirTree[0][1] corrFiles = dirTree[1:] dirFileDict = {} for subDir, files in zip(subDirs, corrFiles): dirFileDict[subDir] = f...
# https://codeforces.com/problemset/problem/1/A import math data = input().split() print(math.ceil(int(data[0]) / int(data[2])) * math.ceil(int(data[1]) / int(data[2])))
#!/usr/bin/env python #-*- coding:utf-8 -*- import unittest from paa_code.big_numbers_multiplication import Karatsuba class KaratsubaTest(unittest.TestCase): def test_divide_number_in_two_parts(self): number = 12345 k = Karatsuba() (left_part_returned,right_part_returned) = k.divide_num...
from cmd import Cmd class Node: def __init__(self,data): """ This constructor is to initialise the node object with data for the node and an empty dictionary denoting the children of the current node :param data: This accepts a string which will be the name of the directory ...
""" Constant values for recovery/BTC """ import decimal import sys PY3 = sys.version_info.major > 2 SATOSHI_PER_BTC = decimal.Decimal(1e8) MAX_BIP125_RBF_SEQUENCE = 0xfffffffd # BIP32 hardened derivation flag HARDENED = 0x80000000 P2PKH_MAINNET = 0x00 P2SH_MAINNET = 0x05 P2PKH_TESTNET = 0x6f P2SH_TESTNET = 0xc4 ...
class RequestsConsumeBaseBackend(object): def consume_request(self, request, start_callback=None, success_callback=None, fail_callback=None): raise NotImplementedError
# entrada: numéro inteiro (n) # saída: fatorial deste número (n!) # entra com o numero num = int(input("Digite o valor de n:")) # indice i e variaveis i = 0 fatorial = 1 n = num # loop while i < num: fatorial *= n n -= 1 i += 1 print(fatorial)
import heapq import itertools import numpy as np __all__ = ['FixedToVariableCode', 'VariableToFixedCode', 'HuffmanCode', 'TunstallCode'] class FixedToVariableCode: """ Binary (prefix-free) fixed-to-variable length code. Let :math:`\\mathcal{X}` be the alphabet of some discrete source. A *binary f...
import numpy as np import keras import random, math import unittest class GeneralUtils(): def __init__(self): pass ''' Return True with prob Input: probability within [0, 1] Ouput: True or False ''' def decision(self, prob): assert prob >= 0, 'Probability should in the...
__author__ = 'shuai' class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if not s or len(s) % 2: return False def _comapare(left, right): if left == "(" and right == ")": return True eli...
# -*- coding: utf-8 -*- """ wendt_mitchell_p4.py Created on Sun Oct 15 19:23:05 2018 Created by: Mitchell Wendt Revised: 10/15/2018 People who helped me: Edward Hughes (base code as provided in lecture, help with setting up the differential equations and plotting the realistic pendulum) """ import numpy as...
from odoo import models, fields, api class hr_job(models.Model): _inherit = 'hr.job' approving_manager_id = fields.Many2one('hr.job',string='Approving Manager',index=True,on_delete="restrict")
def disable_autoreload(): pass def enable_autoreload(): pass def reload(): pass runtime = None def set_next_stack_limit(): pass def set_rgb_status_brightness(): pass
from scoring.score_components.physchem.mol_weight import MolWeight from scoring.score_components.physchem.tpsa import PSA from scoring.score_components.physchem.rot_bonds import RotatableBonds from scoring.score_components.physchem.hbd import HBD_Lipinski from scoring.score_components.physchem.num_rings import NumRings...
import logging import socket import struct import meta log = meta.log class SlimDiscovery(object): deviceid = meta.deviceid revision = meta.revision mac = meta.mac buffersize = 1024 def __init__(self, port=meta.SLIMPORT): self.port = port def pack(self): """byte pack a dis...
import unittest class ExampleTests(unittest.TestCase): def test_1(self): self.assertTrue(1==1)
class Person(): # 直接写到class中的属性叫类属性(可以通过类名直接调用) name = "lily" def __init__(self, name, age): # 写在init中的属性叫对象/实例属性 # self.name = name self.age = age # 1、调用类属性 # 类名.属性名 print(Person.name) # 2、对象属性的优先级高于类属性 # 当对象调用属性时,如果存在对象属性,直接使用对象属性;如 # 果不存在对象属性,去找相同名称的类属性;如果没有相同名称 # 的类属性,返回错误。 p1 =...
''' https://open.kattis.com/contests/kgvxvo/problems/8queens ''' board = [] def split(word): return [char for char in word] line1 = split(input()) line2 = split(input()) line3 = split(input()) line4 = split(input()) line5 = split(input()) line6 = split(input()) line7 = split(input()) line8 = split(input()) boar...
# 1. Write a recursive search function that receives as input an array of integers and a target integer value. This function should return True if the target element exists in the array, and False otherwise. def binary_search_recursive(arr, target, low, high): middle = (low + high) // 2 if len(arr) == 0: r...
print('The program supports three types of alerts, "namely danger zone", "humidity", and "temperature"') print('The temperature range is between 21 c (70 f) and 28 c (82 f)') print('The humidity range is between 40 and 70 percentage') humidity_high = 70 humidity_low = 40 temperature_high = 21 temperature_low = 28 while...
#!/usr/bin/python """#### LING 570: Homework #2 - Ryan Timbrook ############ NFA to DFA -> Converts an input NFA to an equivalent DFA Author: Ryan Timbrook Date: 10/18/2018 Format: nfa_to_dfa.sh input_file > output_file Ran as: $ nfa_to_dfa.sh hw3/examples/nfa1 > q4/ex2.fst1 $ nfa_to_dfa.sh hw3/examples/...
#get_age function takes integers def get_age(): age = int(input("Enter your age: ")) return (print("you are" ,age, "years old")) print(get_age()) #get_name function takes strings def get_name(): name = str(input("Enter youe name: ")) return (print("your name is",name,)) print(get_name()) #this functio...
#!/usr/bin/env python # # Copyright (c) 2012-2014 Poul-Henning Kamp <phk@phk.freebsd.dk> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above...
from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix from sklearn.datasets import make_blobs from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC from sklearn.cluster import KMeans import matplotlib.pyplot as plt import pandas...
"""Server exposing endpoints for uploading and downloading tracks, extracting their encodings and returning the mapped visual parameters """ import data_processor as dp import train import models import mapping_utils import commons import fma_utils from flask import Flask, request, jsonify, send_file from flask_cors ...
import os import sys import allure from allure_commons.types import AttachmentType from jproperties import Properties from pytest import fixture from selenium import webdriver PROJECT_ROOT = os.path.dirname(__file__) CHROME_DRIVER_DICT = { 'linux': os.path.join(PROJECT_ROOT, 'webdrivers/chrome/chromedriver_linux...
#! /usr/bin/env py.test-3 ''' Tests for the module realizing the XML storage using lxml. ''' __author__ = 'Russel Winder' __version__ = '1.2' __date__ = '2014-08-23' __copyright__ = 'Copyright © 2007, 2012. 2014 Russel Winder' __licence__ = 'GNU Public Licence (GPL) v3' import tempfile import sys from lxml.etree im...
import csv import sys import re def findWholeWord(w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search ##ENTRYPOINT l2s_file = sys.argv[1] og_file=sys.argv[2] #UNUSED og2_file=sys.argv[3] #UNUSED tax_id=sys.argv[4] # using the tax_id, extract org_id from levels2species. (extracting plant ...
#!/usr/bin/env python #USRP1 Address Definition MAC_ADDR_CSMA_ON = 65 MAC_ADDR_CSMA_TH = 66 MAC_ADDR_CSMA_BT_1L = 67 MAC_ADDR_CSMA_BT_1H = 68 MAC_ADDR_CSMA_BT_2L = 69 MAC_ADDR_CSMA_BT_2H = 70 MAC_ADDR_CSMA_BT_3L = 71 MAC_ADDR_CSMA_BT_3H = 72 MAC_ADDR_CSMA_BT_4L = 73 MAC_ADDR_CSMA_BT_4H = 74 MAC...
#!/usr/bin/python3 # -*- coding: utf8 -*- from marshmallow_jsonapi.flask import Schema, SchemaOpts, Relationship from marshmallow_jsonapi import fields #~ def dasherize(text): #~ return text.replace('_', '-') class HypervisorsSchema(Schema): id = fields.Str(dump_only=True) name = fields.Str() versio...
import numpy as np import cv2 import classification import constants from scipy.ndimage.measurements import label previous_detections = None windows = None hierarchy_of_windows = None last_heat_maps = [] heat_map_rolling_sum = None def slide_window(image_width, image_height, x_start_stop=[None, None], y_start_stop=...
#!/usr/bin/python3 """write to a CSV file""" import csv import requests import sys if __name__ == "__main__": users = requests.get("https://jsonplaceholder.typicode.com/users/" + sys.argv[1]) user = users.json().get("username") all_tasks = requests.get( "https://jsonplaceh...
import numpy as np class RocchioAlgorithm(object): def __init__(self): self.alpha = 1 self.beta = 0.75 self.gamma = 0.15 pass def run(self, doc_vectors, q_vector, evaluations): # split evaluations to relevant and not relevant D_r = [] D_nr = ...
""" The :mod:`pycircular.datasets` module includes utilities to load datasets, including methods to load and fetch popular reference datasets. It also features some artificial data generators. """ from .base import load_transactions __all__ = ['load_transactions']
# -*- coding: utf-8 -*- """ Project Euler Problem 14 ○ 正の整数に以下の式で繰り返し生成する数列を定義する. n → n/2 (n が偶数) n → 3n + 1 (n が奇数) 13からはじめるとこの数列は以下のようになる. 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 13から1まで10個の項になる. この数列はどのような数字からはじめても 最終的には 1 になると考えられているが, まだそのことは証明されていない(コラッツ問題) さて, 100万未満の数字の中でどの数字からはじめれば最長の数列を生成する...
import torch import math import matplotlib.pyplot as plt class RoundingNoGrad(torch.autograd.Function): """ RoundingNoGrad is a rounding operation which bypasses the input gradient to output directly. Original round()/floor()/ceil() opertions have a gradient of 0 everywhere, which is not useful when d...
""" Main module in optrsa project. Optimization of packing fraction of two-dimensional Random Sequential Adsorption (RSA) packings using Covariance Matrix Adaptation Evolution Strategy (CMA-ES). """ # TODO Read about docstrings and automatic documentation generation services like pydoctor import cma import sys impor...
#!/usr/bin/env python # # # Tutorial 10. Demonstration that the views are linked, but the # data is not. from tutorial9b import PlotFrame2 from enthought.chaco.tools.api import LineInspector class PlotFrame3(PlotFrame2): def _create_plot(self): container = super(PlotFrame3, self)._create_plo...
# # abc006 c # import sys from io import StringIO import unittest class TestClass(unittest.TestCase): def assertIO(self, input, output): stdout, stdin = sys.stdout, sys.stdin sys.stdout, sys.stdin = StringIO(), StringIO(input) resolve() sys.stdout.seek(0) out = sys.stdout.r...
"""Iterable functions""" import typing def it_erable(val: typing.Any) -> bool: """Determine if `val` is a non-string iterable Arguments: val {typing.Any} -- any value Returns: bool -- value is nont-string iterable """ return not isinstance(val, str) and hasattr(val, '__iter__') ...
# Copyright 2015 Google 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 by applicable law or ag...
# -*- coding: utf-8 -*- ''' Created on 2020.05.19 @author: Jiahua Rao, Weiming Li, Hui Yang, Jiancong Xie --no_parallel ''' import os import torch import warnings warnings.filterwarnings("ignore") from pathlib import Path if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() ...
# -*- coding: utf-8 -*- from sys import version_info def get_encodings(): encoding_list = [ ['ascii', '646, us-ascii', 'English'], ['big5', 'big5-tw, csbig5', 'Traditional Chinese'], ['big5hkscs', 'big5-hkscs, hkscs', 'Traditional Chinese'], ['cp037', 'IBM037, IBM039', 'English'], ...
import draw import argparse import math import copy import sys # a dictionary specifying required codeword counts. Ordered by version:correction:codewords ERROR_CORRECTION_DICT = { 1:{'L':19,'M':16,'Q':13,'H':9}, 2:{'L':34, 'M':28, 'Q':22, 'H':16}, 3:{'L':55, 'M':44, 'Q':34, 'H':26}, 4:{'L':80, 'M':64, 'Q':48, 'H'...
import numpy as np import math import random import cv2 from tkinter import filedialog import codecs import shutil import os filename = filedialog.askopenfile() dirold = filedialog.askdirectory() dirnew = (dirold +"/wallpaper") print(filename.name) class img(object): def __init__(self,file): self.file = f...
from __future__ import absolute_import import os from celery import shared_task from django.core import management from leonardo.decorators import catch_result from django.conf import settings @shared_task @catch_result def sync_search_indexes(): management.call_command('rebuild_index', interactive=False) #...
from django.conf import settings from django.contrib.auth.models import User from model_mommy import mommy from rest_framework.reverse import reverse from rest_framework.test import APITestCase from ...models import DOCUMENT_CLASSIFICATION, Example from .utils import (TestUtilsMixin, assign_user_to_role, create_defaul...
while ser_bytes: decoded_bytes = str(ser_bytes[0:len(ser_bytes)-2].decode("ascii")) t = decoded_bytes.split(' ')[0] p = decoded_bytes.split(' ')[1] b = decoded_bytes.split(' ')[2] g = decoded_bytes.split(' ')[3] current_time = datetime.datetime....
__author__ = 'artemr' initList = [[1], [2, 3, [4, [5, 6, 7], 8], [9]], 10, [11, [12], 13], 14] def get_flat(lVals): while any(isinstance(x, list) for x in lVals): tmp = [] for val in lVals: tmp.extend(val) if isinstance(val, list) else tmp.append(val) lVals = tmp[:] return...
# -*- encoding: utf-8 -*- # # Copyright © 2013 Julien Danjou # # Author: Julien Danjou <julien@danjou.info> # # 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/lice...
import cs50 import math cash = 0 while cash == 0: temp = cs50.get_float("Change owed: ") if temp > 0: cash = temp else: cash = 0 pennies = 1 nickels = 5 dimes = 10 quarters = 25 total = 0 cashLeft = round(cash * 100) # quarters total = math.floor(cashLeft / quarters) cashLe...
from selenium import webdriver from selenium.webdriver.firefox.options import Options import pandas as pd import csv import sys import json import os class DynamicScrapper: def __init__(self, config_path): self.data = DynamicScrapper.load_config_file(config_path) self.parent_XPATH = self.data["par...
import basebrowser import datetime import json class Scraper(object): def __init__(self): ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:31.0) Gecko/20100101 Firefox/31.0' self.reqheaders = [ ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Encoding'...
#Função que fará o cálculo da média, dado uma soma de notas. def calcularMedia(soma): qtdNotas = 3 media = soma/qtdNotas return media notas = [['Pedro', 4.5, 7, 9], ['Tiago', 9.4, 10, 8.6], ['Maria', 0, 5, 3.3]] #Variável que guarda a soma das 3 notas para o cálculo da média somaNotas = 0 #Variável que g...
#!/usr/bin/python import sys import ply.yacc as yacc sys.path.insert(0, '../lab-1-scanner') import scanner sys.path.insert(0, '../lab-3-syntax-tree') from AST import * scanner = scanner tokens = scanner.tokens precedence = ( ("nonassoc", "IFX"), ("nonassoc", "ELSE"), ("nonassoc", 'LESS_THAN', 'GREATER_THAN...
#!/usr/bin/env python import os import sys def cmp3(a, b): ''' cmp for python3 ''' return (a > b) - (a < b)
import math from typing import Set, Optional import gi from graph_tool import VertexPropertyMap, Vertex from zxopt.util import is_interactive gi.require_version('Rsvg', '2.0') from gi.repository import Rsvg import cairo from graph_tool.draw import graph_draw from zxopt.data_structures.diagram.diagram import VERTEX...
import requests from bs4 import BeautifulSoup source = requests.get('https://ua.sinoptik.ua').text # print(source) soup = BeautifulSoup(source, 'lxml') # print(soup.prettify()) location = soup.find('h1', class_='isMain').text.lstrip() # print(location) for day in soup.find_all('div', class_='main '): day_nam...
#coding=utf-8 f=open('ecshop_url_txt') f2=open('rs.txt','w') tmp=set() while 1: line=f.readline() tmp.add(line) if line =='': break for x in tmp: f2.write(x) f.close() f2.close()
import re # a1 = '12.12.2000' # a2 = '1.1' # a3 = '1' # # print(re.match("[0-9]+.[0-9]+.[0-9]+", a1)) # print(re.match("[0-9].[0-9].[0-9]", a2)) # print(re.match("[0-9].[0-9].[0-9]", a3)) text = "a123b45с6d" exp = r'(\d+)' # Тут напишите своё регулярное выражение print(re.findall(exp, text))
def main(): with open('domain.txt', 'r') as f: domains = f.read().split('\n')[0:-1] while 1: input_domain = input() if not input_domain: break loc = find_str('.', input_domain) count = input_domain.count('.') start = 0 while start < count: ...
# ######################################################################### # Copyright (c) 2018, UChicago Argonne, LLC. All rights reserved. # # # # Copyright 2018. UChicago Argonne, LLC. This software was produced # # under U.S. Gov...
from sense_hat import SenseHat from time import sleep sense = SenseHat() white = (255,255,255) red = (255,0,0) purple = (255,0,255) ball_position = [4,4] ball_velocity = [1,1] ball_velocity2 = [-1,-1] ball_position2 = [3,3] sense.set_pixel (0,0,purple) bat_y = 4 def draw_bat(): sense.set_pixel(0, bat_y, ...
"""Auxiliary utils for implementing pruning strategies """ from collections import OrderedDict, defaultdict import torch from torch import nn from ..models.head import get_classifier_module def hook_applyfn(hook, model, forward=False, backward=False): assert forward ^ backward, \ "Either forward or bac...
import csv with open('grades.csv') as csvfile: lines = csv.DictReader(csvfile) for line in lines: with open('rating_cat.csv', mode='a') as rating_file: if (line['rating'] > "1" and line['rating'] <="2.5"): rating_writer = csv.writer(rating_file, delimiter=','...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jedisite', '0005_auto_20160107_2136'), ] operations = [ migrations.RemoveField( model_name='decks', ...
import Queue, copy from itertools import tee, izip from collections import defaultdict # Pairing tool # def pairwise(iterable): a,b = tee(iterable) next(b,None) return izip(a,b) # Cartesian X-Y Point # class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(...
import biorbd from time import time from biorbd_optim import ( OptimalControlProgram, ProblemType, Bounds, QAndQDotBounds, InitialConditions, ShowResult, ) def prepare_ocp(biorbd_model_path, final_time, number_shooting_points, nb_threads): # --- Options --- # biorbd_model = biorbd.Mod...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Functions to compute the entropic complexity of a given objective function. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import (ascii, bytes, chr, dict, filter, hex, input, int, ...
import sys fname = sys.argv[1] pattern = sys.argv[2] outprefix = sys.argv[3] n = 0 with open(fname) as f: outf = open(outprefix + str(n),'w') for l in f: if pattern in l: n += 1 outf.close() outf = open(outprefix + str(n),'w') outf.write(l) outf.close()...
import requests from basic import Basic class Menu(object): def __init__(self): pass def create(self, postData, accessToken): postUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % accessToken # if isinstance(postData,unicode): urlResp = requests.post(postU...
# -*- encoding: utf-8 -*- ''' @File : 661-图片平滑器.py @Time : 2021/08/13 22:42:36 @Author : TYUT ltf @Version : v1.0 @Contact : 18235121656@163.com @License : (C)Copyright 2020-2030, GNU General Public License ''' # here put the import lib from typing import List ''' 包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一...
""" This module contains the functions necessary to extract a thumbprint for a given image. When run in main, plots the thumbprint generated by sys.argv[1] """ import skimage.filters as skfill import skimage.morphology as skmorph import skimage.measure as skmeasure import skimage.exposure as ske import matplotlib.pypl...
#encoding=utf8 default_macros = { "1":"\u2776", "2":"\u2777", "3":"\u2778", "4":"\u2779", "5":"\u277a", "6":"\u277b", "7":"\u277c", "8":"\u277d", "9":"\u277e", "fig":'![](/files/images/.png "")', "next":'`ref:fig-next`', "prev":'`ref:fig-prev`', "tip":'> **TIP**\n\n> ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 29 15:14:31 2018 @author: kazeem """ import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import sys from pathlib import Path import time import cv2 """ Usage: python webcam.py <name of person> <number of photos> Example usage: python webcam.py claudia 10 """ def take_photos(person, num): """ Takes <num> number of photos and saves them to the images/<person> directory Args: ...
import csv import sys f = open('test.csv', 'rt') try: reader = csv.reader(f) for row in reader: parts = row.split(","); id, timestamp, year, day, holidays, local_event, item_id, price = parts; print(id); finally: f.close()
import os import dbus import common import util from service import Characteristic, Descriptor from settings import Settings class TimeUpdateCharacteristic(Characteristic): def __init__(self, service, settings: Settings): self.notifying = False self.settings = settings Characteristic....
""" Application: SumZero Author: Roland Zhou This is the top level script to run the Flask app so that all imports are global from the top `sum_zero` module. If the app is run from within the sum_zero/__init__.py, Python will not detect sum_zero as a package. The `config.py` module must also be in the root directory ...
#!/usr/bin/env python3 # -*- mode: python -*- # -*- coding: utf-8 -*- # 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...