text
stringlengths
38
1.54M
from collections import defaultdict tool_vs = dict() with open("plausible.txt") as f: for line in f: if ":" in line: tool = line.split(":")[0] versions = line.split(":")[1].split() tool_vs[tool] = versions tool_exclu_versions = defaultdict(list) for tool_target in tool_vs: # each target tool target_v...
class Solution: def numsSameConsecDiff(self, N: int, K: int) -> List[int]: nums = list(range(1, 10)) if N == 1: nums.append(0) return nums for i in range(N - 1): newnums = [] for n in nums: if n % 10 + K <= 9: ...
from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from rest_framework import serializers from rest_framework.response import Response from .models import ( CarouselDisplay, Kudos, SurveyTopics, RespondentProfile, YaridAccount, QuestionPosts) # ...creat...
def es_primo(n): for numero in range(2, n): if n % numero == 0: return False return True primos = filter(lambda n: not es_primo(n), range(101)) print(list(primos))
#!/usr/bin/python # -*- coding: latin-1 -*- # -------------------------------------------------------------------------------- # @Title: Python example demonstrating various functions of the TRACE32 remote API # @Description: # After establishing a remote connection with TRACE32 PowerView a menu offers # various API...
#coding=utf-8 ''' Created on 2015-12-30 @author: lamter ''' # from gevent import monkey # monkey.patch_all() import time import unittest import json import socket from lib.woodmoo import * import conf_server import conf_debug from request import BaseRequest ''' 建立 redisco 的链接 ''' class TestSocket(unittest.TestC...
from PIL import Image import numpy import time start=time.time() im = Image.open("hello.png") #vaule coulers_found['237-28-36', '255-255-255', '34-177-76'] coulers_found={} array_to_use = numpy.array(im) loopcounter=0 scan=[[1,0],[-1,0],[0,1],[0,-1]] look_for_vaule=(0,0,0) x_postion=-1 y_postion=-1 box=[] qwe=...
#!/usr/bin/env python ''' Created on 19.12.2012 @author: hamood ''' import pika import time from string import Template import sys import os import stat import shutil import simplejson as json import logging import logging.handlers import ftplib import urllib2, base64 import tempfile import subprocess #import context...
import time start_time = time.clock() #a max value for the price Max_val = 1000000 #read data into a dic def read(): names = ["from","to","departuredate","departuretime","arrivaldate","arrivaltime","price","class","code","airline","departurehash","arrivalhash"] data = {} for n in names: f = open(n+...
import tables import numpy as np import numpy.lib.recfunctions as rfn class rpkm_data: def __init__(self): self.rpkm = None self.samples = None self.exons = None self.isGenotype = False self.calls = [] self.refined_calls = [] def smooth(self, window=15, padded=...
import sys sys.stdin = open("4466.txt") t = int(input()) for tc in range(1,t+1): n, k = map(int, input().split()) ns = list(map(int, input().split())) ns.sort(reverse=True) print('#{} {}'.format(tc,sum(ns[:k])))
import sys from utils import Vertex from utils import Graph from utils import parse_file from collections import defaultdict def main(): try: in_file_name = sys.argv[1] except Exception: sys.stderr.write('Usage: python scc.py ${in_file_name}') graph = parse_file(in_file_name) result =...
# -*- coding: utf-8 -*- # author: seven from pocsuite3.api import register_poc, POCBase, Output,logger,POC_CATEGORY,requests from pocsuite3.lib.core.threads import run_threads import random class TomcatCmdExecPOC(POCBase): vulID = 'CVE-2017-12615' version = '1.0' author = ['seven'] vulDate = 'Aug 10, ...
""" 最长上升子序列 标签:动态规划、贪心 链接:https://leetcode-cn.com/problems/longest-increasing-subsequence 给定一个无序的整数数组,找到其中最长上升子序列的长度。 示例: 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 说明: 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。 你算法的时间复杂度应该为 O(n2) 。 进阶: 你能将算法的时间复杂度降低到O(n log n) 吗? 官方解法: 1. 动态规划。 状态定义:dp[i] 为第 i 个元素的...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import datetime import pickle import os.path import json from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import date_time_helper import gcal_variables # create a Google Calendar API endpoint # :param scopes (list) - a...
from styx_msgs.msg import TrafficLight import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from PIL import Image from PIL import ImageDraw from PIL import ImageColor import time import cv2 import sys import rospy import roslib from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvB...
#!/usr/bin/env python import unittest from dominion import Game, Card, Piles import dominion.Card as Card ############################################################################### class Card_Dismantle(Card.Card): def __init__(self): Card.Card.__init__(self) self.cardtype = Card.CardType.ACT...
''' Created on Jan 6, 2017 @author: Vansh-PC ''' from django.contrib import admin from .models import Profile,LinkedInProfile admin.site.register(Profile) admin.site.register(LinkedInProfile)
# -*- coding: utf-8 -*- #from django.contrib.auth.decorators import login_required from menu import * from megavideo.common.DiggPaginator import * from django.shortcuts import render_to_response from django.template import RequestContext from django.template.defaultfilters import slugify from megavideo.common.dlog impo...
from django.urls import path from .import views urlpatterns = [ path('product-details/<slug:slug>', views.product_details, name='product_details'), ]
"""Alarmageddon main module""" __version__ = "1.0.4" from alarmageddon.run import run_tests, construct_publishers, load_config
from tkinter import * from tkinter import messagebox as mb class Point(): def __init__(self, x, y, pointer): self.x = x self.y = y self.pointer = pointer class Triangle(): def __init__(self, x1, y1, x2, y2, x3, y3): self.x1 = x1 self.y1 = y1 self.x2 = x2 ...
from .generalFeedbackObj import GeneralFeedback class ErrorFeedback(GeneralFeedback): def __init__(self, attendee_id, meeting_id, error_type, error_message): super().__init__(attendee_id, meeting_id) self.error_type = error_type self.error_message = error_message def get_...
#!/usr/bin/env python """ Convert strings to LaTeX strings in math environment used by matplotlib's usetex This module was written by Matthias Cuntz while at Department of Computational Hydrosystems, Helmholtz Centre for Environmental Research - UFZ, Leipzig, Germany, and continued while at Institut National de Recher...
import uvicorn from projectname.main import app def run(): uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True, headers=[("server", "you-custom-web-name")]) if __name__ == "__main__": run()
import streamlit as st # To make things easier later, we're also importing numpy and pandas for # working with sample data. import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import altair as alt import scipy.special from modules.sidebar import run_sidebar import modules.opt_runsim as ...
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Jiao Lin # California Institute of Technology # (C) 2009 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-04-05 10:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0009_auto_20180405_1125'), ] operations = [ migrations.AlterField...
#coding:utf-8 from protector.models import Restriction, OwnerToPermission, \ GenericUserToGroup, GenericGlobalPerm from django.contrib import admin class OwnerToPermissionAdmin(admin.ModelAdmin): list_filter = ('owner_content_type', ) list_display = ('owner_content_type', 'owner_object_id', 'date_issued',...
def bigSum(num1,num2): rez="" trecere=0 for i in range(1,min(len(num1),len(num2))+1): s=int(num1[-i])+int(num2[-i])+trecere if s>9: trecere=1 else: trecere=0 rez=str(s%10)+rez if len(num1)>len(num2): for i in range(min(len(num1),len(num2))+...
import numpy as np def nprint(arr): print(f'type : {type(arr)}') print(f'shape : {arr.shape}') print(f'ndim : {arr.ndim}') print(f'dtype : {arr.dtype}') print(f'Data :\n {arr}') a=np.array([1,2,3,4,5]) nprint(a) print() b=np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],...
import numpy as np import nn_sigmoid as sigmoid import nn_sigmoid_gradient as sigmoid_gradient ''' NNCOSTFUNCTION Implements the neural network cost function for a two layer neural network which performs classification [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ... X, y, lambda) compute...
import numpy as np x = np.linspace( 0, 2, 9 ) print(x) b = np.zeros(len(x)) for i in range(len(x)): b[i] = x[i]*(np.pi) print(b[i]) print("Hello World! Python Here")
# coding=utf-8 from flask_admin import BaseView, expose import flask_login as loginflask from Snackbar.Models.User import User from Snackbar.Helper.Billing import rest_bill, make_xls_bill from Snackbar.Helper.Mailing import send_reminder from Snackbar import app from flask import redirect, url_for, current_app, send_f...
#calculate WER from CER #average number of chars in training transcripotions #calculated with avg.py languages = { 'ady':5.9925, 'gre':6.73125, 'ice':5.72, 'ita':6.625, 'khm':5.5125, 'lav':5.94375, 'mlt_latn':5.1675, 'rum':6.1475, 'slv':5.7475, 'wel_sw':5.18375 } import sys import numpy as np #cer val = fl...
""" Exercício Python 036: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. """ valor_casa = float(input('Informe o valo...
import requests from bs4 import BeautifulSoup from PIL import Image from io import BytesIO import os # Web Scrapper that scrapes the images from the Unsplash website # and stores them in a new directory by the name of the search term def scrapper(): search = input("Enter the terms to search for ") search = se...
#%% """ This dataset contains employee career profile and attrition (departure from company) information, such as age, department, job role, work/life balance, and so forth. Using this data, generate a deep learning model that can help to identify whether or not a person is likely to depart from the company given...
import sys sys.path.append( "../../../" ) from dan.lib.helper import * import math import random from solid import * from solid.utils import * parts = [] point_count = 10 distance = math.pi*.5 points = [Vec3(math.cos(a)*10, math.sin(a)*10, 0) for a in [(i/float(point_count-1))*distance for i in range(point_count)]...
from bfieldtools import utils import numpy as np import pytest def test_mesh_utils(): mesh1 = utils.load_example_mesh("unit_disc") mesh2 = utils.load_example_mesh("10x10_plane") mesh2.vertices += np.array([[0, 0, 20]]) mesh3 = utils.combine_meshes((mesh1, mesh2)) assert len(mesh3.vertices) =...
# -*- coding: utf-8 -*- # 写代码是热爱,写到世界充满爱! # @Author:AI悦创 @DateTime :2019/10/1 16:58 @Function :功能 Development_tool :PyCharm from sqlalchemy import create_engine,Column,Integer,String,ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship # 建立一对多...
""" Library Features: Name: lib_graph_map_base Author(s): Fabio Delogu (fabio.delogu@cimafoundation.org) Date: '20210903' Version: '1.0.0' """ ####################################################################################### # Libraries import logging import os import cartopy import ...
#find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20.. n=232792500 # the running number, takes a long while... so start at this number x=11 #checks starting at 11, 11-20 have multiples of 1-10 so we dont need to double check for divisability while 1>0: #while True pr...
class A: def __init__(self): self.num1 = 100 self.__num2 = 200 def __test__(self): print("私有方法 %d %d" % (self.num1,self.__num2)) class B: pass #创建一个子类对象 b = B() print(b) #在外界不能直接访问私有属性和方法 #print(b.__num2) #b.test()
""" The module contains common algorithms implemented in python for practice """ #! /usr/bin/env python def get_fib(nth_fib): '''Returns the nth fibonnacci number with innefficient recursion''' if nth_fib <= 0: return 0 elif nth_fib == 1: return 1 else: return get_fib(nth_fib - ...
from django.db import models # Creacion de modelos class Rol(models.Model): nombre = models.CharField(max_length=30) class Usuario(models.Model): nombres = models.CharField(max_length=50) apellidos = models.CharField(max_length=50) cedula = models.CharField(max_length=20) celular = models.CharFie...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-05-25 15:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Control', '0023_auto_20170525_2255'), ] operations = [ migrations.AlterFiel...
import requests from bs4 import BeautifulSoup URL = 'https://vidstreaming.io/videos/dr-stone-dub-episode-7' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} page = requests.post(URL, headers=headers) #soup = Beautif...
''' 时间日期 ''' from datetime import datetime now = datetime.now() # 2018-10-21 14:30:25.410863 print(now) dt = datetime(2017,1,29) # 2017-01-29 00:00:00 print(dt) timestamp = dt.timestamp() # 1485619200.0 print(timestamp) date = datetime.fromtimestamp(timestamp) print(date) utcdate = datetime.utcfromtimestamp(ti...
"""leaderboard table Revision ID: 9879036ea4bd Revises: Create Date: 2019-08-22 01:45:24.590124 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9879036ea4bd' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto ...
from sqlalchemy import create_engine, text from rx import Observable engine = create_engine('sqlite:///rexon_metals.db') conn = engine.connect() def get_all_customers(): stmt = text("SELECT * FROM CUSTOMER") return Observable.from_(conn.execute(stmt)) def customer_for_id(customer_id): stmt = text("SEL...
import math from cached import cached, auto_cached class Number: def __init__(self, x, counters): self._x = x self._counters = counters def value(self): return self._x @cached("_sqrd_x") def value_squared(self): # Keep track of the amount of times this method has bee...
def kalkulator(): print('\n\t==================================') print('Program Kalkulator Sederhana') print('1. Pertambahan') print('2. Pengurangan') print('3. Pembagian') print('4. Perkalian') pilih = input("\n\tsilahkan pilih : ") if pilih == "1": tambah() elif pilih == "...
import numpy as np LRn222 = 3.8235 * 24 * 60 * 60 # the half-life for Rn-222 (in seconds) LPo218 = 3.098 * 60 # the half-life for Po-218 LPb214 = 26.8 * 60 # the half-life for Pb-214 LBi214 = 19.9 * 60 # the half-life for Bi-214 LPo214 = 164.3e-6 # the half-life for Po-214 DC1HL = np.array([LRn222, LPo218, LPb21...
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-06 05:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('abchrms', '0013_auto_20180706_1021'), ] operations = [ migra...
import json from collections import defaultdict from copy import deepcopy import click from loguru import logger import torch from ax.service.ax_client import AxClient from tqdm import trange from scripts.predict_transformers import evaluate from scripts.train_transformers import do_train from scripts.utils_transform...
import sys import csv import json import math def to_csv(): u = float(sys.argv[1]) s = float(sys.argv[2]) with open("./data.csv", "w") as file: writer = csv.writer(file, delimiter=',') for i in range(201): res = (1 / (s * math.sqrt(2 * math.pi))) * (math.exp(-0.5 * math.pow((i ...
#!/usr/bin/env python3 import sys import re import numpy from pprint import pprint from multiprocessing import Pool INPUT = 'd11-input.txt' GRIDW = 300 GRIDH = 300 DEBUG = False # The current implementation runs reasonably fast. The key factor that # makes it speedy enough is the use of numpy.ndarray.sum() instead of...
# Trabalho de Processamento de Imagens (OCR) # Curso: Ciência da Computação - 2021/2 - PUCMG # Professor(a): Alexei Manso Corrêa Machado # Alunos: Ana Flávia Dias, Eduardo Pereira, Jonathan Douglas e Umberto Castanheira # Data da última modificação: 04/11/2021 # Arquivo: svm.py #Importações import numpy as np ...
import time import re CURR_MS = lambda: time.time() * 1000 print('+-------------------------+') print('| ADVENT OF CODE - DAY 04 |') print('+-------------------------+') START_READ = CURR_MS() print('\nREADING FILE... ',end='') with open("input.txt") as file: inputs = file.read().strip().split('\n\n') print('%.6...
filename = "a.in" outfilename = "output.txt" def solve(f): n = int(f.readline()) arr = map(int, f.readline().split()) a = 'A' senate = [] for i in range(n): senate.append([arr[i], chr(ord('A') + i)]) ans = [] while senate: senate = list(reversed(sorted(senate))) if ...
import Arm_calculus as bib import Arm as bot import Magnet as mag import time class Fork(Tool): def pickup_fork(self, Position): """ This function assumes the fork is laid up with the teeth in the direction of the robot's x axis. """ orientation=checkmagnets(M0,M5) #TODO ...
import pandas as pd import csv import sys from bs4 import BeautifulSoup from urllib.request import urlopen from datetime import datetime, date, timedelta def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) def main(argv): r = urlope...
import numpy as np import os import sys import autopath from wmt16.ml_app.utils.app_funs import get_domain, read_lett from wmt16 import lexical_filter #TODO: set these constants debug=False vector_size = 4 #TODO: set it, the size of feature for a candidate pair #train_dir_path = '/tmp/u/vutrongh/lett.train' train_dir...
''' 深度优先搜索 后进先出的 LIFO stack ''' # 邻接表 V = { "A": ["F", "G"], "B": ["A", "I"], "C": ["A", "D"], "D": ["C", "F"], "E": ["C", "D", "G"], "F": ["E"], "G": [], "H": ["B"], "I": ["H"], } def dfs(V, initNode, visited): stack = [initNode] while True: if len(stack) <= 0: ...
from mail_bug.mail_bug import MailBug def test_return_code(): bug = MailBug([]) assert bug.run() == 0
import sys import os # Add project top level directory to search path. sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) from ralibrarynotification.main import main if __name__ == '__main__': main()
#### Class05 #### Googlemaps API # pip install googlemaps ## https://console.developers.google.com/apis/credentials?project=_ ## need geocoding and distance matrix APIs enabled import imp <<<<<<< HEAD <<<<<<< HEAD imported_items = imp.load_source('pythoncourse2018', 'C:/Users/wooki/Documents/GitHub/pythoncourse2018/da...
#<ImportSpecificModules> from ShareYourSystem.Standards.Classors import Representer from ShareYourSystem.Standards.Objects import Initiator #</ImportSpecificModules> #Print a version of the class Representer._print(dict(Representer.RepresenterClass.__dict__.items())) #Print a version of this object Representer._prin...
from django.contrib import admin from .models import Usuario,Factura,Producto # Register your models here. admin.site.register(Factura) admin.site.register(Usuario) admin.site.register(Producto)
import csv import datetime def dragCoefficient(model,velocity,mach_conversion): if model == "G7": with open("G7 Drag Function.csv") as G7DragFile: G7Drag = list(csv.reader(G7DragFile)) #Used for interpolation y = (y1-y0)/(x1-x0)*(x-x0)+y0 x_values = [] y_valu...
from django.contrib.auth.models import User from django.shortcuts import render from .serializers import MyTokenObtainPairSerializer, RegisterSerializer from rest_framework.permissions import AllowAny from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import generics class MyObtainToke...
def createDeck(): lst = [] for i in 'shdc': for j in range(1, 14): if j == 1: card = 'A' + i elif j == 10: card = 'T' + i elif j == 11: card = 'J' + i elif j == 12: card = 'Q' + i ...
# -*- coding:utf-8 -*- ### # File: save2onnx.py # Created Date: Thursday, September 26th 2019, 2:15:41 pm # Author: yusnows # ----- # Last Modified: # Modified By: # ----- # Copyright (c) 2019 yusnows # # All shall be well and all shall be well and all manner of things shall be well. # Nope...we're doomed! # ----- # HI...
# -*- coding: utf-8 -*- __autor__ = "Jose Jiménez Lopez, Fundación I+D del Software Libre" __email__ = "jjimenez@fidesol.org" __date__ = "10/05/2012" # Put here the models you want to manage through the Django Admin from models import ProductTranslation, Product, ProductImage from django.contrib import admin class P...
# -*- coding: utf-8 -*- """ exceptions.py Exceptions raised by the Alpha Trade client. :license: see LICENSE for details. """ class AlphaException(Exception): """ Base exception class representing a Alpha Trade client exception. Every specific Alpha Trade client exception is a subclass of t...
import pytest from asynctest import mock as async_mock from ......core.protocol_registry import ProtocolRegistry from ......core.goal_code_registry import GoalCodeRegistry from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder from ......protocols.issue_credenti...
def is_palindrome(s): n = len(s) if n == 0 or n == 1: return 1 return s[0] == s[n - 1] and is_palindrome(s[1:n - 1])
# -*- coding: utf-8 -*- import parse import links import os, csv import math import cPickle as pickle import operator # ----------------------------------------------------------------------------- def index(): redirect(URL("default", "run")) plots = UL(LI(A("[Barchart] Total score per over", _href=links.get(1...
from websocket import create_connection ws = create_connection("ws://localhost:8000/ws") ws.send("Hello, World") result = ws.recv() print("Received '%s'" % result) ws.close()
from tkinter import * from vue.base_frame import BaseFrame from controller.Bras_controller import BrasController as B from controller.Moteur_controller import MoteurController as M class ListMicrocontroleurFrame(BaseFrame): def __init__(self, Microcontroleur_controller, Bras_controller, Moteur_contro...
#! /usr/bin/env python """ Author: LiangLiang ZHENG Date: File Description """ from __future__ import print_function import sys import argparse class Solution(object): def concatenatedBinary(self, n): """ :type n: int :rtype: int """ # Solution 1 #res = "" ...
import struct FORMAT_DICT = { '1_S_B': '>b', '1_U_B': '>B', '1_S_L': '<b', '1_U_L': '<B', '2_S_B': '>h', '2_U_B': '>H', '2_S_L': '<h', '2_U_L': '<H', '4_S_B': '>i', '4_U_B': '>I', '4_S_L': '<i', '4_U_L': '<I', '8_S_B': '>q', '8_U_B': '>Q', '8_S_L': '<q', '8_U_L': '<Q', '4_F_B': '>f',...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # In[2]: orders = pd.read_csv("./orders.csv") orders.head() # In[3]: products=pd.read_csv("./products.csv") products.head() # In[5]: products # In[6]: aisle = pd.read_csv("./aisles.csv") dept=pd.read_csv("./departments.csv") # In[7]...
from django.db import models # Create your models here. #don't forget to write important __str__ function for each class School(models.Model): name=models.CharField(max_length=200) degree=models.CharField(max_length=100) start=models.DateField() end=models.DateField() marks_type=models.CharField(...
import sys def parseFile(filename): f = open(filename, 'r') for l in f: l = l.replace('^', '**') s = eval(l) if isinstance(s, float): f = "%0.5f" % s if f.endswith('.00000'): print int(s) else: print f else: ...
import threading import pandas import requests from bs4 import BeautifulSoup result_dir = '../results/PMC-validation/' top_limit = 100 lncRNA_disease_prediction_path = '../data/lncRNA-disease-prediction.csv' base_url = 'https://www.ncbi.nlm.nih.gov/pmc/?term=' # https://www.ncbi.nlm.nih.gov/pmc/?term=(Breast+cancer)...
import datetime from django.contrib.auth.models import User from django.core.cache import cache from django.core.exceptions import ValidationError from django.db import models from misc.validators import expires_at_validator, mask_validator from utilities import postmarkup from utilities.annoying.functions import get_c...
import tensorflow as tf y = tf.linspace(-2., 2, 5) print(y) x = tf.linspace(-2., 2, 5) print(x) point_x, point_y = tf.meshgrid(x, y) print(point_x) print(point_y) points = tf.stack([point_x, point_y], axis=2) print(points.shape) print(points) print(tf.reshape(points, [25, 2])) print('------------------------------...
""" Create a nice christmas card. """ import sys import os import io from ppci import api from ppci.lang.basic.c64 import write_basic_program, BasicLine from ppci.binutils.layout import Layout, Memory, Section from ppci.utils.reporting import HtmlReportGenerator import qrcode from PIL import Image # Mapping of 2x2...
#import libraries import turtle import math #create class to create the user class User: #set initial attributes def __init__(self, name, userID): self.username = username self.userID = userID self.connections = [] #add another user's ID number to one's connection list ...
import numpy as np import matplotlib.pyplot as pl import matplotlib.pyplot as pa X=4;Y=16 # shape of grid grid=np.ones([4,16]) T=np.zeros([42,42],) #transition matrix empty_sq=[] # empty locations in the grid #epsilon=0.4 O=np.zeros([42,42]) # emission matrix # find empty squares in the grid def init_empty_sq(...
#! /usr/bin/env python from __future__ import print_function import argparse import collections import sys import numpy from readfq import readfq # Parse command line parser = argparse.ArgumentParser(description='FASTA/MSA filter tool') parser.add_argument('-m', '--msa', metavar='mafft.msa', required=True, dest='msa...
#!/usr/bin/env python print "hello" print "This is the second line, \nwhich was changed afterwards"
''' Gera audio de arquivo txt em formato wma, utiliza programas: balcon - do Software Balabolka (http://www.cross-plus-a.com/br/balabolka.htm) WMAEncode - Encode WMA (https://hydrogenaud.io/index.php/topic,90519.0.html) Por padrão de linha de comando o balcon gera em WAV, sendo necessário encode para r...
# coding: utf-8 class Solution: """ # The Hamming distance between two integers is the number of positions at which the corresponding bits are different. # Given two integers x and y, calculate the Hamming distance. # Note: # 0 ≤ x, y < 231. # 关键词:异或 """ def hammingDistance(self, x, y): ...
""" Module for Proper Orthogonal Decomposition (POD). Three different methods can be employed: Truncated Singular Value Decomposition, Truncated Randomized Singular Value Decomposition, Truncated Singular Value Decomposition via correlation matrix. """ try: from scipy.linalg import eigh except ImportError: ...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2018-09-22 10:12 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('employee', '0006_auto_20180922_1552'), ] operations = [ migrations.RemoveField( ...
#! python3 import random import copy card_deck = [['Ace of Spades', 'King of Spades', \ 'Queen of Spades', 'Jack of Spades', \ '10 of Spades', '9 of Spades', \ '8 of Spades', '7 of Spades', \ '6 of Spades', '5 of Spades', \ '4 of Spades', '3 of Spades', \ ...