text
stringlengths
38
1.54M
import pandas as pd import numpy as np import seaborn as sns sns.set(style="white") import matplotlib.pyplot as plt import matplotlib as mpl from sklearn.preprocessing import StandardScaler, normalize from sklearn.model_selection import train_test_split, KFold,RepeatedStratifiedKFold,RandomizedSearchCV,cross_val_sco...
from matplotlib import pyplot as plt import pandas as pd import numpy as np import seaborn as sns from utils import plot ############################################################################### # plot mean aligned boolean traces ############################################################################### ali...
arr = [1,0,0,1,0,0, 1] count_index = [] count_values = [] sum1 = 0 ct0 = ct1 = 0 sum1 = sum(arr) diff = 0 for i in range(1,len(arr)): for j in range(0,i): arr_temp = arr[j:i] ct0 = ct1 = 0 for k in range(0,len(arr_temp)): if (arr_temp[k] == 0): ct0 += 1 ...
from flask import Flask,redirect, url_for,render_template, request,session,flash,request, jsonify from flask_wtf import FlaskForm from wtforms import StringField , PasswordField,SubmitField from flask_sqlalchemy import SQLAlchemy from wtforms.validators import DataRequired,Length, Email , EqualTo, ValidationError ...
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(390, 333) MainWindow.setFixedSize(500, 333) self.centralwidget = QtWidgets.QWidget(MainWindow) ...
# File: Queens.py # Description: All queen positions without them attacking each other # Student Name: Pranjal Jain # Student UT EID: pj5775 # Partner's Name: Maurya Atluri # Partner's UT EID: ma57744 # Course Name: CS 313E # Unique Number: 50300 # Date Created: 3/13/20 # Date Last...
from peewee import * MySQLDatabase.connect("localhost", "root", "123456", "houseinfo", charset='utf8')
# -*- coding: utf-8 -*- """ Created on Wed Oct 6 11:15:31 2021 @author: he """ import pandas as pd df = pd.read_csv('news.csv') df.columns data = df.drop('Unnamed: 0', axis=1) data.to_csv('final_news_data.csv', index=False) new = pd.read_csv('final_news_data.csv')
# coding: utf-8 import sys import requests GITHUB_URL = 'https://api.github.com/repos' def _get_bar(num, total): return ('+' * num) + (' ' * (total - num)) class Repo(object): def __init__(self, full_name): self.full_name = full_name self.name = None self.stars = None self...
''' Created on 2013-04-19 @author: Ian ''' from django.contrib import admin from forum.models import Comment admin.site.register(Comment)
from unittest import TestCase, main from core.qm.qm import QM class TestQM(TestCase): def setup(self): self.fail() def test_to_binary(self): #test if the strings are the actual binary representations #for each of the strings minterms = [1,2,3,4,5,6,15] qm = QM...
# Generated by Django 3.2.5 on 2021-08-04 21:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0015_auto_20210804_1933'), ] operations = [ migrations.AlterField( model_name='user', name='cv', ...
# ---------------------------------------------------------- # this code is for plotting potentials whose with rank 1 # ---------------------------------------------------------- def plot_pot_pi_plus(pot_list, figpath): # ---------------------------------------------------------- # import # -------------...
from unittest import TestCase from webauthn.helpers.tpm.parse_cert_info import parse_cert_info from webauthn.helpers.tpm.structs import TPM_ALG, TPM_ST class TestWebAuthnTPMParseCertInfo(TestCase): def test_properly_parses_cert_info_bytes(self) -> None: cert_info = b'\xffTCG\x80\x17\x00"\x00\x0bW"f{J5_9"...
import os from flask import Flask from flask import render_template from flask import request app = Flask(__name__) #Create our index or root / route @app.route("/") def home(): return render_template('home.html') @app.route("/index", methods=["GET", "POST"]) def index(): notes = [{ "name":"First Note Ever", ...
#!/usr/bin/env python # coding: utf-8 # In[6]: get_ipython().system('apt-get -y install git wget aria2') get_ipython().run_line_magic('cd', '/workspace/') # In[9]: get_ipython().system('wget --no-clobber https://storage.googleapis.com/conceptual_12m/cc12m.tsv') # In[5]: get_ipython().system('wget https://sto...
from featuretools.primitives import AggregationPrimitive from featuretools.variable_types import Numeric from tsfresh.feature_extraction.feature_calculators import range_count class RangeCount(AggregationPrimitive): """Count observed values within the interval [min, max). Args: min (float) : The incl...
"""Script for running Pokemon Simulation.""" from threading import Thread from queue import Queue from time import time from agent.basic_pokemon_agent import PokemonAgent from agent.basic_planning_pokemon_agent import BasicPlanningPokemonAgent from battle_engine.pokemon_engine import PokemonEngine from file_manager.l...
from superhero_api import SuperHeroAPI, API_KEY class SuperHeroApp(): def __init__(self): self._s = SuperHeroAPI(API=API_KEY) self._status = True self._prelude_text = '''Ну привет странник. че забрел? либо иди отседа либо используй команды. help - список команд compa...
def describe_city(city,country): print(city,"is in",country) describe_city("Karachi","Pakistan") describe_city("Bonn","Germany") describe_city("Moscow","Russia")
def extract_menu_day_elements(day, parent_element): return parent_element.find('div', {'id': 'menu-plan-tab' + str(day)}) def extract_menu_item(parent_element): return parent_element.findAll('div', {'class': 'menu-item'}) def extract_menu_title(parent_element): menu_title = parent_element.find('h2', {'c...
import FWCore.ParameterSet.Config as cms myan = cms.EDAnalyzer('HcalTimingAnalyzer', eventDataPset = cms.untracked.PSet( simHitLabel = cms.untracked.InputTag(""), # change it if you want 'em hbheDigiLabel = cms.untracked.InputTag(""), # change it if you want 'em hbheRechitLabel = cms.untrac...
import pandas as pd import numpy as np from quant.stock.stock import Stock from quant.stock.date import Date import statsmodels.api as sm def PriceDelay(beg_date, end_date): """ 因子说明:价格延迟 时间序列上,用股票收益对当期市场收益做回归,记为回归1,回归长度为LongTerm 时间序列上,用股票收益对当期市场收益和过去N天市场收益做回归,记为回归2,回归长度为LongTerm 计算回归1的R2除以回归2的R2...
# univariate cnn example from numpy import array from keras.models import Sequential from keras.layers import Dense from keras.layers import Flatten from keras.layers.convolutional import Conv1D from keras.layers.convolutional import MaxPooling1D import pandas as pd import numpy as np import sklearn.metrics as skm impo...
# class in the poppins thingamajig from poplib import * class poppinsMary: def __init__(self): popIp='aaa.bbb.ccc.ddd' popAddr='email@address.com' popPass='EmailPassword' class poppins: def __init__(self): x=poppinsMary() self.popSrvr = POP3(x.popIp) # ip works better than url ...
from django.db import models class Company(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) ticker_symbol = models.CharField(max_length=6, unique=True) name = models.CharField(max_length=150) url = models.CharField(max_length=150) business = models.CharField(max_length=1...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def __init__(self): self.head = None self.tail = None def addNode(self, node): self.tail.next = node self.ta...
from flask import render_template, flash, redirect, request, url_for, send_from_directory,session from app import app from .forms import Setting from .forms import Add from werkzeug import secure_filename import os import time import random import MySQLdb import hashlib import models_admin from random import...
#!/usr/bin/python # -*- coding: utf-8 -*- #-------------------------------------- # Clase que describe el comportamiento del sistema de ILUMINACION de HydroPonic System # # Authors : [Matias Deambrosi, Juan Jose Conejero Serna] # Date : 21/10/2015 # # Contact: [md9@alu.ua.es, jjcs2@alu.ua.es] # #----------------...
from inspect import isfunction, isclass class PollenException(Exception): pass class OverwriteServiceError(PollenException): pass class UndefinedServiceNameError(PollenException): pass class ConfigurableServiceError(PollenException): pass class Pollen(object): def __init__(self): s...
""" Trace the execution of the code in Example 5.2 on paper showing the contents of the run-time stack just before the function call returns. """ # val # Main activation record # y # x
import pymysql import matplotlib.pyplot as plt plt.rcParams['font.family'] = ['sans-serif'] plt.rcParams['font.sans-serif'] = ['SimHei'] conn = pymysql.connect( host = "localhost", user = "root", port = 3306, db = "bilibili" ) cur = conn.cursor() cur.execute("SELECT s...
import matplotlib.pyplot as plt import numpy as np def filter_stat_data(x, y): new_x = [] new_y = [] for k in range(0, (len(x) - 1)): if x[k] > 12000: new_x.append(x[k]) new_y.append(y[k]) return new_x, new_y def fit_data(x, y): return np.polyfit(y, x, 1) def fi...
import argparse from common_crawl.finder.product_finder import ProductFinder from common_crawl.save.json_save_products import JsonSaveProducts from product.extractors import tesco_extractor from common_crawl.utils import search_domain import time # Scans common crawl information for products and saves them. def main...
import numpy as np import pandas as pd # documentation # output: clean data set, remove missing values and convert categorical values to binary, extract sensitive features # for each data set 'name.csv' we create a function clean_name # clean name takes parameter num_sens, which is the number of sensitive attributes t...
from django.conf.urls import patterns, include, url from yasana import urls as yasana_urls from account import urls as account_urls from api import urls as api_urls from partials import urls as partial_urls urlpatterns = patterns('', url(r'^', include(yasana_urls, namespace='yasana')), ...
import unittest def fun(x): return "test" class MyTest(unittest.TestCase): def test(self): self.assertEqual(fun(1), "test")
import torch import dgl from model import GraphTransformerNet import torch.nn.functional as F import torch.nn as nn from data import GraphDataset, collate from torch.utils.data import DataLoader import datetime # device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') device = torch.device('cpu') def...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest import json class PasswordWithJsonTestCase(unittest.TestCase): data_file_path = './user_data.json' def setUp(self): print('set up') self.test_data = json.loads(open(self.data_file_path).read()) @unittest.skip('test_weak_pass...
from main.models import Contact from django.shortcuts import render,redirect from datetime import datetime from main.models import Contact,Product,Order from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth import authenticate,login from django.contrib.auth.forms impor...
__all__ = ["UploadStrategy", "FileUploadStrategy", "UserInputUploadStrategy"] from rest_api.views.strategies.upload import UploadStrategy, FileUploadStrategy, UserInputUploadStrategy
#!/usr/bin/env python # encoding:UTF-8 import unittest from app.student.homework.object_page.homework_page import Homework from app.student.login.object_page.home_page import HomePage from app.student.login.object_page.login_page import LoginPage from app.student.login.test_data.login_failed_toast import VALID_LOGIN_T...
import numpy as np import matplotlib.pyplot as plt from copy import copy # for armchair junctiong # declare parameters # dimension default: energy is eV, length is 10^-10 me = 0.51099895000*(10**6) / (299792458**2) # 전자의 질량 MeV/c**2 hbar = 6.582119569 * 10**(-16) K0 = 2.35*10**(-9) vy = 5.6*10**5 m = 1.42*me mx = 0....
# A simple lambda function that check if a port on a host is open and pushes a cloudwatch metric import json import boto3 import socket def lambda_handler(event, context): # Check if port is open or not (try to connect to a port on a server - timeout set to 1 sec) ip = event['ip'] port = event['port'] ...
""" kalman_filter_dependent_fusion Uses the test and using taking the dependence into account. Follows Bar-Shaloms formulas for doing so. """ import numpy as np from stonesoup.models.measurement.linear import LinearGaussian from stonesoup.models.transition.linear import CombinedLinearGaussianTransitionModel, Constan...
"""Construct a profile with two hosts for testing owamp Instructions: Wait for the profile to start. . . """ # Boiler plate import geni.portal as portal import geni.rspec.pg as rspec request = portal.context.makeRequestRSpec() # Get nodes host = request.RawPC("host") target = request.RawPC("target") # Force hardw...
# a=[1,2,8,7,6,3,4,5] # i=0 # b=[] # while i<len(a): # if i%2==0: # pass # else: # b.append(a[i]) # i=i+1 # i=0 # while i <len(b): # j=i # var=0 # while j<len(b): # if b[j]>b[i]: # var=b[i] # b[j]=b[i] # b[j]=var # i=i+1 # x=0 #...
# KEEP THIS SECRET CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = ''
from bs4 import BeautifulSoup import urllib.request import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.dev") from django.db import models from person.models import Person # class Person: # def __init__(self, fullname, firstname, lastname, location): # self.fullname = fullname # self.fi...
""" A MNIST classifier using batch normalization. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys import tempfile import tensorflow as tf import tensorflow.contrib.layers as layers from tensorflow.examples.tutorials.mnist impor...
def main(): num = int(input("Digite o número: ")) result = verifica_numero_primo(num) print(result) def verifica_numero_primo(num): if num>=0 and num<=100: if num % num == 0 and num % 1 == 0 and not num % 2 == 0: return "é primo" elif num == 2: re...
from numbers import Number import math class RegularConvexPolygon: '''A Regular Strictly Convex Polygon''' def __init__(self, edges:int, radius:Number)->None: '''Polygon initializer with attributes edges and radius''' self.edges = edges self.radius = radius def __validate_edges(sel...
import cv2 WINDOW_ID = '0x2800018' # さっき確認したID video = cv2.VideoCapture(f'ximagesrc xid={WINDOW_ID} ! videoconvert ! appsink') while cv2.waitKey(1) != 27: ok, img = video.read() if not ok: print("Error brank") break cv2.imshow('test', img)
import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle from sklearn.ensemble import RandomForestRegressor from sklearn.neural_network import MLPRegressor from sklearn.pipeline import Pipeline from sklearn.preprocessing import LabelBinarizer, MinMaxScaler, Imputer from basic.bupt_2017_11_...
def display_menu(): print("-" * 30) print(" 图书馆管理系统 v8.8 ") print("1.登录/注册") print("2.新书上架") print("3.热书推荐") print("4.退出系统") print("-" * 30) def menu1(): print("-" * 30) print(" 管理员入口 ") print("1、读者管理") print("2、图书管理") print("3、退出系统") print("-" * 30...
from sqlalchemy import Column, Integer, String, Date, ForeignKey, Float, Boolean, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Product(Base): __tablename__ = 'products' Product_id = Column(Integer, primary_key=True) name = Column(String) price = Column(Float) P...
# Copyright 2014 Baidu, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file # except in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwa...
import tensorflow as tf class GRUCellWithBahdanauAttention(tf.contrib.rnn.GRUCell): def call(self, inputs, state): return inputs, state ### YOUR CODE HERE ### Make sure all variable definitions are within the scope! raise NotImplementedError("Need to implement the GRU cell \ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from Public.BasePage import BasePage from Public.maxim_monkey import Maxim from Public.Decorator import * from uiautomator2 import UiObjectNotFoundError class login_page(BasePage): @teststep def wait_page(self): try: if self.d(text='ECOPRO...
''' Hello my name is Ethan Dewri. This program will scramble text into a two rail cypher and give enctpted and decrypted messages. Scorces : https://www.youtube.com/watch?v=qOlJwi9mu2Q https://www.youtube.com/watch?v=uaCumJi4Iuw ''' choice = input("You shall have the ability to encrypt or decrypt anything th...
from ham.util import radio_types from ham.util.data_column import DataColumn class DmrId: @classmethod def create_empty(cls): cols = dict() cols['number'] = '' cols['radio_id'] = '' cols['name'] = '' return DmrId(cols) def __init__(self, cols): self.number = DataColumn(fmt_name='number', fmt_val=cols[...
class Solution(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ not_working = 0 N = len(nums) for idx in range(N-2): if nums[idx] > nums[idx+1]: if nums[idx] <= nums[idx+2]: ...
# Generated by Django 3.2.4 on 2021-07-03 17:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nduggaapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='category', name='name', ...
#!/usr/bin/env python2.5 ####################################################################### # # Copyright (c) Stoke, Inc. # All Rights Reserved. # # This code is confidential and proprietary to Stoke, Inc. and may only # be used under a license from Stoke. # ########################################################...
import numpy as np import matplotlib.pyplot as plt positions = np.loadtxt("test-positions.txt") plt.plot(positions[:, 0], positions[:, 1]) plt.show()
import boto3 from decimal import Decimal import numpy as np from boto3.dynamodb.conditions import Key, Attr def get_table_metadata(table): """ Get some metadata about chosen table. """ return { 'num_items': table.item_count, 'primary_key_name': table.key_schema[0], 'status': t...
# -*- coding: utf-8 -*- """ Created on Wed Dec 7 14:15:38 2016 @author: 3201955 """ import random import numpy as np import math import matplotlib.pyplot as plt N = 1000 #random points in triangle ABC def monteCarlo_triangle(A,B,C,N): r1 = np.random.uniform(0,1,N) r2 = np.random.uniform(0,1,N) x=(1-np...
import os import platform import subprocess import re import psutil from time import sleep from flask import render_template, abort, request, send_file, flash, redirect, url_for from arm.ui import app, db from arm.models.models import Job, Config from arm.config.config import cfg from arm.ui.utils import convert_log, ...
""" Write a program that walks through a folder tree and searches for files with a certain file extension. Copy these files from whatever location they are in to a new folder. """ import shutil, os def filesCopy(folderLocation, extension, destination): folderLocation = os.path.abspath(folderLocation) for fold...
from django.db import models class Usuario(models.Model): nombre= models.CharField(max_length=20) correo= models.CharField(max_length=30) def __str__(self): return"%s - %s"%( self.nombre, self.correo) # Create your models here.
import os import h5py import numpy as np import argparse import json from tensorflow.keras.preprocessing import image from tensorflow.keras.models import Model, load_model from tensorflow.keras.applications.resnet_v2 import preprocess_input label_list = ['Abyssinian','Bengal','Birman','Bombay','British_Shorthair','Eg...
#!usr/bin/python #coding:utf-8 class panda(): "趴趴熊" pandacount=0 foodcount = 0 def __init__(self,name,bamboo=0): self.name = name self.bamboo = bamboo panda.pandacount += 1 panda.foodcount = panda.foodcount + bamboo def climd(self): print "%s 趴趴……" % self.name def food(self): print "吃了 %d 个……" % self...
# # Copyright 2018 Analytics Zoo Authors. # # 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 tritium.apps.subscriptions.views import SubscriptionViewSet, TransactionViewSet from tritium.apps.users.views import UserViewSet, APICreditViewSet, APIKeyViewSet from rest_framework.routers import DefaultRouter from tritium.apps.networks.views import NetworkViewSet router = DefaultRouter() router.register(r'subsc...
# Created by Gustavo A. Diaz Galeas # # A sample program for an assignment for the students enrolled in the AP # Computer Science course at Colonial High School in Orlando, Florida. # # Purpose: To implement a program that prints out a customers receipt upon # order placement. A worker inputs the necessary data, ...
def isEven(n): if n % 2 == 0: return True else: return False def isDivisibleBy3(n): if n % 3 == 0: return True else: return False for i in range(1,20+1): if isDivisibleBy3(i) and isEven(i): print(i,'<=') else: if isEven(i) and isDivisibleBy3(i) ...
# numpy has an insanely powerful way to create 'dictionaries' from an array (a): lut, ndx = np.unique(a, return_inverse=True) # Now you have a list of unique values in (lut) and a list of indices to them in (ndx) ...fast! # Depending on number of distinct values, index array can be compressed to file by typecasting: ...
import pandas as pd from matplotlib import pyplot as plt import seaborn as sns df = pd.read_csv(r"data/abalone.csv") group = df.groupby('Sex') keys = ['M', 'F', 'I'] ''' for all data, "rings" is dependent, scatter ''' fig1 = plt.figure(figsize=(12, 16)) for i in range(1, 8): ax = fig1.add_subplot(3, ...
from django.http import HttpResponse def ola(request): return HttpResponse("<h1 style='color:Red'>Projeto 1</h1></br><h3>Coisas para colocar.</h3></br><h3>Mais coisas para colocar.</h3>")
# To rearrange a sorted array in the max min form. # for e.g. given_array = [1,2,3,4,5,6,7,8,9] # answer_array = [9,1,8,2,7,3,6,4,5] def Convert_to_max_min(arr, n): temp_arr = [] # to denote the begining of the array start = 0 # to denote the end of the array end = n-1 max = True while s...
dirName = input("| Enter Directory Name : ") print('|\n|\033[92m Directory Created\033[0m') fileName = [] responseCode = 1 while(responseCode < 5 and responseCode > 0): print('|\n| Operations\n|\n| 1.Create File\n| 2.Delete File\n| 3.Search in Directory\n| 4.View All Files\n| 5.Exit\n|') responseCode = int(inpu...
from django_tables2 import Table, Column from .models import Fights from django.utils.safestring import mark_safe from units.models import Unit from types import MethodType from math import log def col_style(): return {'td': {"style": "text-align:center;"}, 'th': {"style": "text-align:center;"}} de...
import moodleGradeHandler as mgh if __name__ == "__main__": username = input('Please Enter Username\n') password = input('Please Enter Password\n') course_url = input('Please Enter Exam URL\n' 'For Example: https://moodle2.bgu.ac.il/moodle/mod/quiz/view.php?id=1853627\n') ...
import vodka import vodka.plugins # vodka.plugin.register('my_plugin') # class MyPlugin(vodka.plugins.PluginBase): # pass
class Solution: def generate(self, numRows: int) -> List[List[int]]: res=[[] for i in range(numRows)] for i in range(numRows): temp=[1]*(i+1) for j in range(1,i): temp[j]=res[i-1][j-1]+res[i-1][j] res[i]=temp return res
""" Dictionary * try except playground 📚 Resources: https://www.youtube.com/watch?v=rfscVS0vtbw&t=1s&ab_channel=freeCodeCamp.org """ try: number = int(input('Enter a number: ')) print(number) except ZeroDivisionError: print('Divided by zero') except ValueError: print('Invalid input')
import requests url = 'https://v7.wuso.tv/wp-content/uploads/2018/03/asdysb0320007.mp4' headers = {'Referer': 'https://wuso.me/', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'} req = requests.get(url,...
from .exceptions import * import random # Complete with your own, just for fun :) LIST_OF_WORDS = [] def _get_random_word(list_of_words): # Exception check if not list_of_words: raise InvalidListOfWordsException() # Using a random integer as an indexer to select a word rand_indexer = random....
# -*- coding:utf-8 -*- import web from jinja2 import Template import os import sys reload(sys) #使用utf8编码 sys.setdefaultencoding('utf-8') # 导入MySQL驱动: import pymysql import json import urllib2 import re urls = ( '/search/(.*)', 'search', '/mh/([\d,/]*)','result', '/test','index', '/mh/(\d*)/(.*)','comic' ) class...
#%% import wrf as w import xarray as xr from netCDF4 import Dataset import pandas as pd import matplotlib.pyplot as plt import cartopy.crs as ccrs import cmaps import os import sys sys.path.append('/home/zzhzhao/code/python/wrf-test-10') from zMap import set_grid, add_NamCo import warnings warnings.filterwarnings("i...
class Node: def __init__(self,data): self.data = data self.next = None class Linklist: def __init__(self): self.head = None def insert(self,data): newNode = Node(data) newNode.next = self.head self.head = newNode def print(self): temp = self.head while(temp): print(temp...
from .Config import Config from .Package import Package class Manager(): STATUS_PROCESSING = 'PROCESSING' STATUS_READY = 'READY' def __init__(self): self.status = self.STATUS_READY def process(self): self.status = self.STATUS_PROCESSING for source in Config().get('sources'): ...
import psycopg2 import sys sys.path.append('/home/proj/price_keeper') from price_keeper import TokenInfoDB import json db = TokenInfoDB() decimal_map = {t[0]: t[1] for t in db.get_all_decimal()} with open('utils/decimal/token_decimal.json', 'w') as f: f.write(json.dumps(decimal_map))
import datetime import pytz from smartweb_service.database import db from smartweb_service.database.user_api_relation import UserApiRelation def validate_api_key(api_key): user_api_rel = UserApiRelation.query.filter(UserApiRelation.api_key == api_key).first() if user_api_rel is None: return False return True def...
from Cell import Cell from Constants import Constants from Config import Config from CubeCoord import CubeCoord import random class Board: def __init__(self, seed): self.map = {} # coord -> Cell self.index = 0 if seed: random.seed(seed) self.generate() def generateCell(self,...
#python Wavelet.py import numpy as np from PyLets import MatPlotWavelets as mwl from PyLets import Others as ot from PyLets import SignalsAnalyses as sia from PyLets import Wavelets as wale t = np.linspace(0, 10,1000) dilat = np.linspace(0, 0.5,1000) WaveletSinal = wale.HermitianWavelet1(t,0.25,5) sinal = wale.SinalB...
#!/usr/local/bin/python #-*- coding: UTF-8 -*- #生成产品页面 ################################################## import string_data #变量保存 import Cmysql #数据库操作文件 import sfile #文件操作 import os import re import time import random def sj(): #产生随机字符 try: #seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU...
"""Copyright (c) 2018 Great Ormond Street Hospital for Children NHS Foundation Trust & Birmingham Women's and Children's NHS Foundation Trust 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 withou...
from selenium import webdriver from selenium.webdriver.common.by import By import time def run_forever_like_Forrest(): moment=time.strftime("%Y-%b-%d__%H_%M_%S",time.localtime()) f = open('output '+moment+'.csv', 'w') headers="LATER OI (CALL),CHANGE IN OI (CALL),LTP (CALL),NET CHANGE (CALL),STRIKE P...
import argparse import json import math import os import shutil import socket from copy import deepcopy from datetime import datetime from pprint import pformat from typing import Callable, Dict, Generator import numpy import psutil import tensorflow as tf import yaml from tensorflow.python.keras.callbacks import Lamb...