text
stringlengths
38
1.54M
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: QAM-Decoder # Author: Ihar Yatsevich # GNU Radio version: 3.7.13.5 ################################################## if __name__ == '__main__': import ctypes import sys ...
# Ask the user for a number. Depending on whether the number is even or odd, # print out an appropriate message to the # user. Hint: how does an even / odd number react differently when divided by 2? import math class info(): def __init__(self): pass def question(self): self.question = input("...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import idlecars.model_helpers import django.core.validators class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='DriverSurvey', ...
#! /usr/bin/env python3 # Ioannis Broumas # ioabro17@student.hh.se # Dec 2020 # Remember OpenCV is BGR # Read the camera on the roof and detect the location of ArUco markers on the map # Can be adapted to detect something else on the board import numpy as np import cv2 as cv from cv2 import aruco #ROS 2 import rclpy...
import uuid from django.db import models, transaction from django.contrib.auth import get_user_model from timebank.models import Account class Order(models.Model): class Meta: verbose_name = 'Pedido' verbose_name_plural = 'Pedidos' STATUS_PENDING = 0 STATUS_CONFIRMED = 1 STATUS_CH...
# all the imports import os import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash from oauth2client import client, GOOGLE_TOKEN_URI, GOOGLE_REVOKE_URI from apiclient.discovery import build import httplib2 import datetime import json app = Flask(__name__) # c...
import jsonschema import numpy as np import pytest import oscope.schema as schema VALID_METADATA = { "sender": { "id": "foo", "name": "bar", "session": "baz", "time": 0 }, "trace": { "samples": 100, "frequency": 3000000, ...
from django.contrib import admin from .models import Question,Quiz,QuizTaker,UserTracker,AccountData # Register your models here. admin.site.register(Question) admin.site.register(Quiz) admin.site.register(QuizTaker) admin.site.register(UserTracker) admin.site.register(AccountData)
import pytest from hw9.hw9_t02 import Suppressor, suppressor test_subjects = [Suppressor, suppressor] @pytest.fixture(params=test_subjects, ids=[subj.__name__ for subj in test_subjects]) def function(request): return request.param def test_context_manager_positive_suppress_index_error(function): with func...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # # Code generated by aaz-dev-tools # --------------------------------...
# -*- coding:utf-8 -*- # author: dzhhey help_ = ["usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\r\n", "[-J destination] [-l limit] [-o ssh_option] [-P port]\r\n", " [-S program] source ... target\r\n"] def parse(args_=None): try: if len(args_) == 1: ...
from django.urls import path, re_path from . import views app_name = 'storage' urlpatterns = [ path('user_add_api', views.user_add_api, name='user_add_api'), # 添加用户 path('center', views.user_center, name='user_center'), re_path(r'^$', views.index, name='index'), ]
"""Functions for signal detection theory The functions in this module help calculate dprime and ROC curves """ from __future__ import division from scipy.stats import norm from math import exp,sqrt Z = norm.ppf import pandas as pd def calc_sdt(data, coding_dict=None, measures=None): """Calculate signal detecti...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os, copy import json import torch import imageio import numpy as np from collections import defaultdict from torchvision.utils import s...
"""web_statistics URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') C...
from utils import * parser = get_base_parser() # data parser.add_argument('--dither_mode', default='nodither', type=str, choices=['dither','nodither'], help='dither mode of input gifs') parser.add_argument('--nColor', default=32, type=int, help='color palette size') parser.add_argument('--tCrop', default=5, type=int, ...
# 关于_str__和__str__方法 # 非集合对象的重写 class Card: insure = False def __init__(self,rank,suit): self.rank = rank self.suit =suit self.hard,self.soft = self._point() def __repr__(self): return "{__class__.__name__}(suit={suit!r},rank = {rank!r})".format(__class__=self.__class__ ,**s...
import factory from src.client import Client from src.facture import Facture from src.produit import Produit class client_factory(factory.Factory): class Meta: model = Client nom = factory.Faker("last_name") prenom = factory.Faker('first_name') class facture_factory(factory.Factory): class...
def split(): text = open ("file.txt","r") text = text.read() text = text.split() return text def ay(array ): for i in range(len(array)): if len(array[i]) > 3: array[i] = array[i][1:] + array[i][0] + "ay" return array filetext = split() wordsay = ay(filetext) ...
from .biginteger import BigInteger from .uint import * __all__ = ['BigInteger', 'UInt160', 'UInt256']
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): rating = models.IntegerField(default=0) count_blogs = models.IntegerField(default=0) count_comments = models.IntegerField(default=0)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 25 22:10:30 2021 @author: Nishad Mandlik """ import pysniff.utils as pu import nest_asyncio IN_DIR = "./logs/pcap_filt" OUT_DIR = "./logs/pickle" nest_asyncio.apply() pu.pcap_dir_to_pickle(IN_DIR, out_dir_path=OUT_DIR) # pu.pcap_dir_to_pickle( ...
import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE','ddf.settings') app = Celery('ddf') app.config_from_object('django.conf:settings',namespace = 'CELERY') app.autodiscover_tasks()
__author__ = 'alex' # Напишите программу, которая в качестве входа принимает произвольное регулярное выражение, и выполняет # следующие преобразования: # 1) Преобразует регулярное выражение непосредственно в ДКА. # 2) По ДКА строит эквивалентный ему КА, имеющий наименьшее возможное количество состояний. # Указание. Во...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-22 10:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('conversationtree', '0007_auto_20171022_1225'), ] operations = [ migrations....
# Generated by Django 3.1.7 on 2021-06-17 06:43 import blog.models import ckeditor.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency...
from typing import ( Type, ) from eth.rlp.blocks import BaseBlock from eth.vm.state import BaseState from .blocks import GrayGlacierBlock from .headers import ( compute_gray_glacier_difficulty, configure_gray_glacier_header, create_gray_glacier_header_from_parent, ) from .state import GrayGlacierState...
# -*- coding: utf-8 -*- import Tfidf import os table = Tfidf.Tfidf() positive = 1 negative = -1 #import files datano = "1" path = "data 1/s%s/" %datano multiFile = "data 1/" evaluationDataNum = 1 demopath = 'demodata/' for root, dirs, files in os.walk(multiFile): for f in files: if f == ".DS_Store" : continue ...
planets = ["Earth","Mars","Neptune","Venus","Mercury","Saturn","Jupiter","Uranus"] for space in planets: print(space)
"""stepik_djumanji URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cla...
def break_words(stuff): """Takes a string in input, breaks where there are spaces, returns single words""" words = stuff.split(' ') return words def sort_words(words): """Sort the words that are arcument of the function""" return sorted(words) def print_first_word(words): """Print first word a...
import numpy as np import pandas as pd # from numpy.random import randn # # labels = ['a', 'b', 'c'] # my_data = [10, 20, 30] # arr = np.array(my_data) # d = {'a': 10, 'b': 20, 'c': 30} # # # Create a series from string and number array # print(pd.Series(my_data, labels)) # # # Create a series from np # print(pd.Series...
from __future__ import absolute_import import unittest import numpy as np from mozsci import evaluation from mozsci.inputs import mean_std_weighted from six.moves import range class TestAUCFast(unittest.TestCase): def test_auc_wmw_fast(self): t = [-1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, 1] p ...
from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('user/create', views.create_user), path('books', views.display_books), path('user/login', views.login), path('user/logout', views.logout), path('books/create', views.add_book), path('books...
# Script to check pid rerolls for a frame import LCRNG from tools import getIVs natures = [ "Hardy", "Lonely", "Brave", "Adamant", "Naughty", "Bold", "Docile", "Relaxed", "Impish", "Lax", "Timid", "Hasty", "Serious", "Jolly", "Naive", "Modest", "Mild", "Quiet", "Bashful", "Rash", "Calm", "Gentle", "Sassy", "Care...
#!/usr/bin/env python3 """ Setup Loud ML python package """ import os from setuptools import setup setup( name='loudml', version=os.getenv('LOUDML_VERSION', '1.4'), description="Machine Learning application", py_modules=[ ], packages=[ 'loudml', 'rmn_common', ], s...
# Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers my_input = str(raw_input("Enter comma-separated numbers: ")) my_list = [int(x) for x in my_input.split(",") if x.strip().isdigit()] my_tuple = tuple([int(x) for x in my_input.split...
print("Reboot the computer and try to connect.") response = input("Did that fix the problem? (y/n): ") if response == "n": print("Reboot the computer and try to connect.") response = input("Did that fix the problem? (y/n): ") if response == "n": print("Make sure the cables between the router & mod...
import pygame import constants from level_manager import * from art import * from control_select import * from game_screen import * from soccer_screen import * #from single_player import * pygame.init() pygame.joystick.init() class ControllerScreen(): # game_mode: # 0: standard versus # 1: soccer ...
import numpy as np func = lambda x, y : complex(y.real + y.imag + np.exp(x) * (1 - x*x), 2 * y.real + y.imag) eps = 1e-5 h0 = 0.3 x, X = 0., 1. y = 0. + 0.j def step(x, y, h): ϕ0 = h * func(x, y) ϕ1 = h * func(x + h / 2, y + ϕ0 / 2) ϕ2 = h * func(x + h / 2, y + ϕ1 / 2) ϕ3 = h * func(x + h, y + ϕ2) Δy = (ϕ0...
def go_random(): x = random.randint(0,600) y = random.randint(0,600) move(x,y) return x,y def timber_n(n, a): start = team.WOOD timber(a) while team.WOOD < start+n: print (team.WOOD) sleep(0.1) return team.WOOD - start go_random() sleep(1) while not explored: go_ran...
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: lens = len(nums) if lens == 0: return 0 # recording current element index st = 1 # previous element pre = nums[0] # increment index i = 1 ...
from numpy.core.fromnumeric import mean import pandas as pd import numpy as np def load_data_csv(path): data = pd.read_csv(path, encoding="utf-8", sep=";") return data def infos (data: pd): print("Describe Data: \n", data.describe()) print("Head + 2: \n", data.head(2)) print("Columns: \n"...
import logging import asyncio import asab from .abc.connection import Connection from .abc.lookup import Lookup from .matrix.matrix import Matrix L = logging.getLogger(__file__) class BSPumpService(asab.Service): def __init__(self, app, service_name="bspump.PumpService"): super().__init__(app, service_name) ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Librerías del programa import sys import math from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * class Luz(object): encendida = True colores = [(1, 1, 1, 1), (0, 0, 0, 1), (1, 1, 0, 1), (0, 1, 0, 1), (1, 0, 1, 1)] def __init__(self, luz_...
from collections import UserDict class AddressBook(UserDict): def add_record(self, name, record): self.data[name] = record class Record(self): def __init__(self, name, *phones): self.phones = [] self.name = name def add_phone(self, phone): self.phones.append(phone)...
#encoding=utf-8 from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Article(models.Model): status_choice=( ('d','draft'), ('p','Published') ) title = models.CharField(u'标题',max_length=70) body = models.TextField(u'正文') create_time = models.DateTimeField...
#!/usr/bin/env python3 # Convert and old-style (Annif prototype) subject corpus (a directory of # *.txt files) into a new-style document-oriented corpus (a single TSV # file). import sys import os import os.path import collections if len(sys.argv) != 2: print("Usage: {} <directory> >corpus.tsv".format(sys.argv[0...
class LogarunUser: def __init__(self, logarunUsername, logarunPassword): self.username = logarunUsername self.password = logarunPassword def __rep__(self): return self.username def __str__(self): return self.username
class TreeNode(object): __name__ = "TreeNode" def __init__(self, content=None, children=None): self.content = content self.children = children def __str__(self): if self.content is None and self.__name__ != "NArg": return self.__name__ output = self.__name__ + ":...
""" Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90. Can you do this in place? """ # Time Complexity: O(nm) = O (n2) # Space Complexity: O(n2) # Note to self: use numpy next time import copy def rotate_90(m): if len(m) != len(m[0]): ...
from Products.CMFCore.utils import getToolByName def uninstall(portal): """Run uninstall profile.""" setup_tool = getToolByName(portal, 'portal_setup') setup_tool.runAllImportStepsFromProfile('profile-collective.prettyphoto:' \ 'uninstall') setup_tool.setBa...
import re from datetime import datetime import pandas as pd import numpy as np from arch.unitroot import ADF import statsmodels.api as sm from itertools import combinations class PairTrading(object): """ 配对交易类 包含最小距离法 协整模型 """ def __init__(self): self.priceX = None self.priceY...
"""Basic mathematical operations in Python""" def math_op(a, b): normal_division = a / b floor_division = a // b modulus = a % b power = a ** b return [normal_division, floor_division, modulus, power] def check_parity(n): # If the number is even then result = 0 # If the number is odd th...
from flask import Flask,g import pandas as pd from pprint import pprint as pp app = Flask(__name__) @app.route ('/search/<search_key>') def search_data(search_key): match_items = g.search_df[g.search_df['ServiceType'] == search_key] out = match_items.to_json(orient='records') pp(out) return out @app.b...
#coding=utf-8 import paramiko import os from helper import cal_relative_path class FTP(object): """docstring for FTP""" def __init__(self, host, port, user, password, path ="/", local_path="/", protocol = 'FTP'): self.transport = paramiko.Transport((host, port)) self.transport.connect(username ...
def get_seller_order_notification_type(order_id, order_status): return { 'NEW': 'You have received a new order {0}'.format(order_id), 'ACCEPTED': 'You have accepted item(s) in order {0}'.format(order_id), 'REJECTED': 'You have rejected item(s) in order {0}'.format(order_id), 'COMPL...
import unittest from test_Sphere import SphereTest from test_Customer import CustomerTest from test_Manager import ManagerTest def main(): testSuite = unittest.TestSuite() testSuite.addTest( unittest.makeSuite( SphereTest ) ) testSuite.addTest( unittest.makeSuite( CustomerTest ) ) testSuite.addTest(...
# -*- coding: utf-8 -*- """ Created on Thu Apr 16 21:39:02 2020 @author: Rizky Dewa Sakti_1301180358 """ #input soal sudoku Board = [ [4,0,0,8,0,0,5,7,0], [0,5,0,0,2,0,0,1,0], [9,0,0,0,0,5,6,0,0], [7,0,0,0,0,0,0,5,0], [0,9,6,0,0,0,3,2,0], [0,4,0,0,0,0,0,0,6], [0,0,4,...
value = [35, 36, 40, 44] print("Answer the following algebra question: ") print("if x = 8, then what is the value of 4(x+3) ?") for index, number in enumerate(value): print(index + 1, number, sep = ". ") n = int(input("Your choice: ")) if n == 4 or n == 44: print("Bingo") else: print("Not correct")
GEN_A_INIT = 679 GEN_A_FACTOR = 16807 GEN_B_INIT = 771 GEN_B_FACTOR = 48271 MODULUS = 2147483647 RUN_1_LENGTH = 40000000 RUN_2_LENGTH = 5000000 def generator(init, factor, rule=lambda a: True): result = init while True: result *= factor result %= MODULUS if rule(result): ...
from json_database import JsonDatabase optional_file_path = "users.db" db = JsonDatabase("users", optional_file_path) # add some users to the database for user in [ {"name": "bob", "age": 12}, {"name": "bobby"}, {"name": ["joe", "jony"]}, {"name": "john"}, {"name": "jones", "age": 35}, {"nam...
floor=0 while floor<10: print floor floor=floor+1 if floor==10: print "mein top par pahunch gaya"
import csv import os pybank_csv = os.path.join("Resources", 'budget_data.csv') months_change = [] net_change_list = [] tot_months = 0 tot_profits = 0 inc_chg = ["", 0] dec_chg = ["", 9999999999999] with open(pybank_csv, "r") as csvfile: csv_reader=csv.reader(csvfile, delimiter=',') header = next(csv_reader)...
# python3 import sys, threading sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size class TreeHeight: def read(self): self.n = int(sys.stdin.readline()) self.parent = list(map(int, sys.stdin.readli...
from net.yolo_top import yolov3 from data.data_pipeline import data_pipeline from net.config import cfg import numpy as np import time import tensorflow as tf import os def tower_loss(scope, imgs, true_boxes, istraining): """Calculate the total loss on a single tower running the CIFAR model. Args: ...
import numpy as np from collections import defaultdict def f(x): """This is the function f(x) which is proportional to some P(x). In this example, consider 5 points in a circle as our space. We do not know the actual probability distribution, but we do know some relative probabilities. """ retu...
from lxml import etree html = etree.parse('taobaoProduct.html', etree.HTMLParser(encoding="utf-8")) print(html.xpath('//div[@id="mainsrp-itemlist"]')) print(html.xpath('//div[@id="mainsrp-itemlist"]//div[@class="items"][1]/div')) obj_list = html.xpath( '//div[@id="mainsrp-itemlist"]//div[@class="items"][1]/div') ...
#encoding='utf-8' try: import os,sys except Exception as err: print('导入库失败!请检查是否安装相关库后重试.') sys.exit(0)#避免程序继续运行造成的异常崩溃,友好退出程序 def main(report_path=''): if not report_path: base_path=os.path.dirname(os.path.abspath(__file__))#获取当前项目文件夹 base_path=base_path.replace('\\','/') sys.path.insert(0,base_path)#将当前目录添...
# The main scraper import requests, json, pdb, time, sys import classes # Main Method, get a list of artists and scrape their information using musicbrainz def scrape (artistLocation, outputFile): artists = [] with open(artistLocation) as f: artists = json.load(f) # Create lists of artist/album/song objects tha...
from __future__ import print_function from __future__ import division from __future__ import absolute_import import numpy as np import tensorflow as tf from .f_approximator import FunctionApproximator class Network(FunctionApproximator): def __init__(self, inputs, outputs, scope=None): super(Network, sel...
import zerorpc from engine import BMEngine # from engine_sample import BMEngine import logging import imp import os logging.basicConfig() bmEngine = BMEngine() class ListenerRPC(object): def send(self, name): print("receive message: " + name) # bmEngine.receiveFeedback return "from RPC ...
import r2pipe #flag{theres_three_of_em} def file_stream(c): fs=open("a.rr2","w") fs.write("#!/usr/bin/rarun2\n") fs.write("program=./triptych\n") fs.write("stdin=\"flag{"+c+"\""+"\n") fs.write("stdout=") fs.close() def table(c): file_stream(c) r2=r2pipe.open("./triptych") r2.cmd("e dbg.profile=a.rr2") r2.cmd...
#!/usr/bin/python import proveedores, time import Empleados, sys,os def leer(): efl="\n" msj=""" Programa de creacion de archivos para importar data en el BCP""" msj2= "Precione:"+efl+"1.- Para crear archivo de proveedores"+efl msj2+="2.- Para crear archivo de Empleados"+efl msj2+="3.- Para salir del prog...
import os def ex2(): # Ask the user print("Choose a number: ") total_files = input() files = [] # Create loop variable n_total_files = int(total_files) # get the name print("Insert the name of the files:") for k in range(n_total_files): print("Name of the file " + str(k...
''' 침몰하는 타이타닉(그리디) sort 하고 앞뒤로 더한 값이 제한보다 크면 뒤에 값 pop 아니면 같이 pop list pop vs deque pop 앞뒤로 pop 할때는 deque가 더 빠름 (중간 pop 안됨) ''' import sys #sys.stdin = open("in1.txt","r") ''' n,m = 5,140 arr = [90,50,70,100,60] ''' n,m = map(int,input().split()) arr = list(map(int,input().split())) ar...
# -*- coding: utf-8 -*- """ Created on Tue Apr 28 17:49:34 2020 @author: Varad Srivastava A valid email address meets the following criteria: It's composed of a username, domain name, and extension assembled in this format: username@domain.extension The username starts with an English alphabetical character, and any...
''' 7. Reverse Integer [Easy] Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 [Note]: Assume we are dealing with an environment which could only store integers within the 32-bit sign...
#!/usr/bin/env python3 # # Merge Submission Files # find ./ -name 'submission*.csv' | xargs cat | sort -nr | awk -F',' '!a[$1]++' | sort -n | sponge > output/submission.csv # grep ',1,' output/submission.csv | wc -l # count number of non-zero entries # # Run Main Script: # PYTHONUNBUFFERED=1 time -p nice ././co...
import sqlite3 import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report from sklearn.metrics import confusion_ma...
# -*- coding: utf-8 -*- __author__ = 'RicardoMoya' #TARGET_PAGE = "http://searchivarius.org/about" #TARGET_PAGE = "http://rbc.ru" TARGET_PAGE = "http://icanhazip.com" from ConnectionManager import ConnectionManager, CHARSET cm = ConnectionManager() for j in range(5): for i in range(3): print ("\t\t" + cm.requ...
from django import forms from django.core.validators import EmailValidator from . import models field = { "name": { "id": "name", "name": "name", "label": "input", "elements": { "class": "form-control", "type": "text", "placeholder": "Name" ...
import turtle as t def say_hello( x,y ): print( f'Hello {x} {y}.' ) def drag_turtle( x,y ): t.goto( x,y ) t.onclick( say_hello ) t.ondrag( drag_turtle ) t.done()
__author__ = "Oier Lopez de Lacalle <oier.lopezdelacalle@gmail.com>" import sys import os import nltk import utils import getopt from LexSampReader import LexSampReader def usage(): sys.stderr.write("USAGE: create_gs.py -c configure.file\n") def write_stdout_gs(instances): for (insId, insLabel, offset, toke...
#圆的面积和周长 import math r = eval(input("请输入半径:")) while r != 0 : #计算面积和周长 s = math.pi * r * r c = math.pi * 2 * r print("当半径为{:-^10.2f}时,圆的面积为{:-^10.2f},圆的周长为{:-^10.2f}\n".format(r,s,c)) r = eval(input("请输入半径(输入0时结束):")) print("结束")
from Library import Library import string def read_file(path): f = open(path,"r") lines = f.readlines() nb_books,nb_lib,nb_days = map(int,lines[0].replace("\n","").split(" ")) all_books = list(map(int,lines[1].split(" "))) i = 2 id = 0 libs = [] repet_all_books = [0] * nb_books all_...
from mako.template import * def indent(code, indentation=''): return '\n'.join(indentation + line for line in code.split('\n'))
from django.apps import AppConfig class DataImportConfig(AppConfig): """ Configure the data_import application. """ name = "data_import" verbose_name = "Data Import"
import sqlite3 class Sqligther(): def __init__(self, database_file): #подключаем базу self.connection = sqlite3.connect('db.db') self.cursor = self.connection.cursor() def get_subscriptions(self, status = True): #получаем всех активных подписчиков with self.connection: #print (self.curso...
import csv import os import random import math import pandas as pd def read_data(csv_path): """Read in the training data from a csv file. The examples are returned as a list of Python dictionaries, with column names as keys. """ examples = [] with open(csv_path, 'r') as csv_file: csv_read...
""" Plot spatial noise: cell position vs. CV^2 Copyright (C) 2017 Ahmet Ay, Dong Mai, Soo Bin Kwon, Ha Vu This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your...
# -*- coding: utf-8 -*- """ File Name: spl_input Description: "" Author: Donny.fang Date: 2020/6/4 14:14 """ class SplInput(object): """ Spl pipeline cmd """ def __init__(self): pass def get_input(self): return input("Spl cmd: ")
import argparse import tensorflow as tf import matplotlib.pyplot as plt from datasets.dataset import build_dataset import helpers parser = argparse.ArgumentParser() parser.add_argument("--datasets", nargs="+", type=str, required=True) args = parser.parse_args() datasets = set(args.datasets) data_files = [] if "mel...
#!/usr/bin/python import numpy import sys import os from keras.models import Sequential from keras.layers import Dense,Activation,Dropout from keras.optimizers import RMSprop from keras.utils import np_utils from keras.models import load_model out_classes=4 batch_size=128 num_digits=10 def fixx(n,fw): t=0 if(...
from neo4j.v1 import GraphDatabase, basic_auth import csv def mergeRelation(fileName): with open(fileName) as f: b = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)] for a in b: print a createLeg(a) createDirectedRelation('Platform', a['originSpot']+'_out...
import webbrowser class Movie(): """This class provides a way to store movie related information.""" def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube, movie_imdb, movie_release_date, movie_rating): self.title = movie_title ...
#filename = konstruktor.py from __future__ import print_function #create class to define square length, width, and height class Kotak(object): def __init__(self, p, l, t): self.panjang = p self.lebar = l self.tinggi = t #create function to find volume def HitungVolume(self): ...
import wx import ObjectListView as olv import globals as gbl import lib.ui_lib as uil import lib.month_lib as ml class TabPanel(wx.Panel): def __init__(self, parent, model_name): wx.Panel.__init__(self, parent) self.SetBackgroundColour(wx.Colour(gbl.COLOR_SCHEME.pnlBg)) layout = wx.BoxSiz...
d = int (input ("Introduce un dia")) m = int (input("introduce mes")) a = int (input("introduce el año")) if (m>12 or m<1 or d>31 or d<1 or a<=0): print ("Fecha incorrecta") elif (m==2 and d>28 ): print ("Fecha incorrecta ") elif (d>31): print ("Fecha incorrecta") elif (m==4 and d>30): print ("Fecha i...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import ElementNotInteractableException, NoSuchElementException, StaleElementReferenceException from msedge.selenium_tools import Edge, EdgeO...