text stringlengths 38 1.54M |
|---|
#coding: utf-8
from utils.utils import *
import numpy as np
print "start::", getTime()
# Fibonacci.fib()
Fibonacci.fib(7,1,1)
print "end::", getTime()
|
# -*- coding:gb2312 -*-
import time
import logging
import random
import os
import threading
import sys
import getpass
import re
import string
import datetime
import traceback
import codecs
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#递归删除路径下文件和文件夹
def delete_file_folder(src):
... |
#! /usr/bin/env python3
# Copyright (c) 2018-Present Advanced Micro Devices, Inc. See LICENSE.TXT for terms.
#
# Parts of this code were adapted from https://www.fullstackpython.com/blog/first-steps-gitpython.html
# available under MIT License: https://github.com/mattmakai/fullstackpython.com/blob/master/LICENSE
# Copy... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^social/$', 'CLEI.apps.evento.views.evento_social'),
url(r'^simultaneo/$', 'CLEI.apps.evento.views.evento_simultaneo'),
url(r'^lugar/$', 'CLEI.apps.evento.views.nuevo_lugar'),
url(r'^lugar/asignar/... |
# #################################################### The Repository
import atexit
import sqlite3
from DAO import _Vaccines, _Suppliers, _Clinics, _Logistics
class _Repository:
def __init__(self):
self._conn = sqlite3.connect('database.db')
self.vaccines = _Vaccines(self._conn)
self.supp... |
def split_and_join(line):
# write your code here
for word in line:
line1 = line.split(" ")
line2 = "-".join(line1)
return(line2)
#another way to do it
def split_and_join(line):
# write your code here
line = line.split(" ")
line = "-".join(line)
l = ""
for lett in lin... |
# -*- coding: utf-8 -*-
import csv
import glob
import os
import sys
#
# Illumina Native format of input filenames: s_(\d+)_(d+)_(\d+)_qseq.txt, where the numbers are lane, index, and tile
# index of 1 contains the sequence reads, index 2 contains the tags
#
def parse_tag_file(tag_filename):
"""Parses tag file in... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
L = 1.2
h = 0.8
N = 3
I = np.array([0 for i in range(2*N)])
VDF_inv = np.array([[0 for j in range(2*N)] for i in range(2*N)])
D = 1.5
a = 0.0035
pi = np.pi
Dz = L/N
s0 = 1/160
def z_bar(i):
if (i <= N):
zi =... |
from django.db import models
from ckeditor.fields import RichTextField
class Categoria(models.Model):
id = models.AutoField(primary_key=True)
nombre = models.CharField('Nombre de la Categoría', max_length=100, null=False, blank=False)
estado = models.BooleanField('Activo/No Activo', default=True)
fech... |
"""""
Description: This is the Main function for decision tree classification algorithm.
Uses monkdata.py, dtree.py, drawtree_qt5.py as well.
Function: Use the Machine-Learning algorithm in dtree.py to classify the unknown data set in monkdata.py
The file drawtree_qt5.py is used to draw the decision tree.
If you... |
# def find(v, x):
# if v[x] == x:
# return x
# else:
# v[x] = find(v, v[x])
# return v[x]
#
# def union(v, y, x):
# y_root = find(v, y)
# x_root = find(v, x)
# v[x_root] = v[y_root]
#
# def solution(n, computers):
# v = [_ for _ in range(n)]
# for start, row in enumer... |
"""
.. module:: PeaksClustering
PeaksClustering
*************
:Description: PeaksClustering
Clusters the Peaks from an experiment all the files together
Hace un clustering de los picos de cada sensor usando el numero de clusters indicado en la
definicion del experimento y el conjunto de colores para el ... |
from random import randint
from time import sleep
itens = ('Pedra', 'papel', 'Tesoura')
print('Escolha:')
print('[ 0 ] Pedra')
print('[ 1 ] Papel')
print('[ 2 ] Tesoura')
n1 = int(input('Digite aqui :'))
n2 = randint(0, 2)
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO')
sleep(1)
print('-_-' * 11)
print('Você esc... |
# -*- coding: utf-8 -*-
# @Time : 2017/9/10 23:51
# @Author : Forec
# @File : focus/views.py
# @Project : WildPointer
# @license : Copyright(C), Forec
# @Contact : forec@bupt.edu.cn
from flask import request, current_app, render_template, abort
from flask_login import login_required, current_user
from . import... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 15:48:17 2019
@author: id127392
"""
import os
from keras.models import load_model
import threading
import datetime
import time
import util
from dsce import dataset, train, datamanip, reduce, analyse, datastream
import tensorflow as tf
import os.path
from... |
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split, KFold
import preprocessing as prep
from sklearn.model_selection import GridSearchCV
from neural_network import prepare_data_... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db.models.expressions import F
# Create your models here.
class MyUserManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
... |
from multiprocessing.dummy import Pool as ThreadPool, current_process
def test(i):
# 本质调用了:threading.current_thread
print(f"[编号{i}]{current_process().name}")
def main():
p = ThreadPool()
for i in range(5):
p.apply_async(test, args=(i, ))
p.close()
p.join()
print(f"{current_proce... |
# order matters!
import models
from models.coach import *
from models.team import *
from models.player import *
from models.ofl_pickem import *
from models.leader import *
from models.match import *
from models.tournament import *
from models.race_stats import *
#Script to initiate all static classes for a fresh DB (... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 5 21:33:38 2017
@author: zhouying
"""
import tensorflow as tf
#import numpy as np
import myutil
class mysdae(object):
def __init__(self,input,hidden1,hidden2,transfer_function = tf.nn.softplus,
optimizer = tf.train.AdamOp... |
#!/usr/bin/python3
max_num = 1000
counter = 1
sum_all = 0
while counter < max_num:
if (counter % 3 == 0) or (counter % 5 == 0):
sum_all = sum_all + counter
counter += 1
print(sum_all)
|
from django.template import Context, Template
from django.template.loader import get_template
from django.shortcuts import render_to_response, redirect
from django.core.context_processors import csrf
from fire_fighter_site.views.helper import create_navlinks
from candidate.forms import PreScreenForm
def display(requ... |
import datetime
from django.db import models
from django.utils import timezone
class Students(models.Model):
Name = models.CharField(max_length=20)
Sex = models.CharField(max_length=2)
School = models.CharField(max_length=100)
Company = models.CharField(max_length=100)
Tel = models.CharField(max_le... |
"""
Solution for origins_and_order
Thoughts:
- Year could be any value. Month is 1-12. Day depends on month.
- Ambiguity could be between month/day (two values <= 12) or day/year (two values <= # of days in month)
- Corner case: If two values are equal, then they are not ambiguous (since they have the same string repre... |
#! /usr/bin/python3
import sys
lab10 = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
total = 0
total = total + int(sys.argv[1])
avg = total / count
print ('The average of the', count, 'numbers is: ' , avg )
|
import csv
from math import radians, cos, sin, asin, sqrt
from datetime import datetime
from collections import Counter
import json
import time
from pytz import timezone
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal d... |
import argparse
import networkx as nx
import random
import sys
import tqdm
from examples.page_rank import PageRankSimulation, LOG_LEVEL_PAGE_RANK_INFO
N_ITER = 15
timestep = .1
RUN_TIME = N_ITER * timestep
PARAMETERS = {
# Experimental results of good values
# |V|=400 |E|=600 : ts=1. tsf=40
# |V|=800 ... |
# A wee calculator to work out CPMs, Budgets, Impressions etc.
def workOutCPM(impressions,budget):
cpmCalc = (budget / impressions) * 1000
return cpmCalc
def workOutBudget(cpm,impressions):
budgetCalc = (impressions * cpm) / 1000
return budgetCalc
def workOutImpressions(cpm,budget):
impressionsCalc = (budget / ... |
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from PIL import Image
# Create your models here.
# class DeliveryAddress(models.Model):
# pass
class Profile(models.Model): # class hồ sơ người dúng
# ... |
from collections import defaultdict
def _items_from_list(l):
for i in range(len(l)):
yield i, l[i]
def _items_from_dict(l):
return l.items()
def choose_from_distribution(distribution, random_number):
s = 0
last_key = None
items = (
_items_from_dict if hasattr(distribution, 'ite... |
#!/usr/bin/env python3
#Answer to exercise number 2
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = []
for number in a:
if (number % 2 == 0):
b.append(number)
#b = [number for number in a if number % 2 == 0]
print(b)
|
from django.contrib import admin
from .models import *
# Register your models here.
# PERMISSAO MAXIMA DE ACESSO PODE REMOVER QUAL OBJECT DA CLASSE MODEL CAD;
# LOGIN: lsbloo
# SENHA : lsbloo6036236
admin.site.register(Pessoa)
admin.site.register(Professor)
admin.site.register(Aluno)
admin.site.register(Notas)
admi... |
import os
path = 'C:\\Users\\julia\\Logs\\'
files = os.scandir(path)
data = []
results = []
for item in files:
results.append([])
if item.is_file():
with open(path+item.name) as fp:
lines = fp.readlines()
data.append(lines)
for index, content in enumerate(data):
while len(... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@Time : 2018-11-09 21:39
@Author : jianjun.wang
@Email : alanwang6584@gmail.com
"""
import numpy as np
import cv2 as cv
img = np.zeros((320, 320, 3), np.uint8) #生成一个空灰度图像
print img.shape # 输出:(320, 320, 3)
# 起点和终点的坐标
ptStart = (60, 60)
ptEnd = (260, 260)
point_col... |
# coding: utf-8
import os
from datetime import datetime
from unittest import TestCase
from unittest.mock import MagicMock, call
from shimbase.database import Database, DatabaseObject, DatabaseInvObjError, \
AdhocKeys
from shimbase.dbimpl import DatabaseDataError, DatabaseIntegrityError
from shimbase.sqlite3imp... |
import numpy as np
import os
np.random.seed(1337)
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop
(x_train, y_train), (x_test, y_test) = mnist.load_data(os.getcwd() + '/data/mnist.npz... |
from .CSVParser import CSV
from .URLCSVParser import URLCSV
from .ArffParser import Arff
from .URLArffParser import URLARFF
|
class Date:
annee: int
mois: int
jour: int
def __init__(self, jour=1, mois=1, annee=1960):
"""
Constructeur de la classe Date
:param jour: jour de la date
:type jour: int
:param mois: mois de la date
:type mois: int
:param annee: année de la date... |
from django.urls import path, re_path
from django.views.generic import TemplateView
from .views import *
from rest_framework.schemas import get_schema_view
slash = '/?'
rest_urls = {
'cohort': 'rest/cohort/',
'trait': 'rest/trait/',
'trait_category': 'rest/trait_category/',
'performanc... |
from drawLine import ViewPort,drawLine
from drawPolygon import drawPoly
#from scanLine import scanLineUtil
import math,sys
from graphics import color_rgb,Line,Point
'''
l=[
[40,0,0],[80,0,40],[40,0,80],[0,0,40],
[40,40,0],[80,40,40],[40,40,80],[0,40,40]
]
'''
def drawAxis(win,new_view):
L1 = Lin... |
import asyncio
import contextlib
import collections
import hashlib
import json
import os
import pathlib
import re
import textwrap
from .async_helpers import safe_communicate
from .compat import makedirs
from .error import PrintableError
from .keyval import KeyVal
# git output modes
TEXT_MODE = object()
BINARY_MODE = ... |
import keras
class FitzHughNagumo(keras.layers.Layer):
def __init__(self, initializer="he_normal", **kwargs):
super(FitzHughNagumo, self).__init__()
v_init = tf.random_normal_initializer()
self.v = tf.Variable(
initial_value=v_init(shape=(input_dim, units), dtype="float32"),
... |
# coding: utf-8
# # 20 Newsgroups text classification with pre-trained word embeddings
#
# In this notebook, we'll use pre-trained [GloVe word
# embeddings](http://nlp.stanford.edu/projects/glove/) for text
# classification using TensorFlow 2.0 / Keras. This notebook is
# largely based on the blog post [Using pre-tr... |
import matplotlib.pyplot as plt
import numpy as np
from .visuals import plot_diagrams
__all__ = ["bottleneck_matching", "wasserstein_matching"]
def bottleneck_matching(I1, I2, matchidx, D, labels=["dgm1", "dgm2"], ax=None):
""" Visualize bottleneck matching between two diagrams
Parameters
===========
... |
from IPython.kernel import client
from subprocess import *
import os
import sys
import commands
import string
import atexit
import time
import socket
import types
import inspect
import casadef
import numpy as np
from math import *
from get_user import get_user
# jagonzal (CAS-4106): Properly report all the exceptions ... |
from flask_wtf import FlaskForm
from wtforms import TextField, SubmitField, StringField, Form, IntegerField, DateField
class CargarTweetForm(FlaskForm):
search = StringField("search")
maximo = IntegerField('maximo')
fecha = DateField('fecha_hasta')
submit = SubmitField('Cargar')
class ObtenerT... |
# -*-coding:utf-8-*-
import numpy as np
import freetype
import copy
import random
import cv2
font_path = '/media/cyoung/000E88CC0009670E/projectCV/chinese_image_text/' \
'img/Img2TextSequence/data_gen/fonts/Deng.ttf'
class put_chinese_text(object):
def __init__(self, ttf_path):
self._face = f... |
from cryptopals import block
if __name__ == '__main__':
test_string = 'YELLOW SUBMARINE'
print(block.pkcs7_pad(test_string.encode(), 20))
|
"""
NeuroImaging volumes visualization
==================================
Simple example to show Nifti data visualization.
"""
##############################################################################
# Fetch data
# ----------
from nilearn import datasets
# By default 2nd subject will be fetched
haxby_dataset =... |
import pandas as pd
import numpy as np
def processData():
fp_german = open('train_german.txt', 'r')
german_string = fp_german.read()
german_string = german_string.replace('\n','')
# Stringi 140'ar parçaya bölme.
germanTrainingSet = np.array([german_string[i:i + 140] for i in range(0,len(german... |
import pytest
import jax
import jax.numpy as jnp
import jax.flatten_util
import numpy as np
from functools import partial
import itertools
import tarfile
import glob
from io import BytesIO
from flax import serialization
import netket as nk
from .. import common
pytestmark = common.skipif_mpi
SEED = 111
@pytest... |
import string
import nltk
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
from nltk.corpus import stopwords
from nltk.corpus import pros_cons
from nltk.stem.lancaster import LancasterStemmer
import itertools
from nltk.collocations import BigramCollocationFinder
from nl... |
import random
def noun_pr():
with open("noun_pr.txt", encoding="utf-8") as f:
nouns_pr = f.read()
splited_nouns_pr= nouns_pr.split()
return random.choice(splited_nouns_pr)
def narech():
with open("narech.txt", encoding="utf-8") as f:
narechs = f.read()
splited_na... |
# Generated by Django 2.2.6 on 2019-10-24 10:52
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("site", "0024_sitesettings_customer_set_password_url")]
operations = [
migrations.AlterField(
model_name="sit... |
from rest_framework.parsers import JSONParser
from rest_framework import viewsets
from scapi.models.shoppingcart import shoppingcart
from scapi.serializers.shoppingcartSerializer import shoppingcartSerializer
class CartViewSet(viewsets.ModelViewSet):
queryset = shoppingcart.objects.all()
serializer_class = sho... |
#!/usr/bin/env python
from setuptools import setup
setup(
name='intercom',
version='0.0.1',
url='https://github.com/alexhanson/intercom',
license='ISC License',
python_requires='>=3.8',
install_requires=[
'click==7.1.2',
'CherryPy==18.6.0',
'Jinja2==2.11.3',
'pyt... |
"""
列表推导和生成器表达式
"""
def main():
symbols = '%^&$*('
symbol = 'time'
codes = [ord(symbol) for symbol in symbols]
print(codes)
# 在 python3 中 推导式不再会有变量泄漏的问题
print(symbol) # time
# 推导式与filter,map比较
print([ord(symbol) for symbol in symbols if ord(symbol) > 40])
print(list(filter(la... |
from openpyxl import Workbook
from openpyxl.drawing.image import Image
#please do install Pillow module
#pip install Pillow to use images
book = Workbook()
sheet = book.active
img = Image("xlf/apple.jpg")
sheet['A1'] = 'This is apple'
sheet.add_image(img, 'B2')
book.save("xlf/9.xlsx") |
import math
def add(a,b):
'this adds 2 num'
print("sum of a and b", a+b)
def diff(a,b):
'diff btn 2 num'
print("diff of 2 num", a-b)
def mul(a,b):
'multiples a with b'
print("Mul of a and b", a*b)
def div(a,b):
'divides 2 nos'
if b==0:
print("enter a nonzero num")
else:
print("div a/b is "... |
# coding=UTF-8
'''
Created on 2017
@author: XYJ
'''
import jieba
import os
import random
import math
def TextProcessing(floder_path,train_size =0.8):
floder_list = os.listdir(floder_path)
train_data_list = []
train_class_list = []
test_data_list = []
test_class_list = []
for floder in floder... |
# -*- coding: utf-8 -*-
import unittest
import os
import swc2vtk
class TestVtkGenerator(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def setUp(self):
self.swc_file_path = os.path.join('tests', 'simple.swc')
s... |
"""Utility functions for POST /tasks/{id}:cancel endpoint."""
import logging
from requests import HTTPError
from typing import Dict
from celery import current_app
from connexion.exceptions import Forbidden
import tes
from pro_tes.config.config_parser import get_conf
from pro_tes.errors.errors import TaskNotFound
fro... |
import numpy as np
import matplotlib.pyplot as plt
from dna_diags import *
def get_time_from_tempfile(ikx,iky):
cikx=str(int(ikx))
if len(cikx)==1:
cikx='0'+cikx
elif len(cikx) > 2:
print cikx
print "Error in get_time_from_temp"
stop
ciky=str(int(iky))
if len(ci... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 13:56:15 2020
@author: damla
"""
import socket
import threading
import time
clientWords = ["Selam", "Naber", "Hava", "Haber", "Kapan"]
serverAnswers = ["Selam", "Iyiyim, sagol", "Yagmurlu", "Korona", "Gule gule"]
print_lock=threading.Lock()
... |
from django.shortcuts import render, redirect, get_object_or_404
from .models import Item, SellerAccount
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from .forms import ItemForm
from django.contrib.auth.decorators import login_req... |
import pytest
from selenium import webdriver
@pytest.fixture
def browser():
driver = webdriver.Chrome('/anaconda3/lib/python3.7/selenium/webdriver/chrome/chromedriver')
driver.set_page_load_timeout(20)
driver.get("http://www.google.com")
driver.maximize_window()
driver.implicitly_wait(20)
driv... |
"""empty message
Revision ID: 2b54b23dec03
Revises: de8d1488ff93
Create Date: 2019-09-04 00:11:21.771179
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2b54b23dec03'
down_revision = 'de8d1488ff93'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import logging
import requests
import simplejson
import json
from flask import Flask, escape, request
from flask import render_template
from flask import jsonify
app = Flask(__name__)
@app.route('/')
def hello(name=None):
#JSON data goes here, so long as it's kept between the def function and fuchsia return, wh... |
# Generated by Django 3.1.2 on 2020-10-28 14:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shared_models', '0018_auto_20201028_1105'),
]
operations = [
migrations.AlterField(
model_name=... |
import numpy as np
import pylab
feature_lengths = [3,4,5,6,7,8,10,12,14]
ngram_crude_f1 = [0.94554,0.95722,0.95337,0.96534,0.95346,0.93217,0.93405,0.90452,0.88380]
ngram_crude_p = [0.94303,0.94453,0.93904,0.95330,0.94699,0.91840,0.92733,0.88707,0.89579]
ngram_crude_re = [0.94908,0.97126,0.96997,0.97836,0.96160,0.9493... |
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns=[
path('',views.Blog_list.as_view(),name="blog_list"),
path('<int:id>',views.Blog_detail.as_view(),name="blog_detail"),
]
|
from flask import Flask, render_template, request
import json
from math import ceil
import imp
import os
from correlator import correlator
from fault_detector import fault_detector
# Create Flask app
app = Flask(__name__)
# Later we will want to pull this from a file, or autogenerate,
# but this prevents arbitrary f... |
import requests
import logging
import sys
import opentracing
from flask import Flask, jsonify, request
from jaeger_client import Config
from flask_opentracing import FlaskTracer
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format='%(asctime)s [%(levelname)s] - %(name)s %(threadName)s : %(mes... |
from source.pages.urls import UrlConstants
import re
class UserDecklists(UrlConstants):
TAPPEDOUT_DECKNAME_CLASSES = "name deck-wide-header"
TAPPEDOUT_PAGINATION = "pagination"
def __init__(self, browser):
self.browser = browser
def navigate_to_users_decklists(self, username):
self.... |
# -*- coding: utf-8 -*-
"""
March 2016
author: teezeit
This script optimizes parameters for xgboost using greeedy gridsearch + crossvalidation
"""
# Imports
print("Test version -Changes made on 12052021")
print("Test version -Changes made on 12052021-Changes_02")
import numpy as np
import xgboost as xgb
import tuning_x... |
items = input("Enter the items separated by spaces (must be even number): ").strip().split()
i = 0
if (len(items))%2 == 1:
input("You need to enter an even amount of numbers")
exit(0)
elif (len(items))<4:
input("Not enough data")
exit(0)
else:
j = int((len(items))/2)
... |
def chooseFromList(message, choices, nullChoice=None, debug = True):
print(message)
if nullChoice is not None:
print("Enter:\t{}".format(nullChoice))
for i, choice in enumerate(choices):
print("{}:\t{}".format(i, choice))
while True:
try:
choice = input("-> ")
if nullChoice is not None and choice == "":... |
# Generated by Django 3.0.8 on 2020-07-08 09:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booking', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id',... |
# https://www.reddit.com/r/dailyprogrammer/comments/67q3s6/20170426_challenge_312_intermediate_next_largest/
from itertools import permutations as ps
def get_next(num):
perms = sorted(set(map(lambda x: int(''.join(x)), ps(str(num)))))
return perms[perms.index(num) + 1]
def main():
inp = [
1234,... |
'''Jason A Smith'''
fract = ''
count = 1
while len(fract) < 1000000:
fract += str(count)
count += 1
print(int(fract[1 - 1]) * int(fract[10 - 1]) * int(fract[100 - 1]) * int(fract[1000 - 1]) * int(fract[10000 - 1]) * int(fract[100000 - 1]) * int(fract[1000000 - 1]))
|
# Generated by Django 2.2.dev20181016201044 on 2018-10-29 04:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20181027_1845'),
]
operations = [
migrations.AddField(
model_name='user',
name='ema... |
if __name__ == '__main__':
with open(r"F:\u1.txt","w+") as f:
mk=str([i for i in range(1,20)])
f.writelines(mk)
ml=f.readline()
print(mk)
print(ml) |
from hashlib import sha256
from time import time
from urllib.parse import urlparse
import requests
from flask import Flask, jsonify, request
import random
#Declaration of the Blockchain
class Blockchain(object):
def __init__(self):
self.chain= []
self.vote_info = {}
self.neighbours = [] #Se... |
#import tensorflow as tf
#from tensorflow import keras
#from tensorflow.keras import layers
import numpy as np
import tensorflow as tf
import argparse
import os
import numpy as np
import json
import smdebug.tensorflow as smd
def model():
hook = smd.KerasHook.create_from_json_file()
optimizer=tf.... |
#180119 MKT
#build gffutils database
import gffutils
if snakemake.params['gtf_format'] == 'ensembl':
db = gffutils.create_db(snakemake.input['gtf_file'], snakemake.output['db_file'], disable_infer_transcripts = True, disable_infer_genes = True)
#flybase gtf file needs id_spec in order to have mRNAs as ids in the... |
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import Beaut... |
# Generated by Django 3.2 on 2021-04-19 23:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Datapoint',
fi... |
import json
from tqdm import tqdm
from typing import List
from collections import namedtuple
import torch
from torch.nn.utils.rnn import pad_sequence
def load_vocab(path) -> namedtuple:
return_dict = json.load(open(path))
# for idx2token, idx2chartoken, have to change keys from strings to ints
# https:... |
# "Make a program in Python, that solve quadratic equations
# A.x2 + B.x1 + C = 0
# Where A, B, C is real numbers (could be negative), find X. "
import math
list_param = []
i = 1
while i <= 3:
print('Type your number', i, ':')
value = input()
if i == 1 and float(value) == 0:
print('Pleas... |
"""myblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
from pyspark import SparkConf, SparkContext, RDD
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
import math
conf = SparkConf().setAppName("Recommender").set("spark.executor.memory", "7g")
conf = SparkConf().setAppName("Recommender").set("spark.storage.memoryFraction", "0.1")
sc = SparkC... |
import os
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
import requests
import cairosvg
import time
import time
import shutil
import logging
from config import Ink_HEIGHT,Ink_WIDTH
picdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'pic')
font16 = ImageFont.truetype(os.path.join(p... |
from server import app
# import os
import unittest
# import tempfile
class BaseTestCase(unittest.TestCase):
# def setUp(self):
# # server.app.config['TESTING'] = True
# # self.app = server.app.test_client()
# pass
# def tearDown(self):
# pass
def test_index(self):
... |
from googleplaces import GooglePlaces, types, lang
from pprint import pprint
import sys
import utils
YOUR_API_KEY = "AIzaSyCQENSbRFfd9_lGuqoXf2icRgtSvED-WHI"
RADIUS = 10000 # in meters
google_places = GooglePlaces(YOUR_API_KEY)
def get_gplaces_results(place, city, state):
# You may prefer to use the nearby_sear... |
# -*- coding: utf-8 -*-
#########################################################
#
# Alejandro German
#
# https://github.com/seralexger/clothing-detection-dataset
#
#########################################################
from PIL import Image
import json
import glob
import random
import matplotlib.pyplot as plt... |
"""
Asynchronous Learning Engine (ALE)
Supports PWS standard desktop (studio)
Mentor Queues
Load Balancing / Air Traffic Control
Courses / Flights
A mentor queue is a worker queue with
tasks pending, in process, complete.
The many subclasses of Task are only hinted
at in this overview.
Example Tasks (Transactions ar... |
import argparse
from string import Template
import subprocess
template_delete_user = Template("""
dn: uid=${ACCOUNT},ou=people,dc=tanaka,dc=lab
changetype: delete
""")
template_delete_from_group = Template("""
dn: cn=${ACCOUNT},ou=groups,dc=tanaka,dc=lab
changetype: delete
""")
def main(user):
# delete user
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2022 shmilee
'''
Extend the matplotlib Axes3D class.
ref
---
1. https://gist.github.com/WetHat/1d6cd0f7309535311a539b42cccca89c
2. mpl_toolkits.mplot3d.art3d.Text3D
'''
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
from matplotlib.artis... |
import re
import tkinter as tk
import tkinter.filedialog
import tkinter.ttk as ttk
from pathlib import Path
from tkinter import font
from tkinter.messagebox import showerror, showinfo
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.backends.backend_tkagg import FigureC... |
import segyio
import pandas as pd
import numpy as np
from tqdm import tqdm_notebook as tqdm
from obspy.io.segy.core import _read_segy
SEGYIO_HEADER_ITEMS = {
'EnergySourcePoint': "SPID",
'SourceX': "SRCX",
'SourceY': ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.