text
stringlengths
8
6.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/11/14 12:23 # @Author : Lucas Ma # @File : process_test2 # 进程间通信 # multiprocessing 模块包装了底层的机制,提供了 Queue,Pipes 等多种方式来交换数据 # 以Queue 为例,在父进程中创建 2 个子进程,一个往Queue 里写数据,一个从Queue 里读数据 from multiprocessing import Process, Queue import os, time, random # 写数据进...
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 22:37:44 2020 @author: Ferna """ import pandas as pd import math #Constantes Debye-Hückel A= 0.50917 B= 0.32832 #Carga y radio de los iones #0-Na+, 1-Cl- Zi= 1.0 ai= [4.0, 3.5] bi= [0.075, 0.015] #Concentración MM= 58.44 #g/mol NaCl C_H = 35 #g/L C_L = 5 #g/L df = pd....
from django.contrib import admin from phoneuser.models import PhoneUser admin.site.register(PhoneUser)
# -*- coding: utf-8 -*- """ Created on Sat Mar 6 11:43:47 2021 @author: anand """ # The algorithm starts at 3 cur_x =5 # Learning Rate rate = 0.1 # This tells us when to stop the algorithm precision = 0.5 previous_step_size = 1 # Maximum number of iterations max_iters = 1000000 # iteration counter i...
n = int(input()) a = "" up = 0 temp = 0 for i in range(n): if i%2 == 0: a += input() else: a += input()[::-1] for i in list(a): if i == "o": temp += 1 elif i == "A": if temp > up: up = temp temp = 0 if temp > up: up = temp print(up)
from jinja2 import FileSystemLoader, StrictUndefined from jinja2.environment import Environment env = Environment(undefined=StrictUndefined) env.loader = FileSystemLoader('.') vrf_var = { "VRF_NAME": "blue", "RD": "100:1", "IPv4_ENABLED": True, "IPv6_ENABLED": True } template_file = 'ex3.j2' templa...
# Generated by Django 3.1.4 on 2020-12-14 13:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('film_app', '0002_auto_20201214_1353'), ] operations = [ migrations.RenameField( model_name='fil...
"""Test aid views.""" import pytest from django.urls import reverse from tags.models import Tag from tags.factories import TagFactory from aids.factories import AidFactory from aids.models import Aid pytestmark = pytest.mark.django_db def test_draft_list_is_for_authenticated_users_only(client, contributor): ""...
from birthday_prog import Birthday hashtable = [] for i in range(12): hashtable.append([]) file_var = open("bdaylist.txt","r") line_var = file_var.readlines() tot_counter = 0 for lines in line_var: word_list = lines.split("/") day = int(word_list[0]) month = int(word_list[1]) year =...
# -*- coding: utf-8 -*- from nipype.interfaces.base import (TraitedSpec, File, isdefined, traits, OutputMultiPath, InputMultiPath) from nipype.interfaces.spm.base import (SPMCommand, scans_for_fnames, SPMCommandInputSpec) from nipype.utils.filemanip import split_f...
import functools import json from enigma_docker_common import storage from enigma_docker_common import config from enigma_docker_common.logger import get_logger logger = get_logger('bootstrap-loader') class BootstrapLoader: bootstrap_file_name = "bootstrap_addresses.json" def __init__(self, cfg: config.Co...
#!/usr/bin/python # -*- coding: iso-8859-15 -*- from xml.sax import make_parser from xml.sax.handler import ContentHandler strinit = "null value" class SmallSMILHandler(ContentHandler): def __init__ (self): self.root-layout = {'w':'', 'h':'', 'bc':''} self.region = [] self.img = [] ...
def standard_units(any_numbers): """Convert any array of numbers to standard units.""" return (any_numbers - np.average(any_numbers)) / np.std(any_numbers) def correlation(t, x, y): """Return the correlation coefficient (r) of two variables.""" return np.mean(standard_units(t.column(x)) * standard_unit...
from threading import Thread import sys, time import numpy as np from Config import Config class ThreadReader(Thread): def __init__(self, remote_q, local_q): super(ThreadReader, self).__init__() self.setDaemon(True) self.remote_q = remote_q self.local_q = local_q self.exi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0011_auto_20150402_0816'), ] operations = [ migrations.AlterModelOptions( name='post', optio...
from model.vehicle_handling.vehicle import Player, Enemy from model.vehicle_handling.spawn_enemies import spawn_chance class GameModel: # player = Player(400, 400, 20, 20, 1, 8, 1, 8) # vehicles.append(Enemy(1, "enemy car", 400, 500)) def __init__(self, num_players=1): if num_players == 2: ...
# Let G = <N, A> be a Graph with N nodes and A Edges, let G' = <N, T> be a partial graph of # that one, it must have, at least, N - 1 Edges to be connected. # A Graph with N nodes with more than N - 1 Edges contains, at least, one cycle, so we can remove, # at least, A - N - 1 edges in a graph with A edges and still ha...
#!/usr/bin/python3 # @Author: Safer # @Date: 2016-12-01 01:40:55 # @Last Modified by: Safer # @Last Modified time: 2016-12-04 17:04:39 import sys import res from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QToolButton, QLabel, QDockWidget from PyQt5.QtWidgets import QFormLayout, QVBoxLayout, QHBoxLa...
print("===문제1===") num = int(input("숫자 입력 : ")) count = 1 result = 0 while count <= num: result += count count += 1 print("1부터 %d까지의 누적합계 : %d"%(num, result)) print("===문제2===") count = 0 #0부터 시작 while count < 10: # 0 ~ 9 : 10번 반복 print("Hello Python") count += 1 # print("===문제3===") #...
def count_text_string(search_for, search_in): """ a function that takes a text to be searched for and a text to be searched in :param search_for: word to be searched for :param search_in: file to be searched in :return: """ character_check = 0 if search_in == "": return...
import numpy as np import matplotlib.pyplot as plt a = np.linspace(-5,5,50) xs=[] xsdot=[] x = 2 for i in range(50): f = np.arcsin(x/a[i]) fdot = np.cos(f) xs.append(f) xsdot.append(fdot) print(a) print(xs) plt.plot(a,xs,'b') plt.plot(a,xsdot,'r') plt.show()
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'nonbundle', 'type': 'static_library', 'sources': [ 'file.c', ], 'postbuilds': [ { '...
#!/usr/bin/env python #coding: utf-8 from licant.modules import submodule from licant.cxx_modules import application import licant from licant.scripter import scriptq scriptq.execute("../../gxx.g.py") application("target", sources = ["main.c"], include_paths = ["../.."], include_modules = [ ("gxx", "posix"), ...
def bmi(w, h): return w/h**2 def bmi2(w, h): return 1.3*w/h**(2.5) def range_f(min, max, step): ans = [] while min <= max: ans.append(round(min, 1)) min += step return ans def cross(a, b): assert(type(a) == list) assert(type(b) == list) ans = [(0.0, 0.0)]*len(a)*len(b) print(len(a)) print(len(b)) for (i...
class Obstacle: color = "gray" stipple = "gray75" def __init__(self, xy, scale=1): self.xy = [int(x) * scale for x in xy] def text(): for x in xy: print(x) def draw(self, canvas): return canvas.create_polygon(self.xy, stipple=self.stipple, fill=self.color)
import os filename = '15464657761111111.pdf' pathDir = 'F:/tqcs/sr' # 判断文件是否存在 if os.path.exists(pathDir + '/' + filename): print(filename + '文件在' + pathDir + '中存在 ! ') else: # 打开文件,不存在则创建 file = open('F:/tqcs/msmj.txt', 'wr') print(filename + '文件不存在sr目录下,将名字写入到msmj.txt文件中 ! ') # 将文件名写入到指定文件中 ...
# Generated by Django 2.0.5 on 2018-06-05 10:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AddField( model_name='book', name='language', fie...
from Simulator_Wrapper import * def get_crossover_name(crossover: int) -> str: if crossover == Crossover_Algorithm.Partially_Matched: return "Partially Matched" elif crossover == Crossover_Algorithm.Order: return "Order" elif crossover == Crossover_Algorithm.Cycle_all_cycles: return "Cycle (all)" elif cross...
# Leia uma string e diga se ela possui apenas letras ou nao string = input() if string.isalpha(): print("Apenas Letras") else: print("Possui Numeros")
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2020-06-14 20:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tickets', '0006_ticket_email'), ] operations = [ migrations.AlterField( ...
# a file hosts all global referred parameters/sets/etcself. from pyomo import environ as pe from data.thermal_data import Tb from utility.data_utility import cal_cnumber m = pe.ConcreteModel() m.COMP_OLEFIN = pe.Set(initialize=['C{0}H{1}'.format(i,2*i) for i in range(2,21)],ordered=True) m.COMP_PARAFFIN = pe.Set(init...
# coding=utf-8 import _sqlite3 as sqlite import csv def connectToDB(): connector = sqlite.connect('neural_db.db') return connector def updateParamToDB(connector, data): cursor = connector.cursor() param_name = data['data']['param'] minimal = data['data']['min'] maximum = data["data"]["max"] ...
"""Users View""" from django.shortcuts import render from django.contrib.auth import views as auth_views from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.detail import DetailView from django.views.generic.edit import FormView, UpdateView from django.urls import reverse, reverse_lazy ...
import turtle def draw_square(any_turtle): for i in range (0, 4): any_turtle.forward(100) any_turtle.right(90) def draw_circle(any_turtle): any_turtle.circle(100) def draw_equilateral_triangle(any_turtle): for i in range (0, 3): any_turtle.forward(100) any_turtle.right(120...
def find_it(seq): dict_of_repeated_numbers = { item : seq.count(item) for item in seq } for key,value in dict_of_repeated_numbers.items(): if value%2 != 0 : return key
import numpy as np import json import matplotlib.pyplot as plt from scipy.optimize import leastsq import argparse """ Attempt to fit log beta vs log [Rc,R0,R90] """ shelldata = json.load(open("Rc-R0VsBeta.json")) parser = argparse.ArgumentParser(description="choose y-axis to plot") parser.add_argument("...
#/bin/bin/python def randnum()
#B d,mn=map(int,input().split()) tq=list(map(int,input().split()[:mn])) print(tq[mn-1])
from django.conf.urls import url from . import views urlpatterns = [ url(r'users/data/epoch$',views.UserGarminDataEpochView.as_view(), name="epoch_data"), url(r'users/data/sleep$',views.UserGarminDataSleepView.as_view(), name="sleep_data"), url(r'users/data/body_composition$',views.UserGarminDataBodyCompositionView...
from drawingpanel import * import math panel = DrawingPanel(500, 500) panel.set_background("green") canvas = panel.canvas def sierpinski_triangle(iterations): '''First iteration / seed ''' C_Point_Y_Value = 53.5898384862 if iterations >= 0: ''' First Iteration ''' canvas.create_polygon(50, 400, 450, 400, 250,...
# -*- coding: utf-8 -*- """ ytelapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ import jsonpickle import dateutil.parser from .controller_test_base import ControllerTestBase from ..test_helper import TestHelper from ytelapi.api_helper import APIHelper ...
from threading import Thread import time import logging from decimal import * import decimal import timeit logging.basicConfig(level=logging.DEBUG, format='(%(threadName)s) %(message)s', ) # Note: this method taken from # https://docs.python.org/3/library/decimal.html#recipes def pi(): """Compute Pi to the curre...
#!/usr/bin/python3 from sys import argv """ script that adds all arguments to a Python list, and then save them to a file """ save_to_json_file = __import__('7-save_to_json_file').save_to_json_file load_from_json_file = __import__('8-load_from_json_file').load_from_json_file my_list = [] try: my_load = load...
from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, new_user, timestamp): return ( six.text_type(new_user.pk) + six.text_type(timestamp) + six.text_type(new_user...
#!/usr/bin/env python from File import File from LSA import LSA from Set import Set from NaiveBayesClassifier import NaiveBayesClassifier import numpy import datetime ############################################################################### # Initializing ########################################################...
#coding:gb2312 #使用try-except代码块处理可能引发的异常 print("Give me two numbers,and I'll divide them.") print("Enter 'S' to quit.") while True: first_num = input("Please enter first number: ") if first_num.upper() == 'S': break second_num = input("Please enter second number: ") try: answer = int(first_num)/int(second_num...
# %load q01_cond_prob/build.py # So that float division is by default in python 2.7 from __future__ import division import pandas as pd df = pd.read_csv('data/house_pricing.csv') # Enter Code Here def cond_prob(df): pd.set_option('display.max_columns',500) all_houses=df.shape[0] old_town=df[df['Neighbor...
# Copyright (c) Members of the EGEE Collaboration. 2004. # See http://www.eu-egee.org/partners/ for details on the copyright # holders. # # 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 #...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ################################################################################# # # # plot_sci_run_trends.py: pdate science run trend plots # # ...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('administration', '0005_auto_20191019_0200'), ] operations = [ migrations.AlterField( model_name='clients', name='credit_card_number', field=models.CharFi...
import json with open('3_2 задача.json', 'w') as to_write: with open('C:\\Users\\Виктория\\Downloads\\RomeoAndJuliet.json', 'r', encoding='utf-8') as f: romeo = json.load(f) for act in romeo['acts']: for scene in act['scenes']: set_char = set() for charac...
import smtplib import os import datetime import dropbox from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate from dotenv import load_dotenv load_dotenv() input("\nUnlock then relock here: https://www.google.com/settings/security/lesssecureapps \n") m...
from django.db import models # from django.utils import timezones from django.contrib.auth.models import User class Meetups(models.Model): # No = models.IntegerField() City = models.CharField(max_length=100) Venue = models.TextField() Time = models.TextField() Theme = models.TextField() MOderat...
from django.contrib import admin # from rangefilter.filter import DateRangeFilter from mpesa_api.core.models import ( AuthToken, B2CRequest, B2CResponse, C2BRequest, OnlineCheckout, OnlineCheckoutResponse, ) admin.site.register(AuthToken) @admin.register(B2CRequest) class B2CRequestAdmin(adm...
import numpy as np import cv2 import math def main(): gry = cv2.imread('lena.jpg', 0) width, height = gry.shape out = np.zeros((height, width), dtype = np.uint8) a = 2 b = -3 c = -1000 shuki = 20 noise_strength = 20 for w in range(width): for h in range(height): ...
from random import randint from boto3 import resource db = resource("dynamodb", region_name="us-east-1").Table("FortunesServerless") def get(event, context): fortune = db.get_item( Key = {"id": randint(0, db.scan()["Count"]-1)} )["Item"]["fortune"] return { "isBase64Encoded": False, "statusCode": 200, "he...
#File: hw2_part1.py #Author: Joel Okpara #Date: 2/14/2016 #Lab Section: 04 #UMBC Email: joelo1@umbc.edu #Description: This program contains HW2 problems 1-10 #Question 1 #Expected Output: 55 num1 = (7 + 4) * 5 print("Num1 evaluates to:",num1) #Actual Output: 55 #Explanation: Parentheses first (11)...
import subprocess def run_code(code): try: output=subprocess.check_output(['python','-c',code],universal_newlines=True,stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: output=e.output except subprocess.TimeoutExpired as e: output='\r\n'.join(['Time Out!!!...
__version__ = '0.0.2' __license__ = 'MIT' def main(): import article, argparse # initialize parser parser = argparse.ArgumentParser(prog='article_gen') parser.formatter_class = argparse.RawTextHelpFormatter parser.description = 'automatic article generator by MaxXing\n' + \ ...
import pyotherside def test_func_one(): # Test function that returns string from python script return "world from python..." def test_func_two(argument): # Test function that returns string from python script return "world from python... but with argument { " + str(argument) + " }"
#!/usr/bin/python from datasport import SerieD import sys gironi={ '2015' : [15523,15524,15525,15526,15527,15528,15529,15530,15531], '2016' : [16348,16349,16350,16351,16351,16353,16354,16355,16368] } girone=ord(sys.argv[1].upper())-65 anno=sys.argv[2] g=0 while g==0: p=SerieD(gironi[anno][girone],sys.argv[3]) g...
# Exercício 7.1 - Livro s1 = str(input('Digite a primeira string: ')).upper() s2 = str(input('Digite a segunda string: ')).upper() pos = s1.find(s2) if pos >= 0: print(f'{s2} encontrada na posição {pos}') else: print('Nada foi encontrado!')
from customers.Aurora.provider.provider_mappings import CREDENTIALS, provider_type_map from lib.master_fake_data_generator import FakeDataGenerator class AURORAProviderFakeDataGenerator(FakeDataGenerator): def generate_pipeline_row(self, row: str, file_size: int) -> dict: f = self._faker r = self...
#coding=utf-8 """ Extra things to make the discord library nicer """ from discord import errors async def safeSend(channel, text=None, embed=None): """ Send a text / embed message (one or the other, not both) to a user, and if an error occurs, safely supress it On failure, returns: ...
import turtle tur=turtle.Turtle() scr=turtle.Screen() scr.bgcolor('black') #tur.pencolor('white') x=30 y=0 Color =['red', 'purple', 'blue', 'green'] tur.speed(0) tur.penup() #tur.goto(0,200) tur.pendown() while True: tur.circle(x) tur.pencolor(Color[y%len(Color)]) tur.forward(x) tur.right(90) x +=1 y +=1 i...
''' Underlying platform implementation for kernel debugging with vmware gdbserver. Msv1_0SubAuthenticationRoutine VMWare config options... debugStub.listen.guest64 = "TRUE" # ends up on port 8864 (or next avail) # 32 bit target.... ( defaults to port 8832 ) debugStub.listen.guest32 = "TRUE" debugStub.listen.guest32...
#!/usr/bin/env python3 # # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause from amaranth import * from amaranth.hdl.ast import Fell from usb_protocol.emitters import SuperSpeedDeviceDescriptorCollection from luna ...
from typing import Dict def save_row(text: str, n2: int, p2: int, smile_dict: Dict[str, str], line: str) -> None: """ Функция для решения задачи № 3: выгрузить в отдельный файл строку, которая содержит частицу "не" или "ни" и смайлик :param text: str :param n2: int :param p2: int :par...
# ============================================================================= # Copyright (c) 2001-2018 FLIR Systems, Inc. All Rights Reserved. # # This software is the confidential and proprietary information of FLIR # Integrated Imaging Solutions, Inc. ("Confidential Information"). You # shall not disclose suc...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'lotto.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): ...
class Cup1: def __init__(self): self.color = None # public variable self.content = None #public variable def fill(self,beverage): self.content = beverage def empty(self): self.content = None def __str__(self): return self.color + " " + self.content cup1 = ...
import re from rest_framework import serializers def correctness_struct_serial(value): regex = '[GMS][0-9]{3}' pattern_object = re.compile(regex) is_match = pattern_object.match(value) if not is_match: serializers.ValidationError("El serial del dispositivo no es valido")
def power(x, n): # Function name, arguments/parameters ans = 1 for i in range(0, n): ans = ans * x return ans # Return statement exits and returns a value. # Passing values to functions - When we call a function we have to pass values for the arguments and this is done exactly the same way as as...
with open(r"C:\Users\admin\OneDrive\デスクトップ\python1\07\20k1026-06-turtle.txt") as file: import turtle t = turtle.Pen() for line in file: data = line.split(":") if data[0] == "FORWARD": t.forward(float(data[1])) if data[0] == "LEFT": t.left(float(data[1])) ...
from pathlib import Path import pandas as pd import shutil import os WORKING_FILES = Path(r"working_files") HTML_1 = r'<html><body>' HTML_2 = r'</body></html>' PARENT = WORKING_FILES.parent RESULT = PARENT / 'result' if RESULT.exists(): shutil.rmtree(RESULT) os.mkdir(RESULT) for filepath in WORK...
import sqlite3 import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem, QWidget from PyQt5.QtWidgets import QMessageBox from main_design import Ui_MainWindow from addEditCoffeeForm import Ui_Form class CafeCoffee(QMainWindow, Ui_MainWindow): def __init__(self...
from flask import Flask, request, redirect, render_template from flask_restful import Resource, Api import json, re, random, string from sqlalchemy import create_engine, text from sqlalchemy.orm import sessionmaker from db import URLs, Base # connect to the db e = create_engine('sqlite:///hackerEarth.db') Base.metada...
import time import torch from torch import nn, optim from torch.utils.data import Dataset, DataLoader import torchvision import matplotlib.pyplot as plt from PIL import Image import sys sys.path.append('F:/anaconda3/Lib/site-packages') import d2lzh_pytorch as d2l device = torch.device('cuda' if torch.cuda.i...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua from flask import Blueprint, render_template, redirect user = Blueprint('user',__name__) @user.route('/index',method=['GET']) def index(): return ('user/index') @user.route('/add') def add(): return 'user_add' @user.route('/show') def show(): ret...
# Copyright 2017 The Forseti Security Authors. 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 ap...
"""This file should contain all tests that need access to the internet (apart from the ones in test_datasets_download.py) We want to bundle all internet-related tests in one file, so the file can be cleanly ignored in FB internal test infra. """ import os from urllib.error import URLError import pytest import torchv...
""" module for base plugin class, utilities, etc. """ from multiprocessing import Process, Pipe import time import monitor class Plugin(object): def __init__(self): self.monitor = monitor.Monitor() self.pipe = None def start(self): self.pipe, child = Pipe() self.proc = Process...
'''n = int(input()) arr = list(map(int,input().strip().split()))[:n] u = len(arr) for i in range(2): for j in range(i+1,3,+1): if arr[i] != arr[j]: arr.remove(arr[i]) print(arr)'''
#just like set in math: a unique collection of items - no duplicated items a= [1,2,3,4,5,6,1,1,1] sA = set(a) print sA sB = set([4,5,6,2,7]) print sA - sB # print sA & sB #intersection print sA | sB #union
import time from scapy.all import * probe = False def arp_display(pkt): if probe: if pkt[ARP].op == 1: #who-has (request) if pkt[ARP].psrc == '0.0.0.0': # ARP Probe print "ARP Probe from: " + pkt[ARP].hwsrc if pkt[ARP].hwsrc == "00:bb:3a:41:4e:7c": print time.ctime(), "Pushed Gerber" os....
#-*- coding: utf-8 -*- def gcd(a, b): while True: r = a % b if r == 0: return b a, b = b, r if __name__ == '__main__': for testcase in range(input()): values = raw_input().split() print gcd(int(values[0]), int(values[1]))
## Sample Input # the first line contains two space-separated integrs denoting the respective values of # n the number of integers in the array # and d the number of rotations to perform ## 5 4 ## 1 2 3 4 5 ## Expected output for a left rotation of 4 # 5 1 2 3 4 from enum import Enum import sys class ArrayRotator: ...
from fotutils.forms import ModelFormWithSlugBase from vars.models import Var, Device class VarForm(ModelFormWithSlugBase): class Meta(ModelFormWithSlugBase.Meta): model = Var class DeviceForm(ModelFormWithSlugBase): class Meta(ModelFormWithSlugBase.Meta): model = Device
def filter_string(string): return int(''.join(a for a in string if a.isdigit()))
# -*- coding:utf-8 -*- """ This python file is used to tranfer the words in corpus to vector, and save the word2vec model under the path 'w2v_model'. """ from gensim.models.word2vec import Word2Vec import pickle import os import gc import sys """ DirofCorpus class ----------------------------- This clas...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic import TemplateView, ListView, CreateView, UpdateView from django.shortcuts import redirect, resolve_url from django.contrib import messages from django.conf import settings from npcms.models import Section, SECTION_MODULE_CHOIC...
#!/usr/bin/env python # -*- coding:utf-8 -*- import pickle # pickle模块是对 python对象 进行 序列化/反序列化 的 二进制协议 # pickle模块有两个过程 # picking:序列化,将 python对象 转换为 字节流 # unpicking:反序列化,将 字节流 转换为 python对象 # pickle使用的数据格式仅用于python # pickle可以直接表示大部分python数据类型,包括自定义类型 # 序列化和反序列化 # dumps(obj, protocol=None, *, fix_imports=True) # loads(byt...
from django.db import models from django.db.models.base import Model # Create your models here. class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() status = models.CharField(max_length=100) image= models.FileField(upload_to...
from django.shortcuts import render from django.views import View from db.login_mixin import LoginRequiredMixin from interview.models import Interview # Create your views here. class OfferView(LoginRequiredMixin,View): '''Offer提交页面''' def get(self,request,interview_id): interview = Interview.objects.g...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ********************************************************** # * Author : xoyabc # * Email : xoyabc@qq.com # * Last modified : 2018-07-03 23:11 # * Filename : host.py # * Description : # * ******************************************************** impor...
import numpy as np import math from math import * import matplotlib.pyplot as plt import ROOT from ROOT import gROOT from math import * from array import array from scipy import stats from scipy.stats import norm import matplotlib.mlab as mlab from mpl_toolkits.mplot3d import Axes3D as ax3 inFile=ROOT.TFile("proc_cry_t...
# -*- coding: utf-8 -*- """ Created on Fri Feb 20 20:39:09 2015 @author: lenovo """ ''' 题目内容: 一个斐波那契数列的前10项为:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 对于一个最大项的值不超过n的斐波那契数列,求值为偶数的项的和。 输入格式: 一个正整数n,如100。 输出格式: 值为偶数的项的和,如 2 + 8 + 34 = 44。 输入样例: 100 输出样例: 44 ''' #n = int(raw_input()) #count = 0 #if n < 2: # pass #elif n ...
# -*- coding: utf-8 -*- import argparse import logging import random import sys import time from enum import Enum from enum import unique from pathlib import Path import requests @unique class DeviceBrand(Enum): Samsung = 'Samsung' Google = 'Google' OnePlus = 'OnePlus' Xiaomi = 'Xiaomi' Vivo = 'V...
def bald(s): states = ["Clean!","Unicorn!","Homer!","Careless!","Careless!","Careless!"] hairs = s.count('/') return [s.replace('/','-'), states[hairs] if hairs < 6 else "Hobo!"] ''' Being a bald man myself, I know the feeling of needing to keep it clean shaven. Nothing worse that a stray hair waving in ...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import ast import builtins import itertools import logging import os.path import sys import typing from dataclasses import dataclass from pathlib import...