index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
14,600
11de5a4dfbe123777d63ffac0827f353c79aa2a3
# https://www.hackerrank.com/challenges/bonetrousle def calc(n, k, b): if n > (k - b + 1 + k) * b / 2: print -1 return res = [n / b for _ in range(b)] for i in range(b / 2): res[i] -= b / 2 - i for i in range(b / 2, b): res[i] += i - b / 2 diff = n - sum(res) ...
14,601
7a5c3dbd25822773ec69260a497017de27ac08b5
from stackformation.aws.stacks import BaseStack from troposphere import ( # noqa FindInMap, GetAtt, Join, Parameter, Output, Ref, Select, Tags, Template, GetAZs, Export ) import troposphere.sqs as sqs class Queue(object): def __init__(self, name): self.name = name self.stack = No...
14,602
faee3ef0346b70498adf1ff014ca145bd3d64661
def test_after_sessionstart(status_plugin_debug): debug_data = status_plugin_debug["after_sessionstart"] assert debug_data["collect"] == [] assert debug_data["pass"] == [] assert debug_data["fail"] == [] assert debug_data["skip"] == [] assert debug_data["state"] == "start" def test_after_fir...
14,603
47cdb277a73aaff8df5031328e2883876bb81dad
""" Hack for getting a handle to the top-level google module, etc. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import google.protobuf.json_format as json_format import google.protobuf.message as message import google.protobuf.struct_pb2 as struct_pb...
14,604
d2721fa5f8b4b766ebf281b731c959ded73a0545
'''巧绘棋盘格''' #调用turtle模块 import turtle as t #绘制棋盘格的竖线,通过设置步长去改变每条竖线的起/终点坐标 for x in range(0, 181, 10): t.penup() t.goto(x, 0) t.pendown() t.goto(x, 180) #绘制棋盘格的横线,通过设置步长去改变每条横线的起/终点坐标 for x in range(0, 181, 10): t.penup() t.goto(0, x) t.pendown() t.goto(180, x) t.hideturtle() t.done() ...
14,605
ed898092b1066b060d8adb0519503fbe3162baaf
# -*- coding: utf-8 -*- from flask_script import Manager from c2 import app manager = Manager(app) @manager.option('-n', '--name',dest='name', default='nowcoder') def hello(name): print 'hello',name @manager.command def initialize_database(): 'initialize database' print 'database ...' if __name__ == ...
14,606
0c79293ac0e2ed4553aefe75fa67515fb19125b1
#!/usr/bin/env python import scipy.stats as stats from PIL import Image, ImageDraw from affine_transformation import * def barnsley_fen(n_i=200000): a = 5 points = [ PointGroup(square(a)) ] trans = [ array([[ 0 , 0 , 0 ], [ 0 , 0.16 , 0 ], [ 0 ...
14,607
1e884185769868ef57670fefee9164a92390b849
from django.contrib import admin from .models import Legume admin.site.register(Legume)
14,608
d46b4f6190169055dd4b376320783827f453ad19
from board_driver_simulator_v2 import open,close,but,pot,det,led import time """ 5. Zmodyfikować program tak aby korzystał z zapisu binarnego (argument funkcji „led”) """ try: open() while(True): #pętla nieskończona led(int('1001', 2)) time.sleep(0.25) led(int('110', 2)) time...
14,609
ee486f0f3f9994dbf0bf0002d18cec56b88ddd98
import random import torch from torch.utils.data import TensorDataset from tqdm import tqdm import numpy as np import settings def create_dataset(df, split=0.8, max_count=1e10): # remove year 2008 and 2020 horse_cols = ['horse_age', 'horse_weight', 'horse_speed_rating', 'horse_past_race', 'ho...
14,610
4b81ce26918ba08aed4807cc50d3758ee06dba1a
import img2pdf from PIL import Image import os # storing images path images = ["images/x.jpg", "images/y.jpg", "images/z.jpg", "images/apple-touch-icon.png"] #put pdf path here pdf_path = "file.pdf" #Writing images to file after converting them to binary with open(pdf_path,"wb") as f: f.write(img2pdf.conve...
14,611
debf0ee4f39a19876eae68cea2cb7caa4d715486
# -*- coding: utf-8 -*- """The parsers and plugins manager objects.""" import pysigscan from plaso.frontend import presets from plaso.lib import specification class ParsersManager(object): """Class that implements the parsers manager.""" _parser_classes = {} @classmethod def DeregisterParser(cls, parser_c...
14,612
878b449a69805e34d28be822bc45eccfb2609c2f
#!/usr/bin/env python # # License: BSD # https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE # ############################################################################## # Documentation ############################################################################## """ A py_trees demo. .....
14,613
dbdd5d238be3540888387d7e2b1b09e76d02cc17
class Module(): def performOperation(self, module, operation, bot): pass
14,614
d6a57391fade9ffa36835728798cd3152d879c2a
# Addition: sumz = 2+3 print('Sum=', sumz) # Subtraction: diff = 3-2 print('diference=', diff) # Multiplication: product = 3*2 print('product=', product) # Division quotient = 5/2 print('quotient=', quotient) # exponent, 4 to the power of 2, 4 squared result = 4**2 print('4 to the power of 2 is', result) minMultiply =...
14,615
77ea817526d788629e0ef1bddcdfff8a04920768
# basics_test.py # write a script that # 1) constructs a list 4 of (arbitrary) 3 dimensional coordinates x,y,z (floats) # 2) nicely print the list by iterating over the 4 list items xyz1 = [1,2,3] xyz2 = [4,5,6] xyz3 = [7,8,9] xyz4 = [10,11,12] list4 = [xyz1,xyz2,xyz3,xyz4] for item in list4: print "xyz = ", ite...
14,616
c985c97506eb9b448d6503e7ea4eec51eb093634
from django.shortcuts import render, redirect from csgames_quals import models def index(request): participants = models.Participant.objects.all() for participant in participants: participant.score = 0 for competition in participant.competitions.all(): if competition in participant...
14,617
50e3106357148697678a8df6e4227add2729dc84
/home/jtloong/anaconda3/lib/python3.6/_collections_abc.py
14,618
6759208ac2765b46db53d4c45442a09f257a6e49
''' from suds.client import Client import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) wsdl_url = "http://localhost:8002/notification.wsdl" client = Client(wsdl_url) ''' from flask import Flask, r...
14,619
226e0d42a9cfb2491f385033a29299bdce4ff00f
# 02_tuple_p.py tuple1 = (1, 2, 3, 4, "a", "b", "c") tuple2 = (1, 2, 3, 4) tuple3 = ("abc", "def") tuple4 = () tuple5 = tuple() aaa = tuple1 + ("a",) print(aaa) bbb = tuple1 * 3 print(bbb) print(tuple4) print(tuple5) tuple6 = 1,2,3,4 print(tuple6) print(type(tuple6)) a = tuple1[1] print(a)
14,620
28760fccd05f3b543b172e79676d7a314bd1b107
from django.db import models # Create your models here. class Todo(models.Model): # id is automatically included. task = models.CharField(max_length=100) done = models.BooleanField() order = models.IntegerField()
14,621
0e6f9da1e7cf1e26c49af2ff99e19e7a61727340
from Models.flowfrontPermBaseline import FF2Perm_Baseline, FF2Perm_3DConv from Models.flowfront2PermTransformer import OptimusPrime, OptimusPrime2, OptimusPrime_c2D from pathlib import Path import socket import torch import numpy as np import Resources.training as r from Models.sensor_to_fiberfraction_model import Atte...
14,622
e37a7259b0a1814f40e4ceae91df44cf473560f6
import os def get_graph_from_data(input_file): """ 从用户与item行为文件中,获取图结构 :param input_file: user item rating file :return: dict:{ UserA: {itema: 1, itemb: 1, itemd: 1}, UserB: {itema: 1, itemc: 1}, ... } """ if not os.path.exists(in...
14,623
8b596b4b8f70084dae3e2b9fb2ff76b0a2d2be01
import random import string import traceback from django.db import transaction from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect # Create your views here. from admins_app.models import User from home_page.models import Books from shopping_app.cart import Cart from shoppi...
14,624
a85aaf76fb327d1293a5fb823c4ca22cb0c1258e
from flask import Flask, render_template, redirect, url_for, request, session app = Flask(__name__) app.secret_key = 'wow' from surv.routes import * from surv.utils.filters import *
14,625
28bd55d23bb320cfa1e095cc897e7d8ebfeabaa5
import matplotlib.pyplot as plt import pandas as pd import nibabel as nib import numpy as np from nilearn import datasets from nilearn import surface from nilearn.plotting import (plot_stat_map, plot_glass_brain, plot_surf_stat_map) from mne.externals.six import string_types from mne.uti...
14,626
7a7b4ca77a23baa258e6be03aff6834195cbcbcd
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-05-12 22:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('LensDataEditor', '0007_auto_20160512_1038'), ] operations = [ migrations.Add...
14,627
3363e69b676d47df14078be171d4a245c7094cb6
list1 = ['physics', 'chemistry', 1997, 2000] # print(list1) # del deleta o valor do elemento nesse caso 1997 # del list1[2] # print("After deleting value at index 2 : ") # print(list1) # del list1[2],list1[1] # print(list1) lista2 = ['banana', 'maçã','abacaxi','uva', 'morango'] lista2.remove('maçã') ...
14,628
854b78e4133929774177cb0c3da7df53a20e6a27
import io import os from PIL import Image, ImageDraw from google.cloud import vision def read_img(image_file): # Instantiates a client client = vision.ImageAnnotatorClient() # The name of the image file to annotate file_name = os.path.abspath(image_file) # Loads the image into memory with io....
14,629
7fc34f081710573c5998074533c9899d72927b15
import numpy as np from cvxopt import solvers,matrix from sklearn import datasets from math import sqrt #===============HELPER FUNCTIONS=============== #Simple function to calculate norm of a vector. def norm(w): return sqrt(np.dot(w,w)) #returns pairs sub dataset of xs of pairs i,j. def pairs(i,j,xs): res =...
14,630
67563247be951c5c0cafb8a66593a4d0b2c7d96f
#coding: utf-8 #!/usr/bin/env python import os from app import create_app, db from app.models import User, Role, Post from flask_script import Manager, Shell from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) @a...
14,631
ed69c2242b43c2101cc1f1dcd4d655b22bd79c7e
from cohort import Cohort from exercise import Exercise from instructor import Instructor from student import Student nutshell = Exercise("nutshell", "Javascript") reactnutshell = Exercise("reactnutshell", "react") bangazon = Exercise("bangazon", "C#/.Net") trestlebridge = Exercise("Trestlebridge Farms", "C#") cohort...
14,632
f9d1b3379d9d0b461788522681e120132cdd17a6
print("Calculo de IMC e condição") peso = float(input("Digite seu peso: ")) altura = float(input("Digite sua altura: ")) imc = peso / (altura ** 2) if imc < 16: print("Magreza grave") elif imc > 16 and imc < 17: print("Magreza moderada") elif imc > 17 and imc < 18.5: print("Magreza leve") elif imc...
14,633
1512e1d227d5d8b5107bfdcaedb6162fc276263c
import sys #Calculates the sum of the integers in a 3-digit number. def calculate_number_sum_3(aNumber): #defines a method that takes a parameter if aNumber < 100 or aNumber > 999: print("The number must be 3 digits!") sys.exit() #closes the program #-------- end of if-statement------ enta...
14,634
f42d0106f800656cc2a5ccaf10c433dad67c763d
# coding=utf-8 # @Time :2020/5/1 0001 15:27 # @Author :Eric # @Email :zhangqi_@pku.edu.cn # @File :sys_standard_lib04.py # @Software :PyCharm # chr ord print(chr(65)) # Unicode码 ---》 str B print(ord('A')) # str ---> Unicode 码 print(ord('上')) # 19978 print(ord('下')) # 19979 print(chr(19979)) # 下 ...
14,635
daf0938282006ca4714aea7cc0c954af79075dad
#!/usr/bin/env python import os import sys if __name__ == "__main__": # We always disable static serving. if (len(sys.argv) > 1 and sys.argv[1] == "runserver" and (len(sys.argv) < 3 or "--nostatic" not in sys.argv[2:])): sys.argv.append("--nostatic") os.environ.setdefault("DJANGO_SETTI...
14,636
cb127ea2295accca81fb9c5668c12f1372740fde
# Generated by Django 3.1.2 on 2020-12-20 22:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('forum_conversation', '0012_auto_20200423_1049'), ] operations = [ migrations.AlterField( model_name='topic', name='c...
14,637
4a184d4c176c1d98f0642228a133888c9f4261be
import clr clr.AddReference('ASCHFProtLib.dll') import ASCHFProtLib
14,638
853f35d4c202c8b9854e3da0e2e3a35921732c8d
# # PySNMP MIB module PDN-MPE-DOMAIN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-MPE-DOMAIN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:30:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
14,639
4c550423b32298c3fe4a41278c64ba743de230f0
import FWCore.ParameterSet.Config as cms import copy import string import pickle import TauAnalysis.Configuration.tools.factorizationTools as factorizationTools import TauAnalysis.Configuration.tools.mcToDataCorrectionTools as mcToDataCorrectionTools import TauAnalysis.Configuration.tools.sysUncertaintyTools as sysUnc...
14,640
6fb8e7b545cf253bf29001e0cb2abaf8a92ffe11
import sys N = int(sys.stdin.readline()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] visited = set() def func(y, x): if y >= N or x >= N: return False if (y, x) in visited: return False if y == N - 1 and x == N - 1: return True visited.add((y, x)...
14,641
effd4357fa7439fa160aeaf06efc5c7d5c250516
from flask import Flask, g from flask_restful import Api from resources.handlers import RootResource, HandleAttackResource, ManageAttackResource from mongodb import MongoDBWrapper def create_app(): app = Flask('dvnh-api') api = Api(app) api.add_resource(RootResource, "/") api.add_resource(HandleAtta...
14,642
d94e07d93c73aef0c872a5e364519be4cb42cc96
# from roles import( # PG, SG, SF, PF, C) # from skills import(PlayerSkill) from college_directory import get_school_name from roles import get_role from skills import get_status class _Player_Database: def __init__(self): self._ballers = { 1: { 'name': 'Raymund Salvador',...
14,643
2f89fcf91532570acbd17e510dabb3be0238f4e8
# Generated by Django 2.1.5 on 2019-04-05 15:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('website', '0002_auto_20190402_1509'), ] operations = [ migrations.AddField( model_name='auction...
14,644
eb10d64131a246d3292604ee0f312617857ed352
# Generated by Django 2.2.4 on 2021-07-10 23:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_blog', '0005_testsuittestcases'), ] operations = [ migrations.CreateModel( name='Configuration', fields=[ ...
14,645
e57b125bdbe1cbb040dcfbfd6211888d9a5d843b
#!/bin/python3 import json import requests import psycopg2 from datetime import datetime as dt #from psycopg2 import connect conn = psycopg2.connect(database="postgres", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432") cursor = conn.cursor() url = 'https://health.data.ny.gov/...
14,646
77bc7b2626baafde44417b6f3026bc0f31c58e51
# Pranav Abbaraju # Escape Sequence Lab # print out a house using escape sequences # house must have the following: a roof (pointy), a door # two windows, two stories (not books) # print out an animal's face using escape sequences print "\r\t\t _____/\\____\n\t __/____/ \\___\\__\n ____/______/ \\___...
14,647
510a7931bf81d3a9545b0fb12458b48c6e194062
import numpy as np import math texto=input("introduzca el valor que se desea: ")#sirve para introducir letras con el teclado y que el programa no avanze print(texto) texto = texto.upper().strip().replace(" ", "");#se ponen mayusculas se extraen caracteres y se eliminan espacios print(texto) print(texto[1]) ...
14,648
711925df8d58e8bbcf56a6b9a8c137227cc242fc
import inspect import math class baseProcessor: def __init__(self, program): self.pointer = 0 self.accumulator_x = 0 self.accumulator_y = 0 self.angle = 0 self.program = program self.functions = dict([(key, value) for key, value in inspect.getmembers(self.__class__, ...
14,649
43ff5f9d8958247a2723191f2107c23867ae53df
#!/usr/bin/env python """Stand alone Python script to be executed on the instance to set it up.""" from __future__ import print_function import json import socket import sys import os HOSTNAME = socket.gethostname() NUXEO_CONF = '/etc/nuxeo/nuxeo.conf' NUXEO_DATA = '/var/lib/nuxeo/data' NUXEO_HOME = '/var/lib/nuxeo/s...
14,650
9f3e025e766341484e2c29dffbc922089ba1a8cd
# -*- coding: utf-8 -*- from math import pi r = float(input()) area = r**2*pi circumference = r*pi*2 print("{:.6f} {:.6f}".format(area, circumference))
14,651
4d5f9faab3eea4ab43a4824fbcd718cf6c49c15a
""" Author: Todd Zenger, Brandeis University This program introduces more about logical statements and if statements """ # First, let's practice with some logical statements # Let's ask it some questions print("Is 5 less than 3? {}".format(5<3)) # Is 5 less than 3? Answer: False (No) print("Is 5 greater than 3? {}"....
14,652
512a7ddb322af7b09bf3736994a054589b80699b
import sys def solve(N, xs): table = [set() for _ in range(N)] for idx, x in enumerate(xs): table[x].add(idx) stack = [idx for idx, s in enumerate(table) if not s] while stack: idx = stack.pop() nxt = xs[idx] table[nxt].remove(idx) if not table[nxt]: ...
14,653
7680c34fb7e3fc73ba76ef994c3a97d89fabeaa3
from .embryo_generator_model import Generator, embryo_generator_model
14,654
b2fe2735fc7682e72cb79cab40cf1a1334f84f9e
#las tuplas no se pueden modificar tupla = ("a", 20, "Hola", 50, 100); print(type(tupla)); #ver un dato mediante indice print(tupla[4]); #recorrer print(tupla[1:3]); #se imprimira despues del dato 1
14,655
ae8e61d6f82922429ea7354b16f00faa824f86c1
import io from flask import request, send_file, make_response from app import db from app.chemas import ImageSchema from app.models import Image from app.utils import ModelTransfer from . import image from PIL import Image as imgTool model_transfer = ModelTransfer(ImageSchema) @image.route("/admin/image/metadata/...
14,656
959673ee42f5e3cdc39cd64b25f86d0033772258
import cv2 import numpy as np from matplotlib import pyplot as plt # SCALING img = cv2.imread('pic.png') resize_image = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC) cv2.imshow('resize', resize_image) cv2.waitKey(0) cv2.destroyAllWindows() # TRANSLATION rows, cols = img.shape[:2] M = np.float3...
14,657
8d7c02bf399aa13dbea8d9be277cdaea156fea22
import numpy as np import string from gensim.models.doc2vec import Doc2Vec,TaggedDocument delset=string.punctuation def get_Doc2vec_sim(model, query, candiadate): query = query.replace(' ', ' ') # candiadate = candiadate.replace(' ', ' ') query_list = query.split(' ') rhyme1_vec = model.infer_vecto...
14,658
0b0d41c3055ba08dbdc515e92d5eb676d246dc7b
from functools import cmp_to_key def compare(x,y): t1 = int(x+y) t2 = int(y+x) if t1 > t2: return -1 elif t1 < t2: return 1 else : return 0 def solution(numbers): answer = '' for i in range(len(numbers)): numbers[i] = str(numbers[i]) numbers.sort(key = cmp_t...
14,659
137e1851f8eea34dab36a00b8bb4a826082664e4
import pandas as pd from cellphonedb.tools.tools_helper import normalize_interactions def call(iuphar_guidepharmacology: pd.DataFrame, genes: pd.DataFrame, proteins: pd.DataFrame) -> pd.DataFrame: iuphar_filtered = iuphar_guidepharmacology[iuphar_guidepharmacology['target_species'] == 'Human'] iuphar_filter...
14,660
4b579610a52478b420ad83400efab385ab6739af
"""Initializes Graphite Variables.""" import logging import os from deepr.utils.graphite import HOST_ENV_VAR, PORT_ENV_VAR, PREFIX_ENV_VAR, INTERVAL_ENV_VAR LOGGER = logging.getLogger(__name__) class GraphiteInit(dict): """Initializes Graphite Variables.""" def __init__( self, host: str = None, p...
14,661
c157af940d79e0cc886b025d4fbbe0c173d683f9
""" Class While While structure while(condition) Action1 Action2 """ counter = 1 sum = 0 while(counter<=10): sum +=counter # print(counter) counter += 1 # print(sum) Letters = ["a","b","c","d","e","f"] index = 0 while(index < len(Letters)): # print(index) # print(Letters[index]) index+=...
14,662
5ba2c801a5649def3745be04dedda8b3632081a2
import logging import random import vk_api from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType import handlers try: import settings except ImportError: exit('Do cp settings.py.default settings.py and set token!') log = logging.getLogger('bot') def configure_logging(): stream_handler = loggin...
14,663
faf39edafa8eca77f2ecc1ef070f288539d30bba
#!/usr/bin/env python3 # -*- Coding: utf-8 -*- import sys import os import signal import pickle import gensim from sklearn.mixture import GaussianMixture signal.signal(signal.SIGINT, signal.SIG_DFL) num_clusters = int(sys.argv[1]) wikiFile = sys.argv[2] baseFile = os.path.splitext(wikiFile)[0] modelFile = baseFile ...
14,664
04d28dbe45a97d6a5abc5b5c6b2b1a3bd94a1905
import numpy as np from sklearn import svm import matplotlib.pyplot as plt from matplotlib import style from sklearn.metrics import accuracy_score style.use('ggplot') """ Defines all arrays to use in this Analysis. """ fLength=[] fWidth=[] fSize=[] fConc=[] fConc1=[] fAsym=[] fM2Long=[] fM3Trans=[] fAp...
14,665
261cc9414deb11950e427dabe6fd2f301fec945f
import pika credentials = pika.PlainCredentials('admin', 'admin') connection = pika.BlockingConnection(pika.ConnectionParameters(host = '122.51.134.114',port = 5672,virtual_host = '/',credentials = credentials)) channel=connection.channel() result = channel.queue_declare(queue = 'python-test6') def callback(ch, metho...
14,666
1983bc1f4e45a5e89dc6fbc538a0a3b9ddc198de
#p.194 ##q51 Anagrams def areAnagrams(string1, string2): string1=string1.upper() string2=string2.upper() string1_letters=list() for strings in string1: string1_letters.append(strings) string2_letters=list() for strings in string2: string2_let...
14,667
1bd066ee9f3c3150b8b1a60eb236afb9d50a7323
# name = input ("Enter name : ") # print("Your name is : " + name) grade = input ("Enter grade : ") print("Your grade is : " + grade)
14,668
dcd997a395d2d8ea4f4f1e728761f5092d068190
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-07-24 20:26 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gwells', '0005_auto_20180629_0024'), ] state_operations = [ migrations.RemoveField...
14,669
e75e0b084aca516c6e8c6517461de452989a53f7
import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", 9600, timeout=3.0) try: print("GSM 900\n") print("List of operating Commands") print("Commands functions") print("AT to check operations") port.write('AT\r\n') rcv = port.read(20) print("GSM" + rcv) while True: ...
14,670
7f5377c8d338a56f93c7fa7807da05224c8fbc8a
# Generated by Django 3.2.5 on 2021-07-20 09:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_...
14,671
c0f3528bfdc2333cb50b7d43033f331fcff82550
''' You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will: Choose one integer x from either the start or the end of the array nums. Ad...
14,672
13a93da8a40499ccd31a238894bcc8838b3c41f9
import random def binary_search(list, start, end, target): print(f'buscando {target} entre {list[start]} y {list[end - 1]}') if start > end: return False middle = (start + end) // 2 if list[middle] == target: return True elif list[middle] < target: return binary_search(lis...
14,673
a6acedbb2d19401d1c5e2c281312cfd7731cb6b9
#!/usr/bin/env python # -*- coding: utf-8 -*- from Configuration import Configuration from Interface import Interface from Structure import * from random import randint from copy import copy, deepcopy class Puzzle: _config = None _matrix = None _hash = None _matrixFinal = N...
14,674
99f9d5a038213bd51da340dfc5c186bbcf97bafb
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
14,675
f3bc66b70525e1d0095e43f99d6a0f5f63c680fe
#!/usr/bin/python import sys import os import re import redis #from autocomplete_redis_python import complete r = redis.StrictRedis(host='localhost', port=6379, db=0) # this module will ask for options addword or autocomplete def complete(r,prefix,count): results = [] rangelen = 50 # This is not random, try...
14,676
5df95ee4d9867cf9455b1d208c6d25cc6eaa8ddf
from django.shortcuts import render from django.views import generic from django.urls import reverse from django.http import HttpResponseRedirect from django.utils import timezone from .models import Record class IndexView(generic.ListView): template_name = 'records/index.html' def get_queryset(self): ...
14,677
f6b3976edd9e237680c1c458a3c196e49063d6cf
import hard_constraints as hc import general_info as gi import random def get_random_time_slot(): """ :return: random time slot """ return random.randrange(gi.total_course_hours) def get_random_time_slots(): """ :return: two different random time slots, integers """ time_slot_1 = ran...
14,678
9ba3b18185679f5e2643cfa0fc0b093dc2dcdd38
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Youtubedlg module responsible for handling the log stuff. """ from __future__ import unicode_literals import os.path from time import strftime from .utils import ( os_path_exists, get_encoding, check_path ) class LogManager(object): """Simple log ...
14,679
50df4d1b91aaaa4092ec1aa3d90367962034f4b7
primes=[2,3,5,7] primes2 = primes.copy() def is_prime(n): if n <= 0: return False if n < primes2[-1]: return n in primes2 else: listOfNumbers = set([x for x in range(2, n + 1)]) while len(listOfNumbers) > 0: currentPrime = listOfNumbers.pop() ...
14,680
5307306aa96bcd6bc364abab60e1b756e15f249a
import logging from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.executors.pool import ProcessPoolExecutor, ThreadPoolExecutor from django_apscheduler.jobstores import register_job from apscheduler.triggers.cron import CronTrigger from django.conf import settings from amaz...
14,681
83a88033176d506acd3ae62f6fe5769e0b8b55ae
from setuptools import setup setup(name='gym_building', version='0.0.1', install_requires=['gym', 'numpy', 'opencv-python'] # And any other dependencies foo needs )
14,682
a9f0b5a3050af07d30bb063fb1e0521acb5d8c90
from retrieveSpectrum.retrieveSpectrum import retrieve_spectrum data_filename = 'sample_file.json' elements =[] Spec = retrieve_spectrum(data_folder='', data_filename= data_filename, \ N_temp= 1 , state_T= 'None' , \ elements= elements, N_ab=1, state_ab='None',\ spectrum_folder ='/home/ma...
14,683
cc91cec7c0469b8adc0674ff253cad8f4ae86de5
# Python3 # https://stackoverflow.com/questions/38950579/fibonacci-sum-of-large-numbersonly-last-digit-to-be-printed i = int(input()) if i<=1: print(i) quit() last = (i+2)%60 if last==1: print(0) quit() elif last==0: print(9) quit() def fibo(i): x, y = 0, 1 for n in range(2, last+1)...
14,684
a66666df8fbcc24eefe0a7f23cbe59886784970c
# 创建节点类 class Node: """ 节点类 """ def __init__(self, val, next=None): self.val = val self.next = next # 链表的操作 class LinkList: def __init__(self): self.head = None # 初始化链表元素 def init_list(self, l): self.head = Node(None) p = self.head for ...
14,685
c4c2912c76dea40a7fe36e070c679142bc0f0425
# coding: utf-8 import gc import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd import time from datetime import datetime, timedelta from collections import deque, defaultdict from itertools import islice from tqdm import tqdm as tqdm from contextlib import contextmanager @cont...
14,686
68bb3f71c45c91d919efec79681358ebd839b371
import re from src.settings.paths import NORMALIZER_DATA as PATH connecting_characters = r'[ارزژدذو]' non_connecting_characters = r'[بپتثجچحخسشصضطظعغفقکگلمنهی]' suffixes = r'تری|ها|تر|ترین|هایم|هایش|هایت|هایمان|هایتان|های' ha_suffixes = r'یمان|یشان|یتان|یم|یت|یش|ی' verb_suffixes = r'ام|ای|است|ایم|اید|اند' pronouns = r...
14,687
69b67e31571492c3f9a7aeb443666ef510fc363d
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Format insar names and images # # By Rob Zinke 2019 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Import modules from datetime import datetime, time import numpy as np import matplotlib.pyplot as plt from osgeo import gdal #################################### ### --- Geographic tra...
14,688
4b73a948ced0cbd0ba692225937d07e99e2d5d7c
# Generated by Django 2.0.5 on 2018-05-05 18:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Gestionale', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='anagraficautente', options={'verbose_name...
14,689
d2f997f0cafffa3168d97c934269fa7818dffe8b
num=int(input("enter the number")) # for i in range(1,11): # print(i,'*',num, '=', num*i) i = 1 while i<=10: res = i * num print(i, "*" ,num, "=", i*num) i += 1
14,690
68ade1e2baad876514bd56181b9ecac1b6fda88b
import tempfile try: import zarr except ModuleNotFoundError: zarr = None import copy import logging from datetime import datetime, timedelta import cftime import pytest import pace.util from pace.util import X_DIMS, Y_DIMS from pace.util._optional_imports import xarray as xr from pace.util.monitor.zarr_moni...
14,691
afe26d26fa251afbe2aab73b2e39ce0cbd95f3dc
from app_blog.app import app from app_blog.app import db import app_blog.view from app_blog.posts.blueprint import posts app.register_blueprint(posts, url_prefix='/blog') if __name__ == '__main__': app.run(port="5020")
14,692
a093b1e90cc02d7a08323f0cb71dcce56ac12738
while 1: s=list(reversed(input()));d=0;f=1;t=0 if s==["0"]:break for i in s:t+=1;f*=t;d+=int(i)*f print(d)
14,693
efec92b115175093dad0899fbf9602ce25c398e4
# -*- coding: utf-8 -*- """ Created on Wed Aug 15 09:23:25 2018 @author: dizhen """ import pandas as pd import numpy as np from sklearn.datasets import load_iris from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC from sklearn.svm import SVC from s...
14,694
0bae4e4fbe8b9de41b1a0fdf71c279e892c244d3
import numpy as np import dd2.utils as utils class Line(): def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.compute() def compute(self): self.vector = utils.math.vector_between_points(self.p1, self.p2) self.norm = np.sqrt(np.dot(self.vector, self.vector))...
14,695
a739d64664d0ff68a6848d5e29b4dcd0e7f079e7
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.stats import norm from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from scipy import stats import warnings warnings.filterwarnings('ignore') # Repository modelsRe...
14,696
643742829b24d53e5c85c68e11b6a1500343b129
''' -Load in W matrix from NMF -prep gene sets for GSEA Larson Hogstrom, 4/2014 ''' import numpy as np import matplotlib.pyplot as plt import cmap.util.mongo_utils as mu import pandas as pd import os import cmap.io.gmt as gmt import cmap.util.progress as update from matplotlib import cm source_dir = '/xchip/cogs/proj...
14,697
ad9fc71cbd54830db9189f57befa3e7e8efd63b7
from naive_factor import div_while from legendre import is_quadratic_residue # Infinite iterator over repeated mod-squarings # @param a Integer to square # @param m Modulus # @yields a^(2^i) (mod m) for i in [1,2,...] def squarings(a, m): while True: a = (a * a) % m yield a # Get two quadratic roo...
14,698
a9fd00961b250c34c79ae5a19f9ea36f4637c843
def ITfourthyear(request): return render(request, 'fourthyear/itfourthyear.html') def Compfourthyear(request): return render(request, 'fourthyear/compfourthyear.html') def Mechfourthyear(request): return render(request, 'fourthyear/mechfourthyear.html') def Electfourthyear(request): r...
14,699
3a0689ae0eba288c752bb6e3066c05c6a62efd50
from django.contrib import admin from Aplicaciones.Venta.models import * # Register your models here. #Orden class OrdenVentaDetalle(admin.TabularInline): model = OrdenVentaDet raw_id_fields = ['producto','nro_orden_v'] class OrdenVentaAdmin(admin.ModelAdmin): list_display = ( "id","fecha_orden_v","cliente...