text
stringlengths
38
1.54M
import bisect a = [2,7] size = 33 for i in range(3,size): if i%2 == 0: a.append(a[-1]+7) else: a.append(a[-1]+3*a[-2]) b = a[:16] c = a[16:] allowedNumbersB = [] allowedNumbersC = [] def f(currentIndex, tillNowSum, type): if currentIndex >= size/2: if type == 0: allowed...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # TODO: could use some profiling to increase speed import solutions.utils as utils def parse_input(fpath): with open(fpath) as f: for line in f: yield int(line) def solver1(jumps, part2flag=False): steps = 0 position = 0 while Tru...
from mite.stats import Counter, Histogram, extractor, matcher_by_type _PAGE_LOAD_METRICS = [ ("dns_lookup_time", "seconds"), ("dom_interactive", "seconds"), ("js_onload_time", "seconds"), ("page_weight", "bytes"), ("render_time", "seconds"), ("tcp_time", "seconds"), ("tcp_time", "seconds"),...
from django.conf.urls import url,include from django.contrib.auth.views import login,logout from . import views urlpatterns=[ url(r'^signup/$',views.signup,name='signup'), url(r'^login/$',login,name='login'), url(r'^logout/$',login,name='logout'), url(r'^profile/$',views.profile,name='profile'), ]
""" hmm.py A program for estimating the hidden state sequence of DNA sequence data using Hidden Markov Models. Both Viterbi's Algorithm and the Forward Backward algorithm are implemented. Authors: Nathan Holeman Tyler Huntington April 16, 2018 """ import optparse from math import log, e from viterbi import ViterbiC...
#!/bin/python3 import math import os import random import re import sys # Complete the happyLadybugs function below. def isLadybugsAreHappy(str_list): for i in range(len(str_list)): if i == 0: prev = '' else: prev = str_list[i - 1] if i == len(str_list) - 1: ...
from client import Client import time import threading msgs = [] c1 = Client("Tudor") c2 = Client("Gigi") c3 = Client("ANdi") time.sleep(1) def update_messages(): while True: try: time.sleep(0.1) messages_to_show = c1.get_messages() msgs.extend(messages_to_show)...
#!/usr/bin/python # -*- coding: utf-8 -*- def create_roles_table(testdb): table_name = 'IF NOT EXISTS ROLES' column0 = 'ID INT NOT NULL PRIMARY KEY' column1 = 'ROLE CHAR(20) NOT NULL' columns = (column0, column1) testdb.create_table(table_name, columns) testdb.insert('ROLES', ('ID', 'ROLE'), (...
from sklearn.preprocessing import Normalizer, StandardScaler import csv import random def readData(): X = [] Y = [] with open('data/train.csv', 'r') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: print x if __name__ == '__main__': readData()
# Python RPA Developer Course # Reading and Writing Files, OS utilities, and Libraries # first lets define a valid file path mypath = r"C:\Users\david\Desktop\new_file.txt" f = open(mypath, "w") f.write("HELLO. THIS IS A TEST") f.close() import os # Get current working directory os.getcwd() # libraries can have su...
""" Declare all global variables """ import os flags = dict() # static folder flags['experiment_folder'] = os.path.join(os.path.join('Modules', 'experiment_he_dcis_segmentation')) ################################################################################### # training flags['gpu'] = '/gpu:0' flags['min_fractio...
import random from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from core.models import Conversa #from nltk.corpus import wordnet, stopwords from random import choice import sys class iaService: bot = None trainer = None conversaDefault = ['Oi', 'Olá', 'Tu...
#import copy class UndirectedGraph: def __init__(self, vertices): self.__numberVertices = vertices self.__dictEdges = {} for i in range(0,vertices): self.__dictEdges[i]=[] def addVertex(self, vertex): if vertex in self.__dictEdges: raise Exc...
import tkinter as tk from loader_sim import * try: import pyperclip except ImportError: print("Install pyperclip if you want to use the clipboard functionality") fileHandle = open("loader.c", "r") loaderc = fileHandle.read() fileHandle.close() # Line numbers in loader.c for each of the stages where the progra...
import logging import mock import pytest import json import datetime as dt from ga4ghtest.core.queue import create_submission from ga4ghtest.core.queue import get_submissions from ga4ghtest.core.queue import get_submission_bundle from ga4ghtest.core.queue import update_submission logging.basicConfig(level=logging.DE...
import time import os, sys import numpy as np #assign defaults dt = 1./500 num_readings = 4000 file_name = 'accel_data_default.csv' #open file (and remove if necessary) if os.path.exists(file_name): print('Output file exists, removing file.') os.remove(file_name) f = open(file_name,'a') time = np.arange(0, d...
from re import Match from typing import Type from xml.etree.ElementTree import Element import markdown from markdown import Markdown from markdown.extensions import Extension from markdown.inlinepatterns import Pattern from markdown.util import AtomicString class HashToSpanCounterPattern(Pattern): def handleMat...
from collections import UserDict import sqlite3 import datetime from dotenv import dotenv_values config = dotenv_values(".env") def create_connection(db_file): connection = None try: connection = sqlite3.connect(db_file) return connection except sqlite3.Error as e: print(e) def ...
# @file ReservationStation.py # @authors Stephen #private constants for readability ID = 0 DEST = 1 OPERATION = 2 TAG_I = 3 TAG_J = 4 VALUE_I = 5 VALUE_J = 6 EXECUTING = 7 class ReservationStation: """ This class implements a generic reservation station """ def __init__(self, size, name)...
import subprocess from subprocess import Popen, PIPE import os file_p = open("/Users/sarahgonsalves223/Desktop/DSA_Python/problems", "r") contents = file_p.read() lines = contents.split("\n") problems = [] for i,line in enumerate(lines): if i%2 == 0: problem = line.strip() problems.append(problem) ...
#Attempt to simulate the spiral/circular movement of particles in a fluid. #In this case I tried to model a hurricane/tornado from vpython import * import random import math import numpy # Set up scene tela = canvas(height = 650, width = 1340, background = vec(0,0,0.2), center = vector(0, 0, 0...
import tkinter as tk import time import webbrowser # 创建主窗口 window = tk.Tk() window.title('微AI战队') window.geometry('630x150') # 设置下载进度条 tk.Label(window, text='Training', ).place(x=50, y=60) canvas = tk.Canvas(window, width=465, height=22, bg="white") canvas.place(x=110, y=60) # 显示下载进度 def progress(): # 填充进度条 ...
class Solution: def minPathSum(self,grid): m = len(grid) n = len(grid[0]) pre = [0] * n t = 0 for i in range(n): pre[i] = t + grid[0][i] t += grid[0][i] for i in range(1,m): cur = [0] * n for j in range(n): cur[j] = pre[j] + grid[i][j] if j == 0 else min(pre[j],cur[j - 1]) + grid[i][j] ...
import requests import mock import pytest from pytest_mock import mocker from votesmart.api import VoteSmartAPI def test_sanity(): assert 1 + 1 == 2 def test_init_api_no_key(): with pytest.raises(ValueError): VoteSmartAPI() def test_api_set_payload(): vsmart = VoteSmartAPI(api_key="fake_key") ...
# Python Mentee - Level 3 - Exercises # https://bairesdev.atlassian.net/servicedesk/customer/article/2101576225 # 4 - Write a Python function using list comprehension that receives a list of words and # returns a list that contains: # _ The number of characters in each word if the word has 3 or more charac...
""" linalg.qr(a[, mode]) |- QR因子计算 |- QR方法是Francis于1961年发表的用于求解所有特征值的算法呢。 |- 该算法对对称矩阵和非对称矩阵都适用,都可以分解成正交矩阵Q和上三角矩阵R乘机的形式。 linalg.svd(a[, full_matrices, compute_uv]) |- 奇异值分解 这个函数不掌握 linalg.cholesky(a) |- 柯列斯基(Cholesky)分解 SVD分解收说明: SVD也是对矩阵进行分解,但是和特征分解不同,SVD并不要求要分解的矩阵为方阵。假设我们的矩阵A是一个m×n 的矩阵...
from input_script_functions import * from output_processing_functions import * from os import system from sys import exit from time import time from openpyxl import Workbook __author__ = 'Max' # all parameters are defined in depth in run_framework.py def run_aermod_framework(surface_observations_file, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 9 16:29:49 2020 @author: rdamseh """ import magic_vnet as vnet import numpy as np import torch def model_size(model): model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_p...
def fuel(mass): return int(int(mass) / 3) - 2 with open("inputs.txt") as f: data = f.readlines() sum = 0 for mass in data: sum += fuel(mass) print sum
from artiq.experiment import * class SAWGTest(EnvExperiment): """test_spline0 purpose: test: expectation: setup: """ def build(self): print(self.__doc__) self.setattr_device("core") self.setattr_device("sawg0") self.setattr_device("sawg1") self.setatt...
from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Idea(models.Model): idea = models.TextField() save_time = models.TextField() save_money = models.TextField() save_effort = models.TextField() def get_absolute_...
def calc(field, x, y): # print ( # field[x-1][y-1] , # field[x-1][y] , # field[x-1][y+1] , # field[x][y-1] , # field[x][y+1] , # field[x+1][y-1] , # field[x+1][y] , # field[x+1][y+1], # ) return ( field[x-1][y-1] + field[x-1][y] + field[x-1][y+1] + field[x][y-1...
from fqueue import Queue import multiprocessing import sys import time def sigint(): import signal, os def sig(n, f): os.kill(0, signal.SIGTERM) signal.signal(signal.SIGINT, sig) def randstr(l=10, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): from random import c...
import numpy as np def batchify(X, batch_size, y=None): l = len(X) for ndx in range(0, l, batch_size): if y is None: yield X[ndx:min(ndx + batch_size, l)] else: yield X[ndx:min(ndx + batch_size, l)], y[ndx:min(ndx + batch_size, l)] """ Below 3 methods are taken from the...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-12-09 20:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('devnoob', '0006_auto_20171209_2026'), ] operations = [ migrations.AlterFiel...
# encoding utf-8 import os # On importe le module os qui dispose de variables # et de fonctions utiles pour dialoguer avec votre # système d'exploitation # Programme testant si une année, saisie par l'utilisateur, est bissextile ou non annee = input("Saisissez une année : ") # On attend que l'u...
from django.db import models class Clinic(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20, blank=False, null=False) department = models.CharField(max_length=20, blank=False, null=False) address = models.CharField(max_length=20, blank=False, null=False) ...
#!/usr/bin/python import sys import subprocess import re import os import glob def print_usage(exit_code): print("%s <path> [<encoding>]" % sys.argv[0]) exit(exit_code) def read_file(filename, encoding): return open(filename).read().decode(encoding, 'ignore').encode('utf-8') def translate_file(smipath, encoding)...
from __main__ import * #-----------------------------------------------------------------------------# #Global variables: #-----------------------------------------------------------------------------# MAX_ITER = 1000 PRINT_AT_N_ITER = 1 SAVING_INTERVAL = 1 SAVE_FOLDER_DETAILED = "outputs_detailed/" SAVE_FOLDER_CONVER...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 17 13:35:14 2018 @author: Bryan """ # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.il...
# Programmer: Daniel Pozmanter # E-mail: drpython@bluebottle.com # Note: You must reply to the verification e-mail to get through. # # Copyright 2003-2007 Daniel Pozmanter # # Distributed under the terms of the GPL (GNU Public License) # # DrPython is free software; you can redistribute it and/or ...
import numpy as np a = np.linspace(1, 999, 999) b = [i for i in a if i % 3 == 0 or i % 5 == 0] np.sum(b)
# Generated by Django 3.2.5 on 2021-07-27 21:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('crops', '0001_initial'), ('sows', '0001_initial'), migr...
#!/usr/bin/env python # coding: utf-8 # # # This is a Python Project on an Amazon e-commerce Customer Reviews Data Set with Fashion Products # # DATA GATHERING AND CLEANSING # In[ ]: # Connect to dataset # In[112]: import os os.chdir(r"C:\Users\alina\Documents\dsa python prject\Ali\Data") os.getcwd() impor...
import random import numpy as np import matplotlib.pyplot as plt from vpython.graph import * from pylab import * """ Metropolis algorithm for a one-dimensional Ising chain. """ # initialize graph/plot scene = display(x=0,y=0,width=700,height=200, range=40,title="Spins") engraph = gdisplay(y=200,width=700,height=300,...
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # T...
# Operadore Lógicos # not and or # not -> Negação - inverte o retorno - True para False , False para True # and -> E - Retorna True se todas as condições forem verdadeiras # or -> ou - Retorna True se uma das condições for verdadeira num1 = 7 num2 = 5 num3 = 4 print (num1 > num2 and num2 > num3) print (num1...
from modules.attention import ResidualAttentionBlock from modules.involution import Involution2d import torch import torch.nn as nn import modules class GenericBackbone(nn.Module): def __init__( self, module_configs : list[dict] ): ''' args: module_configs: list[d...
# -*- coding: utf-8 -*- class Config: BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
""" 页面信息相关的视图函数 """ from rest_framework import generics from rest_framework.permissions import IsAuthenticated from rest_framework.filters import SearchFilter, OrderingFilter from django_filters.rest_framework import DjangoFilterBackend from docs.models.info import InfoCategory, Info, InfoValue from docs.serializers.i...
from __future__ import unicode_literals from flask import session from fossir.core import signals from fossir.core.logger import Logger from fossir.core.settings import SettingsProxy from fossir.util.i18n import _ from fossir.web.flask.util import url_for from fossir.web.menu import SideMenuItem logger = Logger.g...
def string(s1,s2): if len(s1)>len(s2): print(s1) elif len(s2)>len(s1): print(s2) else: print(s1) print(s2) s1=input() s2=input() string(s1,s2)
# -*- coding: utf-8 -*- """ @ time : 2018/6/2 @ author : Xieyz @ software: PyCharm """ from django.utils.deprecation import MiddlewareMixin class DisableCSRFCheck(MiddlewareMixin): def process_request(self, request): setattr(request, '_dont_enforce_csrf_checks', True)
class Person(): def __init__(self, personName, personAge): self.name = personName self.age = personAge def showPersonInfo(self): print(f"Name:{self.name}\nAge:{self.age}") class Student(): def __init__(self, studentId, doj): self.studentId = studentId ...
# coding: utf-8 from ellen.utils import temp_repo def test_list_branches(tmpdir, Jagare): path = tmpdir.strpath t_repo = temp_repo.create_temp_repo(path, is_bare=True) branches = Jagare.list_branches(path) assert branches == t_repo.branches def test_create_branch(tmpdir, Jagare): path = tmpdir...
def get_alert_box(msg,request): html = ''' <script> alert('{}'); document.location.href = '{}' </script> '''.format(msg,"").format(request.META.get('HTTP_REFERER')) return html
import time from threading import Thread from PyQt5 import QtWidgets from PyQt5.QtCore import Qt from Design_ui.Ui_files.progressbar import Ui_Dialog from Threaads.ProgressBarThread import ProgressBarThread from Threaads.QuestionThread import Start_Thread from Design_ui.Abstract.QuestionWindow import QuestionWindow ...
#python code for cracking XOR encryption #code from Cyber Security Essentials by James Graham count = len(data) for key in range(1,255): out = '' for x in range(0,count): out += chr(ord(data[x]) ^ int(key)) results = out.count('.com') + out.count('http') + out.count('pass') if results: ...
# -*- coding: utf-8 -*- from django.apps import AppConfig from common_utils.mail import send_template_mail from notes.signals import note_created class NewsConfig(AppConfig): name = 'news' verbose_name = 'Správy' def ready(self): News = self.get_model('News') note_created.connect(self.note_created, sender=Ne...
import json import os from django.core.management.base import BaseCommand from conference_scrapper.conference.models import Conference, ConferenceGraphEdge def splitter(f): for line in f: yield line.split("\t") class Command(BaseCommand): help = 'Parses files with raw data and create csv file with...
#!/bin/python3 """ __filename__ = "ec2_scheduler.py" __author__ = "Craig Poma" __credits__ = ["Craig Poma"] __license__ = "Apache License 2.0" __version__ = "1.0.0" __maintainer__ = "Craig Poma" __email__ = "cpoma@mitre.org" __status__ = "Baseline" See the requirements.txt file to install libraries for Python 3 this c...
import matplotlib.pyplot as plt class Color(object): def __init__(self, r, g, b): self.r = r self.g = g self.b = b def __repr__(self): plt.imshow([[(self.r / 255, self.g / 255, self.b / 255)]]) plt.show([[(self.r / 255, self.g / 255, self.b / 255)]]) #p...
import pandas as pd data = pd.read_csv("C:\\Users\\ytjh0\\Desktop\\lottery.csv") data2 = data.drop(["round","date"],axis=1) data3=data2.apply(pd.value_counts).fillna(0).astype(int) data3=data3.sum(axis=1) print(data3.sort_values(ascending=False))
""" Title: Long-only timeseries momentum hedged with broad market index. Description: This strategy uses past returns to rank securities and go long (short) the top (bottom) n-percentile Style tags: Momentum Asset class: Equities, Futures, ETFs, Currencies Dataset: US Equities or NSE...
from django.db import models from django.contrib.auth.models import User as DjangoUser class Game(models.Model): """ Game model keep track of game board state for a tic-tac-toe game. Fields: board a 9 character string, each of the 9 positin can hold: 'X' or 'O', this state that the space is played. ' ' me...
from django.urls import path, include from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from generic.views import index from generic.api_urls import router as data_router from . import routers """ URL definitions for the api. """ router = routers.DefaultRouter() router.exten...
from plastering.feature_selector import * import sys target_building = sys.argv[1] load_from_file = int(sys.argv[2]) method = "tree" fs = feature_selector(target_building, method, load_from_file) fs.run_auto()
import z3 import operator import functools as ft def hamming_a(bv): s = bv.size() return z3.Sum([(bv >> i) & 1 for i in range(s)]) # faster than a def hamming_b(bv): s = bv.size().bit_length() return z3.Sum([z3.ZeroExt(s, z3.Extract(i,i,bv)) for i in range(bv.size())]) # faster than b def hamming_c...
# -*- coding: utf-8 -*- # __author__:'Administrator' # @Time : 2018/4/16 11:31 import os import zipfile import gzip import tarfile # 解压zip包 def un_zip(file_name): zip_file = zipfile.ZipFile(file_name) new_file_dir = file_name.split(".zip")[0] if os.path.isdir(new_file_dir): pass ...
import numpy as np from wildcat.solver.qubo_solver import QuboSolver from wildcat.network.local_endpoint import LocalEndpoint from wildcat.annealer.simulated.simulated_annealer import SimulatedAnnealer from wildcat.annealer.simulated.single_spin_flip_strategy import SingleSpinFlipStrategy from wildcat.annealer.sim...
#!/usr/bin/python def gcf(a, b): while b%a > 0: a, b = min(a, b), max(a, b) b %= a return a def pythagorean_triple(a): results = [] for n in range(1, a): b_sq = 2*a*n + n**2 if b_sq**.5 == int(b_sq**.5): b = int(b_sq**.5) if True or gcf(a, b) ==...
# Credit to: https://machinelearningmastery.com/convert-time-series-supervised-learning-problem-python/ def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): """ Frame a time series as a supervised learning dataset. Arguments: data: Sequence of observations as a list or NumPy array. n_in: Number of lag ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2021/1/2 5:40 下午 # @Author : chengyan # @File : TYJPush.py # @Software: macos from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 import base64 import requests import json from logging import getLogger logger = getLogger('HelloWorld') ...
from Package import * from Speak import * def screenshot(): img = pyautogui.screenshot() img.save()
import datetime import glob import os import time import cv2 recognizer = cv2.face.LBPHFaceRecognizer_create() rec = int(input("Введите 1 для фото с веб-камеры, 2 для простых фотографиях: ")) names = None path = '' if rec == 1: recognizer.read(os.getcwd() + '\\face_recognition\\face_recognition_web_camera.yml') ...
class Solution: def myAtoi(self, s: str) -> int: '''字符串转换整数 (atoi)''' if len(s)==0:#特例 return 0 ret=0 i=0 while s[i]==' ':#去' ' i+=1 if i==len(s):#特例 return 0 pos_neg=-1 if s[i]=='-' else 1#正负号 if s[i] in ['-...
from prepare_data import get_test_train from model import XGBootstrapModel from article import Article, DailyArticles import numpy as np from sklearn.metrics import mean_squared_error from random import shuffle # Training 909/1728 def generate_options(): all_options = [] for lr in [0.05, 0.1, 0.3]: ...
# coding: utf-8 # In[92]: import numpy as np import matplotlib.pyplot as plt # # Parameters # In[93]: N = 10 # training samples poly_order = 11 # polynomial order M = 100 # testing samples lagrangian = 0.1 # lambda, regularization parameter # # Generating training samples # I...
import discord import os from discord.ext import commands client = commands.Bot(command_prefix='$') @client.command() async def play(ctx, url : str): voiceChannel = discord.utils.get(ctx.guild.voice_channels, name='General') voice = discord.utils.get(client.voice_client, guild=ctx.guild) await voiceChannel.co...
import discord import asyncio import os import time import random import openpyxl from json import loads from discord.utils import get from discord import Message client = discord.Client() access_token = os.environ["BOT_TOKEN"] token = "access_token" @client.event async def on_ready(): print("====...
from setuptools import setup setup( name = "cmdrunner", entry_points = {'zc.buildout': ['default = cmdrunner:Cmd', 'py = cmdrunner:Python'], 'zc.buildout.uninstall': ['default = cmdrunner:uninstallCmd']} )
import sys import os import pandas as pd indir = sys.argv[1] #"RA_EUR_rs_genes" infiles = os.listdir(indir) #chr11 45406048 rs7127704 T C -0.043478260869564835 for ff in infiles: infile_ = os.path.join(indir, ff) df = pd.read_table(infile_, header=None, dtype=str) #df = pd.read_table(infile_,...
# @author: jcpaniaguas from Trainer import Trainer from Tester import Tester from SheetLocator import SheetLocator import os def find_sheets(photo_directory,number_of_training_photos,groundtruth,model_name,percentage=False): """Function that searches the corners of the testing folios with a given training database...
import os import sys import math import sha256 import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) def _int_to_str(a: int) -> str: return bin(a)[2:] def _str_to_int(a: str) -> int: return int(a, 2) def powers_to_f(powers):...
import sys import csv import pickle freq_threshold=float(sys.argv[1]) test_volume=int(sys.argv[2]) entity_dict={} f=open("/home/ubuntu/results/collectiveDict.pickle","rb") entity_dict=pickle.load(f) f.close() total_hit_rate=0.0 total_error_rate=0.0 miss_count=0 invalid_count=0 for i in range(2000,2000+test_volume):...
# Generated by Django 2.1.7 on 2019-03-20 22:44 from django.db import migrations class Migration(migrations.Migration): dependencies = [("core", "0013_auto_20190320_2159")] operations = [ migrations.AlterModelOptions( name="examsheetevaluation", options={"ordering": ("-created",)} ...
import argparse def mock(args): output = '{0} {1}'.format(args.name, args) print(output) def greet(args): output = '{0}, {1}!'.format(args.greeting, args.name) if args.caps: output = output.upper() print(output) parser = argparse.ArgumentParser() parser.add_argument('--version', action='v...
#!/usr/bin/env python3 import datetime # import logging WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] timetable = { "valid_from": "2018-08-01", "valid_to": "2019-06-19", 'label': 'Klasse 4c', "lessons": { "Mon": ["D", "D", "Sp", "Eng", "Eng", "SK"], # lessons on Monday ...
from GUI.GUITable import Table import pygame import time import constants as const from GUI.GUI_Submit_Button import submit_button from GUI.GUI_Header import header_box class main_GUI: ############################################################################### #This is where all of the Gui classes will be utilized...
# coding=utf-8 # date: 2018-8-21,12:03:24 # name: smz import numpy as np """ 矩阵操作中三个点是表示取该轴所有元素,同: """ def demo(): matrix_a = np.array([[1, 2, 3], [4, 5, 6]]) print 'matrix_a[:]:\n', matrix_a[:] print 'matrix_a[...]:\n', matrix_a[...] print 'matrix_a[0][...]:\n', matrix_a[0][...] matrix_b = np....
from typing import Optional, Set from django.core.validators import RegexValidator from django.db import models from django.db.models.query import QuerySet class Author(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self) -> str: return self.name class Tag(models.Model): name...
#!/usr/bin/env python # -*- coding: utf-8 -*- from multiprocessing import Process import os def info(title): print title print 'module name:', __name__ print 'prarent process:', os.getppid() print 'process id:', os.getpid() def f(name): print 'hello', name if __name__=='__main__': info('main line') p=Process...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns #from scipy import stats #from operator import itemgetter from functools import reduce from sklearn.linear_model import LinearRegression class combine_models: """ This class is used to combine different cluster result...
from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.layers import BatchNormalization from sklearn.model_selection import train_test_split from sklearn import preprocessing import numpy as np import matplotlib....
from transformers import BertTokenizer from torch.utils.data import TensorDataset import torch from tqdm.notebook import tqdm encoded_data_train = tokenizer.batch_encode_plus( df[df.data_type=='train'].text.values, add_special_tokens=True, return_attention_mask=True, pad_to_max_length=True, max_l...
import sys, csv try: header = sys.argv[1] fasta = sys.argv[2] except: sys.stderr.write('script.py header/psl fasta\n') sys.exit(1) class FastAreader: def __init__(self, fname=''): self.fname = open(fname, 'r') if not fname: self.fname = sys.stdin de...
from PyObjCTools.TestSupport import TestCase import HealthKit class TestHKCategorySample(TestCase): def test_constants(self): self.assertIsInstance(HealthKit.HKPredicateKeyPathCategoryValue, str)
# # 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, software # distr...
__author__ = 'siavash' # QSTK Imports import QSTK.qstkutil.qsdateutil as dateUtil import QSTK.qstkutil.DataAccess as dataAccess # Third Party Imports import datetime as dateTime import pandas as pandas import numpy as np import copy import QSTK.qstkstudy.EventProfiler as ep print "Pandas Version", pandas.__version__...
#! /usr/bin/env python3 # coding: utf-8 from covid19 import controller """ Run the app with uwsgi and nginx """ app = controller.app if __name__ == "__main__": app.run(host='0.0.0.0', debug=False, port=80)