text
stringlengths
8
6.05M
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # 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 ap...
import ast import datetime # returns a list with [who_is_playing ('R'/'C'), start_time, child selection, end_time, game result, number of moves, total time of game, who_is_playing, ...] def analyze_tangram_game(filename, pathname='./processed_data/txt/'): who_is_playing = 'R' # can be 'R' or 'C' child_play_...
import torch import numpy as np import time import math from random import randint #Define constants. TRAIN_DATA_SIZE = 60000 TEST_DATA_SIZE = 10000 DATA_SIZE = 28*28 BATCH_SIZE = 200 GENS_PER_DIGIT = 10 MIN_EPOCHS = 50 ABSOLUTE_EPOCHS = 150 LABEL_SMOOTHING = 0.9 #Read the MNIST dataset. def read_mnist(): ...
""" Script maintain all machines Usage: sysadmin.py [options] <machines>... sysadmin.py [options] Arguments: machines specifies individual machines to run commands on Options: --update update all specified machines. --upgrade upgrade all specified machines --reboot reboot all spe...
from zeroconf import ServiceBrowser, Zeroconf from pprint import pprint class Listener: def __init__(self, callback): self.callback = callback def remove_service(self, zeroconf, type, name): pass def add_service(self, zeroconf, type, name): info = zeroconf.get_service_info(type, n...
#!/usr/bin/env python #from src.mp_metapath import * # check if python module 'src.mp_bioclite_wrapper' is available try: from src.mp_bioclite_wrapper import bioconductor bioc = bioconductor() except: print "could not import python module 'src.mp_bioclite_wrapper'" quit() list = ['TFAP2A','Arnt','Arn...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp: print(temp.data) temp = temp.next List = Lin...
import time from timeit import default_timer as timer from datetime import timedelta def bubble_sort(elements): elements_length = len(elements) # Loop through all elements - essentially the passes for item in range(elements_length): # Loop the list from 0 to item-i-1 fo...
from collections import Counter from operator import le, lt, ge, gt, eq, ne def string_evaluation(s, conditions): cnt = Counter(s) ops = {'<=': le, '<': lt, '>=': ge, '>': gt, '==': eq, '!=': ne} result = [] for condition in conditions: left = condition[0] right = condition[-1] ...
import random import dice dice_two = random.randint(1,6 ) total = dice.dice_one + dice_two print('Your total of two dices is: ' + str(total))
###################################################################### # HELPERS / UTILS # ###################################################################### from constants import valid_install_exit_codes, valid_uninstall_exit_codes from subprocess import Popen, ...
import importlib # import csp_bitstring as csp_module csp_module = importlib.import_module('csp_bitstring') def recursive_backtracking(csp, assignment): if csp_module.is_complete(csp, assignment): return assignment var = select_unassigned_variable(csp, assignment) for value in csp_module.order_d...
import re pattern = r"(@|#)([A-Za-z]{3,})\1\1([A-Za-z]{3,})\1" data = input() mirror_words = [] match = re.findall(pattern, data) for m in match: first_word = m[1] # при findall индексите са като при листовете, т.е. с едно назад от реалните second_word = m[2] if first_word == second_word[::-1]: ...
print("Hello Poland!")
import unittest import numpy as np from core.available_turn_coordinates_finder import AvailableTurnCoordinatesFinder class AvailableTurnsComputerTest(unittest.TestCase): def test_for_empty_field_returns_array_of_field_size(self): field = np.matrix('0 0 0; 0 0 0; 0 0 0') found_turns = self.find_tu...
import json from os.path import dirname, realpath, join from flask import Blueprint, request, render_template, jsonify import shared_variables as var routes_module = Blueprint('routes_module', __name__) parent_dir_path = dirname(dirname(realpath(__file__))) user_file = join(parent_dir_path, "data", "topUsers.json") tu...
from __future__ import division #defines function def get_at_content(dna): length = len(dna) #.upper changes lowercase to capitals so function can count them a_count = dna.upper().count('A') t_count = dna.upper().count('T') at_content = (a_count + t_count) / length #round to 2 decimal places return ro...
import sys, os sys.path.append(os.pardir) import numpy as np from dataset.mnist import load_mnist from common.multi_layer_net_extend import MultiLayerNetExtend (a_train, b_train), (a_test, b_test) = load_mnist(normalize=True, one_hot_label=True) network = MultiLayerNetExtend(input_size=784, hidden_size_list=[100, 10...
class Animal: def eat(self): print("吃") class Dog(Animal): def drak(self): print("叫") class Xiaotq(Dog): def fly(self): print("飞") xiaotq = Xiaotq() xiaotq.fly() xiaotq.drak() xiaotq.eat()
import TextAnalysis def openfile(filename): file = open(filename) file = file.read() words = file.split() limit = len(words) return file text=openfile("scam2.txt") #EMAIL ANALYSIS algorithm in TextAnalysis def emailanalysis(text): if (TextAnalysis.getemail(text))is not None: mail...
lst = [1,2,3] lst_ = [1,2,3] _lst = lst print(id(lst)) print(id(lst_)) print(_lst is lst)
__author__ = 'Caro Strickland' import sys import random print("\nWelcome to Python Hangman! \n") #Creation of the 'correct_guess' and 'incorrect_guess' lists correct_guess = [] incorrect_guess = [] #Adding words to the list of guessable words word_list = [] f = open('words.txt') for word in f.read().split(): wor...
# h is the separation distance # r is the range or distance parameter (r>0) which measures how quickly the correlations decay with distance import numpy def Spherical(h, r): n = numpy.size(h) corelation = numpy.zeros(n,dtype=numpy.double) for i in range(n): if h[i] == 0.0: corelation[i] = 1.0 elif h[i] >=...
class Field: def __init__(self, name): self.name = name self.players = [] @property def height(self): return len(self.players) @property def top_player(self): if len(self.players) == 0: return None return self.players[-1] def place(self, p...
from http.cookiejar import LWPCookieJar import matplotlib.pyplot as plt import requests # 保存Cookie session = requests.Session() # 创建cookie实例 session.cookies = LWPCookieJar('cookie') # 验证码 captcha = 'http://www.tipdm.org/captcha.svl' # 验证码保存路径 path = 'captcha/' rq = session.get(captcha) with open(path + 'captcha.jpg',...
import uuid from django.db import models class Currency(models.Model): """Currency model""" name = models.CharField(max_length=120, null=False, blank=False, unique=True) code = models.CharField(max_length=3, null=False, blank=False, unique=True) symbol = models.CharField(m...
#!/usr/bin/python # -*- coding: UTF-8 -*- """" версия 1.0.1 классы для работы со входными данными. для тренировки модели - набор маршрутав """ import logging import numpy as np import pandas as pd from torch.utils import data from utils.data_structures import GeoImage log = logging.getLogger(__name__) class Query...
import string from typing import Type import pytest from spectree import SecurityScheme from spectree._pydantic import ValidationError from spectree.config import Configuration, EmailFieldType from .common import SECURITY_SCHEMAS, WRONG_SECURITY_SCHEMAS_DATA def test_config_license(): config = Configuration(li...
products = {} count_products = 0 while True: command = input() if command == "statistics": break product_name, quantity = command.split(": ") if product_name in products.keys(): products[product_name] += int(quantity) else: count_products += 1 products[product_name] ...
import urllib def read_txt(): quests = open("C:\Users\Administrator\Desktop\movie_quotes\movie_quotes.txt") content = quests.read() print content quests.close() check(content) def check(check_text): connection = urllib.urlopen("http://www.wdylike.appspot.com/?q="+check_text) value = connection...
# Copyright 2021 DAI Foundation # # 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,...
# Sources: https://www.techbeamers.com/create-python-irc-bot/ import socket import time errors = { "ERR_NICKNAMEINUSE": "433" } # Define the IRC class class IRC: irc = socket.socket() # Define the socket def _init_(self): self.irc = socket.socket(socket.AF_INET, socket.SOCK_...
print('Melting and Boiling Points of Alkanes\n{:<10}{:<25}{:<25}'.format('Name',\ 'Melting Point(deg C)', "Boiling Poing(deg C)")) print('{:<9} {:<23d} {:}\n\ {:<9} {:<23d} {:}\n\ {:<9} {:<23d} {:}\n\ {:<9} {:<23.1f} {:}\n'.format("Methane",-162,-183, "Ethane",-89,-172,"Propane",-4220,-188,"Butane",-0.5,-135))
import dash.testing.wait as wait from dash import Dash, html from dash_bootstrap_components import ( Popover, PopoverBody, PopoverHeader, themes, ) from selenium.webdriver.common.action_chains import ActionChains def test_dbpo001_popover_click(dash_duo): app = Dash(external_stylesheets=[themes.BOO...
#Importing the libaries import face_recognition import cv2 import os from google. colab. patches import cv2_imshow #Image preprocessing def img_resize(path): img = cv2. imread(path) (h, w) = img. shape[:2] width = 500 ratio = width / float(w) height = int(h * ratio) #resizing the image with custom ...
import requests from bs4 import BeautifulSoup def weather(html): return html.find("div", {"class" : "link__condition day-anchor i-bem"}).text def temp(html): return html.find("span", {"class" : "temp__value"}).text url = "https://yandex.ru/pogoda/moscow?from=serp_title" response = requests.get(url) html =...
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if len(s) == 1: return 1 hash = {} n = len(s) result = 0 for i in range(n-1): if s[i] not in hash: hash[s[i]...
def convertToDecimal(n): arr = list(str(n)) print arr i = len(arr) - 1 #print i dec = 0 while i >= 0: dec = dec + 2**i*int(arr[(len(arr)-i-1)]) #print i, 2**i,dec i = i - 1 return dec print convertToDecimal('0101011010')
# -*-coding:utf-8 -*- __author__ = '$' import numpy as np import re import itertools from collections import Counter import os import csv import jieba import random import collections import gensim from gensim import * def count_tf(): data1 = [] data2 = [] data3 = [] data4 = [] data5 = [] wi...
num1 = input("첫 번째 실수 : ") num2 = input("두 번째 실수 : ") print(float(num1) + float(num2)) num1 = float(input("첫 번째 실수 : ")) num2 = float(input("두 번째 실수 : ")) print(num1 + num2)
from django import forms from django.forms import ModelForm class UploadFileForm(forms.Form): file = forms.FileField()
from typing import Optional, List, Callable, Tuple import torch from torch import Tensor from torch.utils.data import Dataset, DataLoader from utils import make_batch_one_hot import numpy as np def icarl_accuracy_measure(test_dataset: Dataset, class_means: Tensor, val_fn: Callable[[Tensor,...
""" Heat Relaxation A horizontal plate at the top is heated and a sphere at the bottom is cooled. Control the heat source using the sliders at the bottom. """ from phi.flow import * DOMAIN = dict(x=64, y=64, extrapolation=0) DT = 1.0 x = control(32, (14, 50)) y = control(20, (4, 40)) radius = control(4, (2, 10)) tem...
from flask_jsonpify import jsonify def hello(): return jsonify({'text':'Hello World!'})
""" Testes de internacionalização """ import gettext x = gettext.bindtextdomain('mensagens') print(x) _ = gettext.gettext print(_('this'))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 16/4/24 下午1:38 # @Author : ZHZ import pandas as pd if1 = pd.read_csv("/Users/zhuohaizhen/PycharmProjects/Tianchi_Python/Data/OutputData/1_if1.csv",index_col = 0) # isf1 = pd.read_csv("/Users/zhuohaizhen/PycharmProjects/Tianchi_Python/Data/OutputData/1_isf1...
from app import app from flask import jsonify import os @app.route('/') def index(): SECRET_KEY = os.environ.get("SECRET_KEY") msg = '' if not SECRET_KEY: msg = "<h1>Hello from Flask</h1>" else: msg= f'<h1>Hello from Flask. You secret is {SECRET_KEY}</h1' return msg @app.route...
import numpy as np import pandas as pd #write function that takes in two strings and returns if strings are equal def check_two_strings(string1,string2): #split strings 1 and 2 and get distance length_string1_split = len(list(string1.upper())) length_string2_split = len(list(string2.upper())) return(length_strin...
from employee import Employee emp_1 = Employee(1, "Sunny", "M.tech", 56000, "CS") emp_2 = Employee(2, "Bunny", "M.tech", 46000, "IS") emp_1.show_info() emp_2.show_info() emp_1.increment_salary(3000) emp_1.show_info() emp_2.show_info()
#!/usr/bin/env python3 import os import sys print(sys.argv) cmd = " ".join(["ttracer_invoker", "start"] + sys.argv[1:]) print(cmd) os.system(cmd)
def F (W:list,X:list) -> float: retVal = 0. for i in range(len(X)): retVal += W[i] * X[i] return retVal def signum (val:float)->int: return +1 if val > 0 else -1 if val < 0 else 0 def recalcWeight(Wold, Xvec, Y, C, error): newW = [] for i in range(len(Wold)): newW.append(Wold[i]+...
# Generated by Django 2.2.6 on 2019-12-05 15:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('work', '0054_auto_20191203_1652'), ] operations = [ migrations.RemoveField( model_name='progressqty', name='review',...
# Generated by Django 3.2.3 on 2021-06-12 05:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pizza_app', '0011_ingredientsize_orden'), ] operations = [ migrations.RemoveField( model_name='pizza', name='size', ...
from kafka import KafkaProducer from kafka import KafkaConsumer from kafka.errors import KafkaError from elasticsearch5 import Elasticsearch import json import datetime class KafkaC: """ 消费模块: 通过不同groupid消费topic里面的消息 """ def __init__(self, kafka_host, kafka_port, kafka_topic, group_id): se...
# -*- coding: utf-8 -*- """ Created on Wed Apr 17 14:28:53 2019 @author: Vall """ import iv_plot_module as ivp import iv_utilities_module as ivu import matplotlib.pyplot as plt from math import sqrt from numpy import pi import numpy as np from scipy.optimize import curve_fit #%% def getValueError(values, errors=Non...
def fibb(n): fibNums = [0, 1] for i in range(2, n+1): fibNums.append(fibNums[i-2]+fibNums[i-1]) return fibNums[n] N = int(input()) print(fibb(N))
""" Box-and-Whisker Plot """ import scripts.plot._tools as tools import argparse as ap import os import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from typing import Dict, Any, Optional def load_dataframe(ifname: str) -> pd.DataFrame: # Get file extension _, ext = os.path.spl...
n=input ('enter a no') m=2 count=0 while count < n: for i in range (2,m): if m%i==0: break else: print m, count+=1 m+=1
# Write a Python program to count the number of elements in a list within a specified range. def countElement(n,m,listprovided): count = 0 for i in range(len(listprovided)): if listprovided[i]>=n and listprovided[i]<=m: count += 1 else: pass return count listprovi...
import math import matplotlib import random class co: one = 0 two = 0 test = range(1,102) def calc(one=random.randint(1,401)): price = co.one + (co.two * one) return price,one def cochange(change="add"): if change == "take": co.one -= int((100*price_check))+1 co.two -= int((100*pri...
'''Rotation of an image means rotating through an angle and we normally rotate the image by keeping the center. so, first we will calculate center of an image and then we will rotate through given angle. We can rotate by taking any point on image, more preferably center''' from __future__ import print_function ...
from django.db import models from django.contrib.auth import get_user_model # from accounts.models import CustomUser class Blog(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) text = models.TextField() created_on = models.DateTimeFi...
from chainer import Chain, serializers, optimizers, cuda, config import chainer.links as L import chainer.functions as F from chainer import iterators from chainer import Variable import numpy as np import const import os.path import pandas as pd from time import time import util cp = cuda.cupy class UN...
class BankAccount: def __init__(self, name, surname): self.name = name self.surname = surname self._balance = 0 self._password = '' def set_balance(self, amount): self._balance += amount def set_password(self, parole): self._password = parole def get_ba...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class TensorflowToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f0...
#!/usr/bin/env python3 """ QAMatching.py used for this QAMatchingServer.py Created by Sriram Sitharaman, Damir Cavar Version: 0.1 Given a input Natural Language query, Identifies the matching regex and hits the neo4j graph DB with the corresponding Cypher query 11/30/2017 : Created by Sriram Sitharam...
#!/usr/bin/env python3 import shutil import os # change current directory to "/home/student/mycode" os.chdir('/home/student/mycode/') ''' Calling shutil.move(source, destination) will move the file or folder at the path source to the path destination and will return a string of the absolute path of the new location...
import os, sys from .Faresystem import Faresystem from .Linki import Linki from .Network import Network from .NetworkException import NetworkException from .PTSystem import PTSystem from .PNRLink import PNRLink from .Supplink import Supplink # add ..\_static for dataTable import sys.path.append(os.path.abspath(os.path...
from flask import Flask, jsonify, url_for, make_response, request, abort from rele import inicializaPlaca, definePinoComoSaida, escreveParaPorta, obterEstadoPorta reles = [] def init(): inicializaPlaca() definePinoComoSaida(7) definePinoComoSaida(11) escreveParaPorta(7, 0) escreveParaPorta(11,...
import datetime as dt from django.test import TestCase, Client from django.utils import timezone from .models import * from .scheduler import * from .statistics import * class TaskModelTests(TestCase): # Test that marking a task as done works as expected def test_mark_done_on_todo_task(self): # Crea...
# JTSK-350112 # regexw.py # Taiyr Begeyev # t.begeyev@jacobs-university.de import csv import re import datetime def extract_time(row): y = int(row[1]) mn = int(row[2]) d = int(row[3] ) h,m = row[4].split(':') h = int(h) m = int(m) return datetime.datetime(y, mn, d, h, m) def extract_temp(...
#!/usr/bin/python3 for numbers in range(0, 99): print("{:02d}".format(numbers), end=', ') print("{:02d}".format(numbers + 1))
import sbol3 import tyto import labop ############################################# # Helper functions # set up the document doc = sbol3.Document() sbol3.set_namespace("https://sd2e.org/LabOP/") ############################################# # Import the primitive libraries print("Importing libraries") labop.import_...
# Generated by Django 2.2.12 on 2021-04-25 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('task', '0009_auto_20210425_1311'), ] operations = [ migrations.AddField( model_name='task', name='image', ...
import requests date = '13990507' url = 'http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=' + date r = requests.get(url, allow_redirects=True) open(date+'.xlsx', 'wb').write(r.content)
segundos = int(input("Ingrese una cantidad en segundos: ")) if len(str(segundos)) <=5 and (segundos)>0: horas = 0 minutos = 0 while segundos > 3600: horas = horas + 1 segundos = segundos - 3600 while segundos > 60: minutos = minutos + 1 segundos = segundos - 60 ...
import numpy as np import scipy.spatial.distance as dist from permaviss.simplicial_complexes.vietoris_rips import vietoris_rips def test_vietoris_rips(): X = np.array([[0, 0], [1, 0], [0, 1], [1, 1]]) Dist = dist.squareform(dist.pdist(X)) # Expected values expected_complex = [ 4, np....
# найти ивывести строки, содержащие двоичную запись числа, кратного 3. import re import sys pattern = r"^((1(01*0)*1|0)*)$" for line in sys.stdin: try: test_line = line.rstrip() f = re.findall(pattern, test_line) if f is not [] and f[0][0] == test_line: print(f[0][0]) exce...
import torch import numpy as np class Resize_preprocess(object): """Rescales the input PIL.Image to the given 'size_w,size_h'. """ def __init__(self, size_w, size_h): self.size = (size_w, size_h) def __call__(self, img): return img.resize(self.size) class AverageMeter(object): ...
#!/usr/bin/python # -*- coding: UTF-8 -*- import urllib import re import time pre_url = 'http://movie.douban.com/top250?start=' top_urls = [] top_tag = re.compile(r'<span class="title">(.+?)</span>') top_content = [] top_num = 1 def getHtml2(url2): html2=urllib.urlopen(url2).read().decode('utf-8') return ht...
#!/usr/bin/env python # pylint: disable=I0011,C0103,C0326 import os.path import shutil import dill # Languages are a tuple with a full name and a short name. # LANGUAGES = [("Haskell", "hs"), ("Javascript", "js"), ("MATLAB", "m")] LANGUAGES = [("Cpp", "cpp"), ("R", "r"), ("Rcpp", "rcpp")] # The ligatures dict associ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ 创建时间:Sun Aug 5 09:42:55 2018 作者: 星空飘飘 平台:Anaconda 3-5.1.0 语言版本:Python 3.6.4 编辑器:Spyder 分析器:Pandas: 0.22.0 解析器:lxml: 4.1.1 数据库:MongoDB 2.6.12 程序名:autologinzdiao.py 登陆中调网 http://www.zdiao.com/ 模拟浏览器登录输入验证码10后自动登录获取cookie 通过id定位元素:find_element_by_id(“id_vaule”) 通过name定位元素:f...
from kafka import KafkaProducer import sys import time import os f=list(open('/home/student1/streamingGc/dataset/foil13/TAXI_sample_new_3.csv')) producer= KafkaProducer(bootstrap_servers=['localhost:9092']) prev=None counter=0 i=0 modCounter = 0 while(i<int(sys.argv[1])): s= f[i] bt = s.split(',',1)[0] ...
"""Custom template tags.""" from datetime import datetime from django import template from django.template import Context, Template from django.utils.safestring import mark_safe from django.utils.translation import gettext as _ from modoboa.core import signals as core_signals register = template.Library() @regist...
from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest import random from common import cache_ def send_code(phone): #生成code code_set = set() while len(code_set) < 4: code_set.add(str(random.randint(0.9))) code = ''.join(code_set) #保存code到缓存中,-redis ...
#!/usr/bin/env python3 import RPi.GPIO as GPIO import socket import sys import time port = 3 GPIO.setmode(GPIO.BCM) GPIO.setup(port, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) HOST = '10.42.0.1' # later: identify automatically the ip (fast implementation) PORT = 80 bytes_encoding = 'utf-8' print(GPIO.input(port)) with ...
from rest_framework import serializers from .models import * from django.contrib.auth.models import User class KlientS(serializers.ModelSerializer): class Meta: model = Klient fields = ['Imie', 'Nazwisko', 'Telefon','Kod_pocztowy', 'Adres', 'Miasto'] class Dane_firmyS(serializers.ModelSer...
import torch as tc import torch.nn as nn import torch.nn.functional as F import torch.optim as optim tc.manual_seed(1) x_train=tc.FloatTensor([[1],[2],[3]]) y_train=tc.FloatTensor([[2],[4],[6]]) W=tc.zeros(1,requires_grad=True) print(W) b=tc.zeros(1,requires_grad=True) print(b) hypothesis=x_train*W+b print(hypothesi...
from datetime import datetime from http import HTTPStatus from modules.db import get_db_data, set_db_data, bulk_client_update, bulk_service_update import MySQLdb import configparser import itertools import json import logging import numpy as np import os import plotly import plotly.plotly as py import plotly.graph_obj...
#######Prepare QGIS for working############################################################################################################################# ############################################################################################################################################################ from ...
# 150. Evaluate Reverse Polish Notation class Solution: def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ import operator as ops operands = [] opes = {'+': ops.add, '-': ops.sub, '*':ops.mul, ...
"""\ Usage: python ChouFas_predictor.py <fasta_file> Options: <fasta_file> protein FASTA file --help print help message """ import sys from time import sleep ... # Chou-Fasman Amino Acids Propensities Value For Helix helix = {"A":1.45, "C":0.77,"D":0.98,"E":1.53,"F":1.12,"G":0.53,"H":1.24,"I":1.00,"K":1.07, "L...
import cv2 import numpy as np import argparse import imutils ap=argparse.ArgumentParser() ap.add_argument('-i','--image',required=True,help='Path to the image') args=vars(ap.parse_args()) image=cv2.imread(args['image']) cv2.imshow('Original',image) (h,w)=image.shape[:2] center=(w/2,h/2) M=cv2.getRota...
from rest_framework import permissions class IsAdmin(permissions.BasePermission): def has_permission(self, request, view): return request.user.is_admin class IsApothecary(permissions.BasePermission): def has_permission(self, request, view): return request.user.role == 'apothecary' class Is...
import matplotlib.pyplot as plt import math import numpy as np y = [] p_range = np.arange(0.00001,0.99999,0.00001) gamma_range = np.arange(0.1,3.0,0.3) for gamma in gamma_range: y.append([]) for p in p_range: q = 1.0 - p weighted_p = math.exp(-1*(math.pow(math.log(1.0/p),gamma))) y[-1...
#-*- coding=utf-8 -*- from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo, DataRequired from wtforms import ValidationError from ..models import User from flask import session cla...
from django.urls import path, include from .views import FavouriteProducts, add_favourite_product urlpatterns = [ path('favourite-products', FavouriteProducts.as_view(),name='favourite-products'), path('add_favourite_product', add_favourite_product,name='add_favourite_product'), ]
# # @lc app=leetcode.cn id=515 lang=python3 # # [515] 在每个树行中找最大值 # # @lc code=start # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def largestValues(self, root: Op...
# Script to create RBAC roles-to-rights map for IEEE 1547-2018 points. RBAC roles and rights are created based on the # recommendations in J. Johnson, “Recommendations for Distributed Energy Resource Access Control,” # Sandia Technical Report SAND2021-0977, 2021. # # Comments to jjohns2@sandia.gov import json import o...
import os if __name__ == "__main__": # For direct call only import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import random import pytest import math import glob import time import numpy as np import pylo # python <3.6 does not define a ModuleNotFoundError, use this fallback fro...