text
stringlengths
38
1.54M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time    : 2019/12/9 16:54 # @Author  : ZHANG Shaohua # @Contact : sofazhg@outlook.com # @File    : mammo_structurize.py # @Software: PyCharm import csv from os.path import abspath, join, dirname project_dir = dirname(dirname(abspath(__file__))) data_dir=join(project_di...
# 第 0003 题:生成的200个激活码保存在Redis非关系型数据库中 import random, string import redis def get_string(num, length=10): codes = [] chars = string.ascii_uppercase + string.digits for i in range(num): one_code = random.sample(chars, length) codes.append(''.join(one_code)) return codes def save_code_redis(): r = redis.Redi...
import zlib import lzma def compress(files, arc): with open(arc, "wb") as main: main.write(b"GCRA") main.close() for file in files: with open(file, "rb") as f: data = f.read() cData = lzma.compress(data) cFile = zlib.compress(bytes(file.spl...
import torch from torch import nn import math from discrete_nn.layers.type_defs import InputFormat class DiscreteSign(nn.Module): def __init__(self): super().__init__() def forward(self, x): outputs = torch.ones_like(x) outputs[x < 0.0] = -1 return x class DistributionSign(n...
from .table import Table class Database: hotels = Table('name') rooms = Table('hotel_id', 'price', 'capacity') bookings = Table('room_id', 'name', 'paid')
# This is for making the list needed to make the binary grid for AIMS. # Input is a list of structures and the paths to them. # Can put the header line on manually import numpy as np ######################################## def get_profiles(filename): names = [] with open(filename) as f: for line in f: names....
import sys sys.path.append('/home/liu121/emnlp_baseline') import argparse import operator class Check: def __init__(self, data_config): self.data_config = data_config def load(self): with open(self.data_config['train_conll_filePath'],'r') as f: lines = f.readlines() doc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 29 14:29:06 2021 @author: sidtrip """ import random #write a code to find dot product of vectors x = random.sample(list(range(500)), 5) y = random.sample(list(range(500)), 5) dot_product = 0 for i in range(len(x)): dot_product += x[i] + y[i] ...
# !/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020.2 # @Author : 绿色羽毛 # @Email : lvseyumao@foxmail.com # @Blog : https://blog.csdn.net/ViatorSun # @Note : 类似"黑客帝国"中的代码雨效果 # 导入系统文件库 import pygame import random from pygame.locals import * from random import randint # 定义一些窗体参数及加载...
temperature_checkbox_indicator = """ QCheckBox { color:red; } """ pressure_checkbox_indicator = """ QCheckBox { color:magenta; } """ humidity_checkbox_indicator = """ QCheckBox { color:blue; } """ wind_speed_checkbox_indicator = """ QCheckBox { color:green; } """ altitude_checkbox_indicator = """ Q...
from PyQt5.QtWidgets import QVBoxLayout,QWidget,QMainWindow,QGroupBox,QGridLayout ,QLabel,QFrame, QPushButton, QDesktopWidget, QApplication, QHBoxLayout from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal, QSize from PyQt5.QtGui import QPainter, QColor, QPalette from enum import Enum import sys, random class Direct(...
""" Workflow Job ------------------ The Query class represents a workflow job model from the RESTFul Workflow Service API """ import configparser import json import datetime import os import botocore.session import dateutil import time import logging from typing import Callable, Union, Optional, Dict, List from . i...
import pandas as pd import time n_trips = 1000 def estimate(t, total_t, processed, left): """calculates the mean time it takes to process one chunk and reports the remaining time based on this estimation.""" t_ = time.time() diff = t_ - t total_t += diff chunks_processed = processed // n_trips ...
from django.shortcuts import render, redirect, HttpResponse, Http404, HttpResponseRedirect # Create your views here. def home(request): return render(request, 'home.html') def result(request): if request.method == "GET": return redirect("/") if request.method == "POST": if not "pr...
# creating jpeg file to png import tkinter as tk from tkinter import filedialog from PIL import Image root = tk.Tk() canvas1 = tk.Canvas(root, width = 550, height = 550, bg='lavender', relief='raised') canvas1.pack() label1 = tk.Label(root, text='Image conversion from JPEG to PNG') label1.config(font=('calibre', 20)) ...
# CRE_ContractProcessor: Convert the input SOW contracts into data objects for analysis import os import subprocess import fnmatch import PyPDF2 import docx import docx2txt import logging from collections import OrderedDict from shutil import which def convertDocToDocx( inputDocument, sowLocation, logger ): logger.d...
def tournamentSort(a, n): N = 1 while N < n: N *= 2 b = [0]*(N*2) for j in range(n): b[N + j] = a[j + 1] for i in range(n): for j in range(N*2 - 1, 2, -2): if b[j] > b[j - 1]: b[int(j/2)] = b[j] else: b[int(j/2)] = b[j -...
# -*- coding:utf-8 -*- # Author:D.Gray from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from time import sleep,...
# -*- coding: utf-8 -*- { 'name': "l10n_it_stock_ddt", 'website': 'https://www.odoo.com', 'category': 'Accounting/Localizations/EDI', 'version': '0.1', 'description': """ Documento di Trasporto (DDT) Whenever goods are transferred between A and B, the DDT serves as a legitimation e.g. when the poli...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals. See gittutorial[7] to get started, then see giteveryday[7] for a useful minimum set of commands...
import csv from datetime import datetime from matplotlib import pyplot as plt filename = 'sitka_weather_2018_simple.csv' place_name = '' fig, ax = plt.subplots(2) for i in range (2): with open(filename) as f: reader = csv.reader(f) header_row = next(reader) print(header_row) date...
import json from stock_tracer.common import transaction from stock_tracer.scheduler import UpdateQuoteAction from stock_tracer.operation import AddScheduledAction from stock_tracer.test.db import DBUnitTestMixin class TestAddScheduledAction(DBUnitTestMixin): """TestAddScheduledAction""" def test_add_scheduled...
import got3 import pandas as pd from time_keeper import count from multiprocessing import Pool import numpy as np def get_tweets(phrase): data=[] tweetCriteria = got3.manager.TweetCriteria().setQuerySearch(phrase).setSince("2018-01-01").setUntil("2018-12-31").setMaxTweets(0) print(len(got3.manager...
import sys import os sys.path.insert(0, os.path.abspath("/Users/es2814/live/dcarte/")) import dcarte import pandas as pd print(pd.__version__) print(dcarte.__version__) dcarte.download_domain('raw')
# -*- coding: utf-8 -*- import os import sys from setuptools import find_packages, setup requires = [ 'pyserial-asyncio', 'sanic' ] setup(name='twidunode', version='0.0.1', classifiers=[ "Programming Language :: Python", ], author='Stefano Scipioni', author_email='ste...
#!/usr/bin/python3 import vlla c = vlla.Canvas() for i in range(0, 6): for j in range(0, 60): c.set_pixel(i, j, vlla.Color(24, 0, 0)) for i in range(6, 11): for j in range(0, 60): c.set_pixel(i, j, vlla.Color(24, 12, 0)) for i in range(11, 16): for j in range(0, 60): c.set_pixel(i...
import cv2 def isotropically_resize_image(img, size, resample=cv2.INTER_AREA): height, width = img.shape[:2] if width > height: height = height * size // width width = size else: width = width * size // height height = size resized = cv2.resize(img, (width, height), in...
import PIL from PIL import Image, ImageOps from math import pi from math import sqrt from math import radians from math import sin from math import cos import pygame pygame.init() screenWidth = 800 screenHeight = 800 screen = pygame.display.set_mode((screenWidth, screenHeight)) import argparse parser = argparse.Argu...
#!usr/bin/env python3 # -*- coding:utf-8 -*- import pymysql import time from match_f import areaandstationlist,assetmatch,stationmatch starttime = time.clock() # 连接数据库 db = pymysql.connect("localhost", "root", "", "assetsmanagement", charset='utf8') cursor = db.cursor() # 查询数据库中的表格 (arealist, stationlist) = areaands...
from django.conf.urls import patterns, url urlpatterns = patterns( '', url(r'^checks$', 'what_json.views.checks'), url(r'^add_torrent$', 'what_json.views.add_torrent'), url(r'^sync$', 'what_json.views.sync'), url(r'^sync_replicas$', 'what_json.views.sync_replicas'), url(r'^update_freeleech$', '...
# Generated by Django 2.2.6 on 2019-10-08 20:48 import configuration.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category',...
__author__ = 'DreTaX' __version__ = '1.0' """ This file was created for plugin developers to be able to use the correct functions without looking at the wiki or the api. API showoff purposes only, and nothing else. """ import ItemDefinition import Rarity class ItemBlueprint: ingredients = [] amou...
import torch import matplotlib.pyplot as plt import data import numpy as np device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = torch.load('/home/alice/alice/masters_project/MoonSRCNN-master/source/30e_64arch_Adam_MSE_0001lr/model28.pth') input = data.load_input('/home/alice/alice/masters_...
""" Module to check whether a linked list is a palindrome. Approaches: 1) Use a stack (O(N) space and time); 2) Reverse and compare (O(N) time O(N) space) todo: we are comparing the whole list - only need to check half the list, since the other half will be identical See: https://www.geeksforgeeks.org/function-to-chec...
import ajay0006Library as Dj ball = [ [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0] ] Dj.ClearScreen() Dj.setBacklight() # ...
# Generated by Django 2.1.5 on 2019-01-19 15:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0003_cartitem_price_sum'), ] operations = [ migrations.AlterField( model_name='cartitem', name='quantity', ...
name = "AP Calculus AB" header = "Time to learn" author = "Naweid" calc = [{"topic": "Limits", "img": "https://www.mathsisfun.com/calculus/images/discontinuous-function.svg", "sizex": 1,"sizey": 1, "video": "none", #put none if no video is included "description": "Limits are the firs...
import os from absl import (app, flags) from models.detector import Yolo, Csresnext FLAGS = flags.FLAGS # 模型配置目录,包括anchors,classes,backup等,目录下名字需保持一致。 flags.DEFINE_string('model_cfg_dir', None, 'The model_cfg dir for detecting.') flags.DEFINE_string('image_dir', None, 'The image dir for detecting.') USE_CPU = False i...
import cv2 import numpy as np import subprocess import logprint import re import time # evaluate the luma for each specified brightness value, return list of results def brightness(device, cap, ctrl, debug, log_file): results = [] cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1...
import hashlib ## Integrity check, use K2 def integrity(plain,K2): initialvector = "This is the initialization vector" initialvector = hashlib.sha256(initialvector.encode()).hexdigest() finalhash = [] ##initial initial_vectortwo = K2+initialvector initialhash = hashlib.sha256(initial_vectortwo....
# 직업군 추천하기 : https://programmers.co.kr/learn/courses/30/lessons/84325 def multiply_each(arr1, arr2): new_arr = [] for i in range(len(arr1)): new_arr.append(arr1[i] * arr2[i]) return new_arr def solution(table, languages, preference): table_list = [row.split(' ') for row in table]...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import build_activation_layer, build_norm_layer from mmcv.ops.modulated_deform_conv import ModulatedDeformConv2d from mmengine.model import BaseModule, constant_init, normal_init from mmdet.registry impo...
import sys from utils.node import * from core.hive import * from core.spark import * from utils.config_utils import * def copy_lib_for_spark(master, slaves, beaver_env, custom_conf, hos): spark_version = beaver_env.get("SPARK_VERSION") output_conf = os.path.join(custom_conf, "output") core_site_file = os....
import pytest class TestSample: def test_pass(self): assert True def test_fail(self): assert False @pytest.mark.skip def test_skip(self): assert True @pytest.fixture def cause_error(self): raise Exception def test_error(self, cause_erro...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Edito.button_label' db.add_column('editos_edito', 'button...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-07 10:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user', '0001_initial'), ] operations = [ m...
""" dfs 돌기 종료조건은 돌은 횟수 c 되면 답 기록 조건은 최종 조합 문자가 l글자일 경우 dfs 돌떄 체 크해야되는거 - 전의 알파벳이면 안됌 - 이미 선택한 알파벳이며 안됌 --> 오름 차순 후 그 다음 인덱스부터 순회 하는 것으로 해결 가능 - 모음 하나 있는지 , 자음 두개 있는지 check """ import sys l, c = map(int, sys.stdin.readline().split()) alpa = list(map(str, sys.stdin.readline().split())) alpa.sort() def makePWD(cnt,...
from fastapi import FastAPI,Request,Depends from fastapi.templating import Jinja2Templates import models from sqlalchemy.orm import Session from database import SessionLocal,engine from pydantic import BaseModel app = FastAPI() models.Base.metadata.create_all(bind = engine) templates = Jinja2Templates(directory = 'te...
""" My datastructure to optimize the circuit inside the problem set. Using a profiler like cProfile, we could see that the initial performance bottleneck came from the min() function, which needed O(n) time to find the minimum. So using the minheap datastructure you could bring the cost to O(1). """ class PriorityQu...
# Generated by Django 3.1.4 on 2021-02-13 20:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0008_auto_20210213_2006'), ] operations = [ migrations.AlterField( model_name='product', name='category',...
import numpy as np import pandas as pd from dowhy.causal_estimator import CausalEstimator from dowhy.causal_estimators.instrumental_variable_estimator import InstrumentalVariableEstimator class RegressionDiscontinuityEstimator(CausalEstimator): """Compute effect of treatment using the regression discontinuity me...
""" Created on Tue Jun 6 17:06:15 2017 @author: johnnyhsieh """ import numpy as np import matplotlib.pyplot as plt import pandas as pd #import the trainning data training_set = pd.read_csv('Google_Stock_Price_Train.csv') training_set = training_set.iloc[:,1:2].values #Feature scaling normalize the data for more e...
from observer.tests.compat import TestCase from observer.tests.compat import MagicMock from observer.tests.models import Article from observer.tests.factories import ArticleFactory from observer.watchers.value import ValueWatcher class ObserverWatchersValueWatcherTestCase(TestCase): def setUp(self): self....
# imports import os import io import sys from utils import create_QR, create_PDF_medium, create_PDF_large, create_PDF_small from flask import Flask, jsonify, request # APP app = Flask(__name__) # Static path STATIC_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")) OUTPUT_PATH ...
from typing import List from collections import deque class Solution: def processQueries(self, queries: List[int], m: int) -> List[int]: P = deque([i for i in range(1,m+1)]) r = [] for i in range(len(queries)): r.append(P.index(queries[i])) P.remove(queries[...
a = print a("hello") def test(): return print test()("hello") # Decorator def deco(func): def wrap(): print(func.__name__) return func() return wrap @deco def test2(): return 3 @deco def test3(): return 4 print(test2()) print(test3())
class Persona: contador_personas = 0 @classmethod def id_contador(cls): cls.contador_personas +=1 return cls.contador_personas def __init__(self,name,age): self.id_personas = Persona.id_contador() self._name= name self._age = age @property def id(s...
from django.db import models class Customer(models.Model): name = models.CharField(max_length =50 ) cpf = models.CharField(max_length =12, unique=True ) phone = models.CharField(max_length = 12 )
''' Practice : Blackjack Marcel Schaeffer 10/24/17 ''' import random class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return self.suit + ' of ' + self.rank def value(self): if self.rank == 'A': return 1 e...
# Printing, Printing, Printing days = "Mon Tue Wed Thu Fri Sat Sun" # using a back slach and 'n' puts the code starting on a new line months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print("Here are the days: ", days) print("Here are the months: ", months) # using three double-quotes allows you to type muktiple se...
from profiles.views import ProfileCreateView, ProfileDeleteView, ProfileDetailView, ProfileListView, ProfileUpdateView from django.urls import path app_name = "profiles" urlpatterns = [ path('', ProfileListView.as_view(), name='profile-list'), path('<int:pk>/', ProfileDetailView.as_view(), name='profile-detai...
#!/usr/bin/python from argparse import ArgumentParser from py_ptrace import call_execve arg_parser = ArgumentParser() arg_parser.add_argument('-p', '--pid', type=int, required=True, help='set process id') arg_parser.add_argument('-a', '--addr', type=int, required=False, help='set address') args = arg_parser.parse_arg...
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email="fulano@email.com", ...
from django.shortcuts import render from features.models import Info # Create your views here. def index(request): return render
# Ennþá í vinnslu # Þetta mun vera einhver syntax errors en það er því það þarf að fylla út það sem vantar. # Format skipanir fyrir hvert og eitt stak # Filtered útprentun eftir flokki, t.d til að prenta aðeins út nöfn viðskiptavina. eða nöfn og auðkenni. import csv with open ("", "r", encoding = "utf-8") as csv_...
from django.contrib import admin from .models import File_motor # Register your models here. admin.site.register(File_motor)
import os import json import numpy as np import serial import time from RESTRequest import pose_estimator PORTNUM = 'COM10' BAUDRATE = 9600 PAUSFRAME = 2 connected = True def delAll(): path_to_json = './json_file_stream/' json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('....
from heapq import heapify, heappush, heappop from weights import ew from comptab import fcomp from bitcoding import DALL from inverse import inv from conjunction import l_and import itertools from counters import arcCount, conCount # path consistency using van Beek weights def PCew(ConMatrix, m = -1, n = -1): pq = ...
n,t = map(int,input().split()) a = [int(input()) for _ in [0]*n] total = 0 pre = 0 for i,time in enumerate(a): if i == 0: pass else: if t < time-pre: total += t else: total += time-pre pre = time print(total+t)
from mesh.standard import * from scheme import * from platoon.resources.executor import Endpoint class Process(Resource): """A process.""" name = 'process' version = 1 class schema: id = UUID(nonnull=True, oncreate=True, operators='equal') queue_id = Token(nonempty=True, operators='e...
#################################### # David Sprehn and Espen Nielsen # March 2018 #################################### # This is a work in progress! # We haven't yet completed training of an AI that can play well. # Goal: we wanted to learn about neural networks and their AI applications, # so we dec...
from random import sample texto = print("Ordem de alunos que vão apresentar o trabalho") a1 = input('Primeiro aluno:') a2 = input('Segundo aluno:') a3 = input('Terceiro aluno:') a4 = input('Quarto aluno:') lista = [a1, a2, a3, a4] ordem = sample(lista, k=4) print('A ordem de apresentação será {}'.format(ordem))
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 22:04:08 2020 @author: vominhthuan """ import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestRegressor import matplotlib.pypl...
from django.forms import ModelForm from django.contrib.auth.models import User from django import forms class SignupForm(ModelForm): #회원가입을 제공하는 class이다. password_check = forms.CharField(max_length=200, widget=forms.PasswordInput()) #아쉽게도 User 모델에서는 password_check 필드를 제공해주지 않는다. #따라서 따로 password_check 필드를 직접 정의해줄 ...
from lxml import etree class Builder: def __init__(self): self.__root = None def set_root(self, name): self.__root = etree.Element(name) def add_subelement(self, father, name): sb = etree.SubElement(father, name)
# -*- coding: utf-8 -*- from sklearn.metrics import accuracy_score from hyperopt import hp, fmin, tpe, STATUS_OK, Trials from sklearn.tree import DecisionTreeClassifier # Utilities for preprocessing import pandas as pd from preprocessing import generate_types train_file = "new_train.csv" df_train = pd.read_...
def invert_array(a, s): """ inverts list, example: [1, 2, 3, 4, 5] -> [5, 4, 3, 2, 1] :param a: list :param s: list size :return: reversed list """ for k in range(s): a[k], a[s - 1 - k] = a[s - 1 - k], a[k] return a def test_invert_array(): a1 = [1, 2, 3, 4, 5] p...
#!/usr/bin/python # encoding: utf-8 import os import urllib2 import socket from sgmllib import SGMLParser from django.core.mail import send_mail from pprint import pprint # ========================================= # Settings # ========================================= TCMS_SETTINGS = 'tcms.product_settings' ADMINS...
import shutil, torch, pickle, os, argparse, torch from tqdm import tqdm from torch import nn from torch.optim import Adam import torch.optim as optim from RNN_model import GRUNet import torch.nn.functional as F def get_args(): parser = argparse.ArgumentParser( description="") parser.add_argument("-tr",...
class Solution(object): read_buffer = [] legacy_buffer = [] def read(self, buf, n): ch_read, ch_remaining = 0, n while self.legacy_buffer and ch_remaining: buf[ch_read] = self.legacy_buffer[0] self.legacy_buffer.pop(0) ch_read += 1 ch_remaining...
"""zidian = {} zidian['user_name'] = input("请输入名字:") zidian['user_age'] = input("请输入年龄:") fout = open('allusers.txt', 'w', encoding='utf8') fout.write(zidian) fout.close() print(zidian) """ """# 打开「detail_content」文件 fout = open('detail_content', 'w', encoding='utf8') # 写入文件内容 fout.write(content) 关闭文件 fout.close()...
import requests, json, sys, time from datetime import datetime locationURL = 'https://visits.evofitness.no/api/v1/locations?operator=5336003e-0105-4402-809f-93bf6498af34' capacityForURL = 'https://visits.evofitness.no/api/v1/locations/{}/current' attempts = 1 responses = [] def getArgument(argumentKey): args = sy...
# 문자열 표시 print("qwerty12345문자열") print('qwerty12345문자열') print("""qwerty12345문자열""") print('''qwerty12345문자열''') #문자열내에 특수문자 표현 str = '당신의 이름은 "한사람"입니다.' print(str) str = "당신의 이름은 '한사람'입니다." print(str) str = '당신의 이름은 \'한사람\'입니다.' print(str) str = "당신의 이름은 \"한사람\"입니다." print(str) # 긴 문자열의 표현 longstr =...
import os from tkinter import * from tkinter import filedialog def openfile(): filename = filedialog.askopenfilenames(parent=root, initialdir="C:\\Users\\Tri Nguyen\\Documents", title="Select File") print(filename) root = Tk() root.geometry("300x300") menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) f...
#Fijamos las variables y su valor import time numero1 = 0 numero1= int(input("Dame un numero para la cuenta atras \n")) for i in range(1,numero1): print ("",numero1-i) time.sleep(0.5) print ("El cohete ha despegado")
import logging from logging.config import fileConfig import errno import os import shutil import tempfile from fabric.api import local, env from fabric.context_managers import cd import boto3 from paramiko import SSHClient from communication.scp import SCPClient from task import Task from . import Workflow class...
from django.urls import path from articles import views as articles_views app_name = 'articles' urlpatterns = [ path('create-article', articles_views.create_article, name="create_article"), path('<int:article_id>', articles_views.modify_article, name="modify_article"), path('article-approval', articles_vi...
from __future__ import print_function x=input() count=1 print ('%d,'%x,end='') while(x!=1): if (0==x%2): x=x/2 count+=1 if (x!=1): print ("%d,"%x,end='') else: print ("%d"%x,end='') else: x=x*3+1 count+=1 if (x...
from instruction import instruction from action_enum import Actions class load_argument_instruction(instruction): def __init__(self, name, index): self.index = index super().__init__(name) @classmethod def create(cls, name, elements): if elements and not elements[0].isnumeric(...
########### Python 2.7 ############# ## Sample script for calling the moderator EvaluateImage Api with a local file ## To run this script, python 2.7 is required. #################################### import httplib, urllib, base64 headers = { # Request headers # Replace the placeholder {Add your Subscription I...
import pdb #WHENEVER THERE'S NO PARENTHESIS, THE REG EXP IS NOT WORKING!!!!!! open('shabbos.txt', 'r') #same as bava_metzia.txt, #bava_kamma.txt same except daf not inside parentheses so use daf = re.compile('@22.*?') #becorot.txt completely different: daf not inside parentheses #and @22 i...
""" Создать таблицы в базе данных декларативным способом (на основе классов) """ from typing import ItemsView from sqlalchemy import create_engine, MetaData, Table, Integer, String, \ Column, DateTime, ForeignKey, Numeric, CheckConstraint from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy...
import os import phd from ..utils.logger import phdLogger from ..utils.particle_tags import SimulationTAGS class SimulationOutputterBase(object): """Class that signals the simulation to write out data at current state of the simultion. This class is the api for all outputters. To inherit you will have...
""" The CMYK color model is the standard in the printing industry and refers to the primary colors of pigment: Cyan, Magenta, Yellow, and Black. K stands for 'Key' since in 4-color printing the Cyan, Magenta and Yellow printing plates are carefully keyed or aligned with the key of the Black key plate. RGB (Red, Gr...
import itertools from zope.component import getUtilitiesFor from zope.interface import implements from plone.app.themeeditor.interfaces import IResourceRetriever from plone.app.themeeditor.interfaces import IResourceType class ResourceRetriever(object): implements(IResourceRetriever) def iter_resource_types(s...
# Generated by Django 1.9.9 on 2017-01-19 18:58 from django.db import migrations insurances = [ ('111', 'Všeobecná zdravotní pojišťovna ČR'), ('201', 'Vojenská zdravotní pojišťovna ČR'), ('205', 'Česká průmyslová zdravotní pojišťovna'), ('207', 'Oborová zdravotní poj. zam. bank, poj. a stav.'), (...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('ft_fitting', '0007_ingredient_picture'), ] operations = [ migrations.CreateModel( name='Brand', fiel...
from src.quantum_phase_estimation.quantumdecomp.gate import GateSingle, GateFC from src.quantum_phase_estimation.quantumdecomp.gate2 import Gate2 def rearrange_for_merge(gates): """Rearranges gates, so mergeable gates are next to each other. Swaps only 1-qubit gates acting on different qubits, which always c...
from openpyxl import load_workbook import numpy as np wb=load_workbook('./H_7_1/H_7_1.xlsx') ws1=wb.worksheets[0] rows=ws1.max_row #取行的最大長度 ws1.cell(row=1,column=7).value='加權股價指數' ws1.cell(row=1,column=8).value='工業生產指數' ws1.cell(row=1,column=9).value='物價' ws1.cell(row=1,column=10).value='匯率' ws1.cell(row=1,column=11...
import os # FIXME: import sys sys.path.append("/net/hciserver03/storage/abailoni/pyCharm_projects/hc_segmentation/") import logging import argparse import yaml import json from torch.nn.modules.loss import BCELoss # from skunkworks.trainers.learnedHC.visualization import VisualizationCallback from long_range_hc.traine...