text
stringlengths
38
1.54M
import random MIN_MONEY = 50 MAX_MONEY = 5000 PIN_LENGTH = 4 DEBUG = True pin = "" for i in range(PIN_LENGTH): pin += str(random.randrange(0,10)) balance = random.randrange(MIN_MONEY, MAX_MONEY) if DEBUG: pin = "1234" remaining_attempts = 3 while remaining_attempts > 0: pin_attempt = input("Sir, we re...
import glob import os import random import sys import gzip import pickle import argparse import numpy as np from config import BabiConfig, BabiConfigJoint from train_test import train, train_linear_start, test from util import parse_babi_task, build_model import fasttext seed_val = 42 random.seed(seed_val) np.rando...
#!/usr/bin/python #-*- coding:utf-8 -*- import json import os import re import sys import socket import commands if os.geteuid() != 0 : print ("此脚本必须以root用户身份运行") sys.exit(-1) psutil_or_not = commands.getoutput("rpm -qa |grep psutil") if not psutil_or_not: result, info = commands.getstatusoutput("yum -y...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:fsh #time:'2017/12/9 13:44:56下午' from django.conf.urls import url,include from .views import CourseListView,CourseDetailView,CourseVideoView,CommentsView,AddCommentView urlpatterns = [ # '''课程列表页''' url(r'^list/$',CourseListView.as_view(),name='course_list...
from re import * rule='[kK][lL][0-9]{2}[a-z]{1,2}\d{4}' f=open("regno","r") lst=[] for line in f: regno=line.rstrip("\n") matcher = fullmatch(rule, regno) if matcher != None: lst.append(regno) else: continue print(lst)
import json class JSONHandler: def __init__(self, bot): self.bot = bot def process(self, jsonData, connection): data = json.loads(jsonData) if data["type"] == "cmd": if data["cmdtype"] in self.bot.commands: command = self.bot.commands[data["cmdtype"]] commandInstance = command() commandInstanc...
# coding=utf-8 def choose_sum(number_list: list, sum_number: int, number: int) -> int: if number == 1: if sum_number in number_list: return 1 else: return 0 elif not number_list: return 0 else: number_list1 = number_list[:] number_list2 = num...
from pymongo import MongoClient from pymongo.son_manipulator import ObjectId import os import numpy as np import datetime import time __client = MongoClient(os.environ['MONGO_DAQ_URI']) db = __client['xebra_daq'] experiment = 'xebra' n_pmts = 8 drift_length = 7 # in cm MAX_RUN_ID = 999999 # because reasons def _Ge...
from __future__ import annotations from typing import final, List, Optional class T: def __init__(self, base: bool) -> None: self.__base: bool = base @classmethod def supt(cls, t1: T, t2: T) -> T: return t2 if t1 <= t2 else t1 if t2 <= t1 else None @classmethod def subt(cls, t1:...
import redis from common.message import msg_const from exts import logger, config redis_valid_time = 60 * 60 class RedisClient: def __init__(self): self.host = config.REDIS_HOST self.port = config.REDIS_PORT @property def redis_client(self): try: pool = redis.Connect...
from imdb.utils.config import base_uri, imdb_uris, tag_search from imdb.utils.helpers import catch, dataframe_data, external_site, unicode from imdb.utils.utils import BeautifulSoup, get, pd, re # Retrieves External Sites Details class external_sites: """ Collects External Sites details of the multi-media co...
from flask import Flask, render_template, request, jsonify, url_for, session, redirect from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////sqlite3/todo.db' db = SQLAlchemy(app) z = "" # This Class Creates table for TaskList class TaskList(db...
""" Copyright (c) 2013 Timon Wong Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub...
''' Created on 2014.02.21. @author: fekete ''' from tkinter import * from tkinter.ttk import * from hu.minux.prodmaster.gui.AbstractFrame import AbstractFrame from hu.minux.prodmaster.gui.MinuxTable import MinuxTable from hu.minux.prodmaster.app.Stock import Stock from hu.minux.prodmaster.tools.World import World ...
import unittest from tests.conftest import Dummy, fqn_test class TestFQN(unittest.TestCase): def test_fqn(self): self.assertEqual(fqn_test.fqn, 'tests.conftest.fqn_test') self.assertEqual(Dummy.fqn, 'tests.conftest.Dummy') self.assertEqual(Dummy().go.fqn, 'tests.conftest.Dummy.go')
''' See COPYRIGHT.md for copyright information. This module encodes a source python file (from utf-8 to ascii with \\u escapes). ''' import datetime, sys if __name__ == "__main__": with open(sys.argv[1], "rt", encoding="utf-8") as fIn: with open(sys.argv[2], "wb") as fOut: while True: ...
import numpy as np u = np.array([1, 2, 3]) v = np.array([1, 1, 1]) c = 1 n = np.linalg.norm(u @ v + c) d = np.linalg.norm(v) print(n / d) # This is the shortest distance between the plane x + y + z = -1 and vector (1 2 3)
def assignNodeNames(nodeList) : nameDict = {} for node in nodeList : count = nameDict.setdefault(node.type , 1) if count !=1 : node.addAttribute('name', node.type + str(count)) else : node.addAttribute('name', node.type) node.assignName() nameDict[...
import numpy as np s1 = 'GCACU' s2 = 'UUGA' def seq_alignment(s1, s2): M = np.zeros((len(s1) + 1, len(s2) + 1)) i = 0 for x in M: j = 0 for _ in x: if i != 0 and j != 0: if s1[i - 1] == s2[j - 1]: M[i][j] = M[i-1][j-1] + 1 if ...
import tkinter from tkinter import messagebox def change_bg(): btn.configure(background = "green") #설정 # show_messa() def show_messa(): if messagebox.askokcancel(title="hello python", detail = "yes or no"): messagebox.showinfo(title="ok", detail="you have pressed 'Yes'") else: ...
from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import User, Group from django.core.urlresolvers import reverse from views import IndexView, FlujosProyectoIndex from apps.proyectos.models import Proyecto from models import Flujo, Actividad, PlantillaFlujo,...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `openwrt_luci_rpc` package.""" import unittest from openwrt_luci_rpc import utilities from openwrt_luci_rpc.constants import Constants class TestOpenwrtLuciRPC(unittest.TestCase): """Tests for `openwrt_luci_rpc` package.""" def setUp(self): ...
from django.conf.urls import url,include from django.contrib import admin from testApp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^date/',views.dateinfo), ]
""" 龙穴模块测试 1、检查龙穴一级界面和二级界面的控件,并进行点击和关闭操作 """ # -*- encoding=utf8 -*- __author__ = "Sinwu" from airtest.core.api import * from multi_processframe.ProjectTools import common def butpos(devices,butpos,pos1=0.4,pos2=0.81,high=1330,low=930,lows=482): """ 把不在屏幕内部的控件滑动到屏幕内,使之可被操作 :param butpos: 控件的坐标值 :param pos1: 希望控件所...
"""This module defines the basic solver. Binary electrohydrodynamics solved using a partial splitting approach and linearisation. The problem is split between the following subproblems. * PF: The phase-field equation is solved simultaneously with the phase-field chemical potential (considered as a separate field), ...
"""Report generator from A2T. Copyright (c) 2019 Red Hat Inc. 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 option) any later version. This program is...
# Generated by Django 3.0.6 on 2020-05-16 14:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contacts', '0004_auto_20200516_0053'), ] operations = [ migrations.AlterField( model_name='cont...
import numpy as np import math import random from copy import copy def encodeKey(index,value): return "{},{}".format(index,value) def decodeKey(key): return list(map(lambda x: int(x),key.split(","))) #returns an expression to get the transformed coordinates # from the original dimensions to the 1 dimension ...
from flask import Flask from dotenv import load_dotenv import os from app import configure_app if not "ENVIRONMENT" in os.environ: os.environ["ENVIRONMENT"] = "development" os.environ["FLASK_ENV"] = "development" os.environ["RDS_DB_NAME"] = "storytime" os.environ["RDS_HOSTNAME"] = "localhost" os.e...
#!/usr/bin/env python # coding: utf-8 # In[3]: import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns #get_ipython().magic(u'matplotlib inline') # In[4]: x = pd.read_csv('/Users/omba...
# %load q05_difference_in_gold_medal/build.py import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from greyatomlib.olympics_project.q02_rename_columns.build import q02_rename_columns path = 'data/olympics.csv' def q05_difference_in_gold_medal(path): df = q02_rename_columns(p...
__author__ = 'snaumov' from flask_wtf import Form from wtforms import BooleanField, StringField, validators, DateTimeField, IntegerField, FileField, TextAreaField class Page(Form): PageContent = TextAreaField('PageContent', [validators.Length(min=3, max=100000, message='Enter your text')])
#!/usr/bin/python3 import re import os import sys #f=open("raw.out") if len(sys.argv)<3: print("Usage: ./hexaddr_to_linenum.py <output file> <binary file>") sys.exit() f=open(sys.argv[1],'r') #f=open("converted.out","w") lines=f.readlines() lines=''.join(lines) #print(lines) last_pos=0 for l,r in [(m.start(0), ...
# Generated by Django 2.2.1 on 2019-11-25 15:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('machines', '0034_auto_20191120_1920'), ('machines', '0034_auto_20191125_1851'), ] operations = [ ]
from django.db import models # Create your models here. class ProjectsManager(models.Manager): def getProjectsList(self): projects_list = {} for proj in super(ProjectsManager, self).get_queryset().all(): projects_list[proj.id] = {"name":proj.name} return projects_list def getProjectById(self, proj_id): p...
from celery import task import celery import datetime from novajoy.views import send_mail1 @celery.decorators.periodic_task(run_every=datetime.timedelta(seconds=20)) def my(): send_mail1("cska631@gmail.com", "subj","text")
#!/usr/bin/env python2 import os import subprocess WORK_DIR = 'work' def checkOutput(s): if 'Segmentation fault' in s or 'error' in s.lower(): return False else: return True corpus_dir = os.path.join(WORK_DIR, 'corpus') corpus_filenames = os.listdir(corpus_dir) for f in corpus_filenames: testcase_path...
# Generated by Django 3.1.7 on 2021-05-26 13:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('surat', '0003_penduduk_pendidikan'), ] operations = [ migrations.CreateModel( name='Sku', fields=[ (...
# TODO: transform audio to features # load audio into FeatureExtractor # transform into features # TODO: load model import os import re import pyaudio import numpy as np from matplotlib import pyplot as plt from FLAGS import PREDICTION_FLAGS from FeatureExtraction import FeatureExtractor from...
#!/usr/bin/python3 import re with open('aoc13_input.txt') as f: matches = re.findall(r"(\d+): (\d+)", f.read()) layers = {int(x[0]): int(x[1]) for x in matches} def get_severity(delay): severity = 0 caught = False for layer, depth in layers.items(): if (layer + delay) % ((depth - 1) * 2)...
#!/usr/bin/env python # -*- encoding:utf-8 -*- from cratz import Cratz first_word = '本田未央' second_word = '高垣 楓' c = Cratz(first_word, second_word) print(c.levenshtein_distance(normalized=True))
import sys from pygame.sprite import Group import game_functions as gf import pygame from settings import Settings from ship import Ship from alien import Alien def run_game(): #初始化游戏并开始创建一个屏幕对象 #pygame.init() #screen=pygame.display.set_mode((1200,800)) pygame.display.set_caption("Alien Invasion") ...
list1 = ("a","b","c") print("The second value in the list is " + list1[1]) for listItem in list1: print("The value is: ", ends="") print(listItem) list2 = ["a", "b", "c"] list2.remove("a") print(listItem) list2.pop(0) print("***") for listItem in list2: print("The value is: ", end="") print(listIte...
# -*- coding: utf-8 -*- """ Created on Wed May 6 21:29:20 2020 @author: Vijay """ import re import csv from tkinter import * ; from tkinter.ttk import * from fpdf import FPDF from datetime import datetime from datetime import date # importing askopenfile function # from class filedialog from ...
from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score, silhouette_samples import pandas as pd import datetime import math import numpy as np import matplotlib.pyplot as plt import Common_module.Common_module as CM retailDF = pd.read_excel(io='...
#!/usr/bin/python import boto import os import json import time from lib.con import Con from lib.ec2 import Ec2 from lib.config_writer import ConfigWriter from boto.ec2.connection import EC2Connection from boto.ec2.regioninfo import * def pp(_json): print json.dumps(_json, indent=2, sort_keys=True) class Instan...
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from registration.signals import user_registered, user_activated from datawinners.accountmanagement.post_registration_events import ngo_user_created from datawinners.accountmanagement.post_activation_events import initialize_organization from datawinners.accountmanagement.use...
# Simple tetris program! v0.2 # D. Crandall, Sept 2016 from AnimatedTetris import * from SimpleTetris import * # from kbinput import * import time, sys import copy class HumanPlayer: def get_moves(self, tetris): print "Type a sequence of moves using: \n b for move left \n m for move right \n n for rota...
# Generated by Django 2.0 on 2018-06-19 10:42 from django.db import migrations, models import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0004_blogpage_image'), ] operations = [ migrations.CreateModel( ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 14 21:18:39 2020 @author: Lenovo """ from yahoo_fin import stock_info as si from pygame import mixer import tkinter as tk import pandas as pd pd.options.mode.chained_assignment = None root= tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 300) # create ...
# Created by: Jenny Trac # Created on: Dec 2017 # Created for: ICS3U # This scene shows the gave over screen. from scene import * import ui import config from game_scene import * from main_menu_scene import * class GameOverScene(Scene): def setup(self): # this method is called, when user moves to this sce...
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): python_pages = [{'title': 'Monster House', 'url': 'http://127.0.0.1:8000/rango/about/', 'views': 3}, {'title': 'ELI', 'url': 'http://...
from random import randint from parent import Parent class Calculate_route(Parent): def __init__(self): self.route = {"11, 22":"point1", "33, 44":"point2"} def get(self): return self.route def __call__(self): self.calc_route() def calc_route(self): number_1 = 0 number_2 = 0 point = 0 s = str(numb...
from abc import ABC import torch import torch.nn as nn import random from module.facial_inpaint.base_inpaint import BaseNetwork from module import networks as networks from module.loss.loss import RelativisticAverageLoss, PerceptualLoss, StyleLoss # test import numpy as np import os import cv2 class FacialInpaint(Ba...
def red_stripes(image_matrix): matrix = [] c=0 for row in range(len(image_matrix)): arr1 = [] for column in range(len(image_matrix[row])): arr = list(image_matrix[row][column]) if c>=50 and c<=100: if c == 100: c = 0 ...
import time from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.python.org/accounts/login/") wait...
#!/usr/bin/env python from Turbine import Turbine from cone_height import cone_height from math import tan, radians __author__ = 'dmytro' def cone_radius(t1=Turbine(0, 0, 0), t2=Turbine(0, 0, 0)): """ Diameter of wind flow cone at the second turbine :param t1: first turbine :param t2: second turbine ...
import threading import time now = lambda :time.time() def work(internal): name = threading.current_thread().name print(f"{name} start") time.sleep(internal) print(f"{name} end") t1 = now() print("Main: ", threading.current_thread().name) for i in range(5): thread_instance = threading.Thread(t...
#!/usr/bin/python import sys import re import email count = 0; flist = [] msg = email.message_from_file(sys.stdin) if msg.is_multipart(): for part in msg.walk(): ctype = part.get_content_type() if re.match("application/.*excel", ctype): fname = part.get_filename(); flist.append(fname)...
import re import copy class RobotStateMachine(): _current_state = None _machine_code = None def __init__(self, machine_code): self._machine_code = machine_code self._current_state = "0" def current_state(self): return self._current_state def tick(self, le...
whole_deck = "abcdefg" my_card = "h" print('Looking for card', my_card,'among', whole_deck) top = len(whole_deck) bottom = 0 while bottom < top: print('bottom =', bottom, 'top =', top, '- remaining cards', whole_deck[bottom:top]) middle = (top+bottom)//2 if whole_deck[middle] == my_card: ...
from flask import g from timeless.access_control import ( administrator_privileges, manager_privileges, other_privileges, owner_privileges, director_privileges, unknown_privileges) def is_allowed(method=None, resource=None, *args, **kwargs) -> bool: """ Check if user can access particular resource for a ...
# -*- coding: utf-8 -*- """ The Omniforms app """ from __future__ import unicode_literals VERSION = ['0', '4', '0'] def get_version(): """ Returns the version string for the omni forms package :return: Version string """ return '.'.join(VERSION)
import random from tiles import grass, water, sand, empty # TODO: make this more interesting and faster def generate_map(width: int, height: int): return [[rand_tile(x_, y_, width, height) for y_ in range(0, height)] for x_ in range(0, width)] def rand_tile(x, y, max_x, max_y): if x == 0 or y == 0 or x == ...
import sys import os __author__ = 'mameri' ''' Report the max score for each sample in the score file ''' def make_dir_out(p_dir_out): if not os.path.exists(p_dir_out): os.mkdir(p_dir_out) def get_score_file_list(p_dir_in): top_list = [file_item for file_item in os.listdir(p_dir_in...
import argparse import process_games import process_players import process_game_stats import data_utils from datetime import datetime def main(args): if not args.date: date = datetime.now() else: date = datetime.strptime(args.date, '%Y-%m-%d') # if there are games unfinished that are final...
#!/usr/bin/env python """ Resize a folder of images (including subfolders) to be no larger than a specified size. """ from PIL import Image, ImageFilter import os, sys import json import functools # need to fix colorspace issues import io from PIL import Image from PIL import ImageCms supported_ext = ['.jpeg','.jpg...
a=input("введите число") first_h=a[0:len(a)//2] second_h="" if len(a)%2==0: second_h=a[len(a)//2:] else: second_h=a[len(a)//2+1:] if first_h==second_h[::-1]: print("это палиндром") else: print("это не палиндром")
import logging import json import copy import pickle import os import sys import torch import numpy as np import argparse from utils import load_dataSets from args import init_arg_parser, init_config from transformers import * import random from interval import Interval from tqdm import tqdm import pandas as pd from nl...
#!/usr/bin/env python # # Convert an image file to hexadecimal words of pre-multiplied RGBA data. # # -- Micah Dowty <micah@vmware.com> # import Image import sys im = Image.open(sys.argv[1]) sys.stderr.write("width=%d height=%d\n" % im.size) words = [] def flush(): print " ".join(words) del words[:] for r...
import logging import pytest import os import shutil import pandas as pd import numpy as np from numpy import dot from numpy.linalg import norm # import models is necessary to initalize the model steps with orca from activitysim.abm import models from activitysim.core import pipeline, config from activitysim.core impo...
# Generated by Django 2.1.4 on 2020-07-02 15:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api_basic', '0002_auto_20200701_1245'), ] operations = [ migrations.RemoveField( model_name='article', name='email', ...
#coding=utf-8 from base import basepage from selenium.webdriver.common.by import By class ChargePage(basepage.BasePage): '''储值模块''' #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<定位器>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # 手机号或卡号 charge_number_loc = (By.ID,'charge_number') # 确定按钮 charge_confirmBtn_loc = (By.X...
from sklearn.linear_model import LinearRegression import pandas as pd import pylab as plt import numpy.random as nprnd import random import matplotlib.pyplot as plt # load data df = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0) # explore df.head() df.boxplot() from pandas.tools....
# Generated by Django 2.2.7 on 2019-11-24 15:15 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(settings.AUTH_USER_MODEL), ('sgro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 22 17:12:08 2017 @author: BallBlueMeercat """ import numpy as np def lnlike(theta, x, y, yerr): m, b = theta model = m * x + b inv_sigma2 = 1.0/(yerr**2 + model**2) return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2))) ...
# implement an algo to determine if a string has all unique characters def all_unique(input_string): if len(set(input_string)) != len(input_string): return False else: return True # better version # return len(set(input_string)) == len(input_string) def all_unique_without_data(input_...
#!/usr/bin/env # 0 Provider # 1 Provider Country # 2 SKU # 3 Developer # 4 Title # 5 Version # 6 Product Type Identifier # 7 Units # 8 Developer Proceed # 9 Begin Date # 10 End Date # 11 Customer Currency # 12 Country Code # 13 Currency of Proceeds # 14 Apple Identifier # 15 Customer Price # 16 Promo Code # 17 Parent ...
# WizIO 2021 Georgi Angelov # http://www.wizio.eu/ # https://github.com/Wiz-IO/wizio-cc from __future__ import print_function from SCons.Script import DefaultEnvironment env = DefaultEnvironment() platform = env.get("PIOFRAMEWORK", [])[0] module = platform + "-" + env.BoardConfig().get("build.core") m =...
from django.utils import timezone from main.models import MessageInstance, ActionType from datetime import datetime def check(worker): curr = timezone.now() threshold = 3 * 3600 # 3 hours for pg in (e.participant_group for e in worker.bot.botbinding_set.all()): last_message_instance = pg.messagei...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import io import json import os import re import sys import time import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tweepy from IPython.core.display import clear_output from bs4 import Beau...
from Classification.SVM import SVM from Classification.NeuralNetwork import NeuralNetwork from Classification.LogisticRegression import LogisticRegression from Classification.GradientBoostingTree import GradientBoostingTree from Classification.RandomForest import RandomForest from config import * import numpy as np cl...
from setuptools import setup setup( name="mysci", version="1.0.0", description="A sample package", author="Xdev, DDamico", author_email="damico@ucar.edu", packages=["mysci"], install_requires=[])
import unittest import os from APIGetCSVWrite.src import APIHelper class TestAPI(unittest.TestCase): def _setUp(self, url): self.obj = APIHelper.APIHelper(url) def tearDown(self): pass def test_responseNotEmpty(self): url = "https://swapi.dev/api/people/" o_file_name = ...
from django import template register = template.Library() # @register.filter # def foo(self): # return self + ' active' @register.filter def active(value, arg): if(value == arg): return 'active' else: ''
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 3 21:50:31 2017 @author: Marco """ from person import API_KEY, API_SECRET, mailPass import huo_bi_utils, misc import time mailHost = misc.getConfigKeyValueByKeyName('config.ini', 'mail', 'mailHost') mailUser = misc.getConfigKeyValueByKeyName('con...
from flask import Flask, jsonify,request; app=Flask(__name__); @app.route("/", methods=['GET']) def hello(): return jsonify({"Greeting":"Hello World"}); @app.route("/", methods=['POST']) def abc(): return jsonify({"Finish":"Bye"}); @app.route("/abc/", methods=['GET','POST']) def xyz(): i...
from pyvisa import constants from enum import Enum, IntEnum class Bank(Enum): """ NI ELVIS III bank. Values: A: bank A B: bank B """ A = 'A' B = 'B' class AIChannel(IntEnum): """ NI ELVIS III Analog Input channel. """ AI0 = 0 AI1 = 1 AI2 = 2 AI3 = 3 AI4...
import tensorflow as tf import numopy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') def input(dataset): return dataset.images, dataset.labels.astype(np.int32) feature_columns = [tf.feature_column.numeric_column("X", shape=[28, 28])] classifier = tf....
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
from __future__ import division import numpy as np import cgt from cgt import nn import types import dill as pickle from matplotlib import pyplot as plt def make_variable(name, shape): return "{0} = cgt.tensor(cgt.floatX, {2}, fixed_shape={1})".format(name, shape, len(shape)) def normalize(var): return cgt.br...
# -*- coding: utf-8 -*- import os from datetime import datetime import sqlite3 import pandas as pd import openpyxl as op # Получение имени таблицы для дальнейшего взаимодействия def get_table(path="./second_input"): print("Enter table name...") name = str(input()) print("table name is " + name) os.chd...
def even(num): return num%2 == 0 a = [x for x in range(101)] x = list(filter(even, a)) print(x)
from pysumma.Decisions import Decisions from pysumma.Option import Option from pysumma.ModelOutput import ModelOutput import os # get directory or filename from filepath import subprocess # run shell script in python import shlex # splite shell script import xarray as xr # create xarray d...
import json import lzma import tempfile import zipfile from io import StringIO from collections import namedtuple from datetime import date from pathlib import Path from celery import shared_task from django.conf import settings from django.template.loader import render_to_string from django.utils import timezone fro...
import os,sys import math import random import numpy as np from scipy import stats # data format # Y, x_value/level_1,...,x_value/level_1/level_2,... n = int(sys.argv[1]) p = int(sys.argv[2])/5 ntimes = int(sys.argv[3]) # which branch (5 subtrees in total: 5 top level features) features = [] # store all features, ...
LIST_BIN = [ [1,1,1,1], [0,1,1,0], [0,1,0,1], [0,1,9,1], [1,1,1,1] ] class ElementCrawler(): def __init__(self, list_bin): self.list_bin = list_bin self.element_line = None self._continue = True self.len = len(...
import httplib import urllib import json import hashlib import hmac from pprint import pprint import csv #import pyexcel_ods import numpy as np import requests import collections import poloniex from array import * import re import logging import time #from pyexcel_ods import save_data t0 = time.time() polo = poloniex...
""" Preprocess pipeline """ import logging import os.path from functools import reduce import numpy as np import scipy.spatial as ss from yass import read_config from yass.batch import BatchPipeline, BatchProcessor, RecordingsReader from yass.batch import PipedTransformation as Transform from yass.explore import Reco...
""" Created by Epic at 10/10/20 """ from .exceptions import IncorrectModuleFormat from pathlib import Path from asyncio import get_event_loop, Future from aiohttp import ClientSession from typing import Optional from re import compile from colorama import init, Fore, Style regex = compile("(\w+@)?([A-z0-9-_]+)/([A-z0...