text stringlengths 38 1.54M |
|---|
#! /usr/bin/python
import sys
f = open('July20/random_med_mote6.log','r')
g = open('July20/random_med_mote6.out','w')
lines = f.readlines()
for line in lines:
line = line.strip()
if line != '':
nums = line.split()
output = ''
source = int(nums[8],16)
if source == 0:
output = output + "Infra... |
# space scramble
# ludwig game jam 2021
# written and designed by capnsquishy
import os
import pygame
from pygame import Rect
from pygame.math import Vector2
from views import title_screen, resource_screen
class Interface:
def __init__(self):
pygame.init()
self.cell_size = Vector2(64, 64)
... |
from abc import ABC, abstractmethod
class TurnsManager(ABC):
@abstractmethod
def add_unit(self, unit):
raise NotImplemented
@abstractmethod
def remove_unit(self, unit):
raise NotImplemented
@abstractmethod
def get_next(self):
raise NotImplemented
|
from sys import stdin,stdout
def dsum(n):
if n//10==0:return n*(n+1)//2
count,temp=0,n
while not temp//10==0:count,temp=count+1,temp//10
p=10**count
mod=n%p
return (dsum(mod)+temp*(mod+1)+p*temp*(temp-1)//2+(p*count*temp*45//10))
def main():
out=""
a,b=map(int,stdin.readline(... |
from django.views.generic import ListView
from models import TriggerLog
class CaseFirstBookChangesView(ListView):
template_name = "triggerlog/case_first_book_changes.html"
paginate_by = 12
table = 'bookcaseidinfo'
context_object_name = 'logs'
def get_queryset(self):
logs = TriggerLog.obje... |
import boto3
connection = boto3.client(
'emr',
aws_access_key_id="ASIAWAQG777R7GVHCPFI",
aws_secret_access_key = "******",
aws_session_token = "*******"
)
lst = connection.list_clusters(ClusterStates=['TERMINATED'])
print(lst)
|
import random
def main():
resp = input("Would you like to play a game?[y/n]")
if resp.lower() == 'y':
play_game()
def play_game():
number = random.randint(1, 100)
guess = -1
while guess != number:
guess = int(input("Pick a number between 1 - 100. "))
if guess > number:
... |
import matplotlib
import matplotlib.pyplot as pyplot
import csv
import sys
import os
from operator import itemgetter
def createPlot(xList, xLabel, yLabel, title):
pyplot.hist(xList, bins=50)
pyplot.title(title)
pyplot.xlabel(xLabel)
pyplot.ylabel(yLabel)
def sortByNumberOfLines(fileList):
l = []
... |
#!/usr/bin/python3
# for pruning parabank 2, takes only the first unique target line, fifthing the data
# optionally take the most different one
import sys
def dice(sent1, sent2):
set1 = set(sent1.split())
set2 = set(sent2.split())
return 2 * len(set1.intersection(set2)) / (len(set1) + len(set2))
def ma... |
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import spsolve
import matplotlib.pyplot as plt
# --------------------------------------------------------------------
# basic parameters
dt = 0.2*60*60 # delta t [s]
tn = 10000 # number of time steps
t = np.arange(0, dt*tn, dt)
L = 5.0e6 # length... |
def check_mispaired(input,output):
"""
Returns sam file only with reads mapped to chrM.
Rather than randomly selecting the origin of multimapped reads,
the program favours two paired reads to derive from
one chromosome, chrM.
"""
with open(input) as f, open(output, "w") as g:
lines = f.readlines()
M = "chr... |
# coding: utf-8
"""Wikipediaコーパスを解凍して記事のみを抽出し単一ファイルに出力する"""
__author__ = "Aso Taisei"
__date__ = "12 Mar 2020"
import os
import sys
import yaml
def dump():
"""Wikipediaコーパスを解凍して記事のみを抽出し単一ファイルに出力する"""
# ファイルパス
wiki_extractor_path = "./script/WikiExtractor.py"
wiki_xml_path = "./data/jawi... |
# noqa: D100
import logging
from typing import List, Optional, Union
import hail as hl
logging.basicConfig(
format="%(asctime)s (%(name)s %(lineno)s): %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def get_reference_ht(
ref: hl.Referen... |
# Generated by Django 3.0.8 on 2020-07-20 15:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('NetflixApp', '0002_auto_20200719_1518'),
]
operations = [
migrations.DeleteModel(
name='Rating',
),
migrations.DeleteMod... |
import os
import cv2
import numpy as np
from PIL import Image
import pickle
from pathlib import Path
import string
from sklearn.model_selection import train_test_split
from keras.layers import Dense, LSTM, Reshape, BatchNormalization, Input, Conv2D, MaxPool2D, Lambda, Bidirectional
import keras.backend as K
from keras.... |
# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
class Users(models.Model):
_inherit = 'res.users'
menu_ids = fields.Many2many('ir.ui.menu', 'user_menu_rel', 'uid', 'menu_id', string='Menu To Hide', help='Select Menus To Hide From This User')
report_ids = fields.Many2many('ir.actions.repor... |
#Import module
import pygame, sys, random
from pygame.math import Vector2 #mempermudah supaya saat manggil g nulis pake "pygame.math.Vector2" terus2an
#Membuat kelas FARMER
class FARMER:
def __init__(self): #menginisiasi
self.randomize()
def draw_farmer(self):
#membuat rect
... |
from nanpy import (ArduinoApi, SerialManager)
import time
try:
connection = SerialManager()
a = ArduinoApi(connection = connection)
except:
print("Failed to connect to Arduino.")
trigger = 7
echo = 8
a.pinMode(trigger, a.OUTPUT)
a.pinMode(echo, a.INPUT)
a.digitalWrite(trigger, a.LOW)
print("Waiting for sensor t... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Dr. Ralf Schlatterbeck All rights reserved
# Reichergasse 131, A-3411 Weidling, Austria. rsc@runtux.com
# #*** <License> ************************************************************#
# This module is part of the package FFM.
#
# This module is licensed under the terms of th... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#path('', views.home, name='takatarecovery-home'),
path('', views.home, name='takatarecovery-home'),
path('makemodel/', views.makeModelCheck, name='takatarecovery-ma... |
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
RETRIES_STATUS_CODES = [429, 500, 502, 503, 504] # not used rn
"""
Used self-retry logic. but check this package:: Read about requests.retries here: [doc](https://findwork.dev/blog/advanc... |
import PyQt5.QtWidgets as QtWidgets
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import cfg.game as game_cfg
import lib.view_lib as view_lib
import view.h_list_view as h_list_view
import view.h_row_view as h_row_view
# 轨迹默认配置视图
class TrajectoryChangeView(h_list_view.HListLabel):
select_trajectory_id ... |
'''
For given integer x, print 'True' if it is positive, print 'False' if it is negative and print 'Zero' if it is zero
'''
a = int(input("Enter any number"))
if a==0:
print ("It is Zero")
elif a>=0:
print ("It is positive")
else:
print ("It is negative") |
#!/usr/bin/env python2.6
"""
The primary startup script for winnie. Initializes
the IRC connection
"""
from winnie.protocols.irc import connection as IRC
from winnie.web import server as HTTP
def main():
try:
irc = IRC.Connection()
irc.start()
except KeyboardInterrupt, e:
irc.runnin... |
# -*- coding: utf-8 -*-
import yaml
import os
class StreamingConf:
def __init__(self, conf_file):
home_dir = os.environ['MYSTR_HOME']
f = open(home_dir + '/conf/' + conf_file, 'r')
self.conf = yaml.load(f)
f.close()
#def get_job_manager(self):
# return self.conf['... |
"""
Ad-hoc csv report generation script.
"""
import os, sys
import argparse
from datetime import datetime
import pandas as pd
BASE_DIR = os.path.dirname(__file__)
REPORT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', '..', '..', '_reports'))
sys.path.append(os.path.join(BASE_DIR, '..', '..'))
import db
rpt_c... |
import matplotlib.pyplot as plt
class Imageprocessor:
def load(path):
img = plt.imread(path)
print ("Loading image of dimensions " + str(len(img[0])) + ' x ' + str(len(img[1])))
return img
def display(path):
plt.imshow(path)
plt.show
arr = Imageprocessor.load("4... |
import numpy as np
import random
homeNum = 1 # 车场个数
carNum = 3 # 车型个数
clientNum = 5 # 客户个数
garbageNum = 4 # 垃圾种类数
chargerNum = 3 # 充电桩个数
# 每个客户的垃圾重量规格矩阵
clientWeightMatrix = np.zeros(shape=(clientNum, garbageNum))
# 每个客户的时间窗
clientTimeWindow = np.zeros(shape=(clientNum, 2))
# 每个客户需要的服务时间
clientServeTime = np.zero... |
from wtforms import Form, SelectField, SubmitField, validators, ValidationError, DateField
from wtforms_components import DateTimeField, DateRange
from datetime import datetime
cities = [('Vancouver', 'Vancouver'), ('Portland', 'Portland'), ('San Francisco', 'San Francisco'),
('Seattle', 'Seattle'), ('Los Angeles', ... |
#!/usr/bin/env python3
import sys
import os
import shutil
palPath = r"{{palPath}}"
def printUsage():
print("Usage: pal [-h] command\n")
print("Quickly create new pal projects.\n")
print("Available commands:")
print(" new Create a new pal project in the current directory.")
print(" help ... |
#import the random
#import random
#winning_number= random.randint(0,10)
#print(winning_number)
#num_guesses = 5
#user_won = False
#while num_guesses != 0 and user_won == False:
# user_guess = int(input("Enter your guess: "))
# if user_guess == winning_number:
# print("Hey, you won!")
# user_won = True
# else:
# ... |
"""
Test configuration loading
@author aevans
"""
import os
from nlp_server.config import load_config
def test_load_config():
"""
Test loading a configuration
"""
current_dir = os.path.curdir
test_path = os.path.sep.join([current_dir, 'data', 'test_config.json'])
cfg = load_config.load_conf... |
#!/usr/bin/env phthon
import MySQLdb, os, commands,re, time
def get_db_con(dbname="resource_pool"):
DB_HOST="localhost"
DB_USER="root"
DB_PASS="virtcompute"
try:
conn=MySQLdb.connect(host=DB_HOST,user=DB_USER,passwd=DB_PASS,db=dbname)
except MySQLdb.Error,e:
print "Mysql Error %d: %... |
from collections import defaultdict
import string
S = input()
letters = defaultdict(lambda: False)
for s in S:
letters[s] = True
ans = 'None'
for l in string.ascii_lowercase:
if letters[l] == False:
ans = l
break
print(ans)
|
from tkinter import *
from tkinter.ttk import Combobox, Scrollbar
import tkinter.ttk as ttk
import datetime
import mysql.connector as mysql
class GymManagementSystem:
def __init__(self,root):
self.root=root
self.root.title("GYM MANAGEMENT PROJECT")
self.root.geometry("1300x660+... |
print("**********LATIHAN1*******")
print("program menghitung laba perusahan dengan modal awal 100juta")
print("")
print("Note")
print("Bulan pertama dan ke 2 = 0%")
print("pada bulan ke 3 = 1%")
print("pada bulan ke 5 = 5%")
print("pada bulan ke 8 = 2%")
print("")
a=1000000
for x in range(1,9):
if(x>1 ... |
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = None
def touch(x, y):
global d
device.touch(x, y, "DOWN_AND_UP")
def fight():
global d
invoke_hero()
MonkeyRunner.sleep(0.5)
call_all_skill()
MonkeyRunner.sleep(0.5) ... |
import turtle
turtle.pensize(3)
turtle.penup()
turtle.goto(-200, -50)
turtle.pendown()
turtle.circle(40, steps=3)
turtle.penup()
turtle.goto(-100, -50)
turtle.pendown()
turtle.circle(40, steps=4)
turtle.penup()
turtle.goto(0, -50)
turtle.pendown()
turtle.circle(40, steps=5)
turtle.penup()
turtle.... |
# numpyライブラリをインポート
import numpy as np
# 整数型の配列を用意
arr_int32 = np.array([100, 200, 300, 400, 500], dtype=np.int32)
print(arr_int32)
# 浮動小数点型の配列を用意
arr_float = np.array([0.1, 0.2, 0.3, 0.4, 0.5], dtype=np.float64)
print(arr_float)
# 配列通しの計算を + で表現できます。
arr_sum = arr_int32 + arr_float
print(arr_sum) |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from typing import Optional
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Cloud Map"
prefix = "servicediscovery"
class Action(BaseAction):
def __init__(self, a... |
# Create a list where each element is an individual base of DNA.
# Make the array 15 bases long.
bases = ['A', 'T', 'T', 'C', 'G', 'G', 'T', 'C', 'A', 'T', 'G', 'C', 'T', 'A', 'A']
# Print the length of the list
print("DNA sequence length:", len(bases))
# Create a for loop to output every base of the sequence on a ne... |
from abc import ABC, abstractmethod
import traceback
class ClientActionException(Exception):
def __init__(self, message = ""):
self.message = message
super().__init__(self.message)
class ServerActionException(Exception):
def __init__(self, message = ""):
self.message = message
... |
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# 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... |
from array import array
t = int(input())
for i in range(t):
n, r = tuple(map(int, input().split()))
l = list(map(int, input().split()))
# print(*(l[n-r:]+l[:n-r]))
x = r % n #mostimp concept
print(*(l[n-x:]+l[:n-x]))
def left_rotation(arr, d, n):
for i in range(d):
temp = ... |
class selectCalData:
def selectCalData(self):
calAll = []
calAll.append([])
calAll[0] = ['월','일정','이번달','고사','여름','겨울','졸시','휴학']
calAll.append([])
calAll[1] = ['1학기','2학기']
calAll.append([])
calAll[2] = ['전기','후기','중간','성적','동계','하계','수강','졸업','방학']
... |
import os, time
import struct
from string import Template
import numpy as np
from astropy.io import fits
import astropy.units as u
import astropy.constants as ct
from hyperion.model import ModelOutput
from scipy.interpolate import griddata, interp2d
from myutils.logger import get_logger
from myutils.math import rebin_... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('show/new', views.add_new_show),
path('show/create', views.create_show),
path('show/<int:id>', views.display_show),
path('show/<int:id>/edit', views.edit_show),
path('show/<int:id>/update', views.update... |
import modules as mod # from other file
# All of the following modules are from STD
import random as rand
import math as math
import datetime as dt
import calendar as calendar
import os
courses = ['History', 'Math', 'Physics', 'Eecs', 'Art']
index = mod.find_index(courses, 'Eecs')
print(index)
random_course = ran... |
def odd_even():
for i in range(0,2001):
if (i % 2 == 1):
print 'number is '+ str(i)+". This is an odd number"
if (i % 2 == 0):
print 'number is '+ str(i)+". This is an even number"
odd_even() |
import _pickle as cPickle
from YCgplearn.genetic import SymbolicRegressor
from YCgplearn.fitness import make_fitness
import pydotplus
from ycquant.yc_interpreter import *
import os
# from ctypes import *
from ycquant.yc_backtest import *
import numpy as np
class YCGP:
"""
Gentic Programming Algorithm base... |
from djikstra import *
import pylab as pl
N =100
varx = N*2
vary =N*2
resolution = 1
g = make_grid(N, N)
data = []
for a in range(1,100,resolution):
data.append([])
for (i,j) in g:
g[ (i,j) ] = gaussian(i,j, dy=-N/2, A=a)
for path_constant in range(1,100,resolution):
print a,path_constan... |
import pygame, sys, math
from pygame.locals import *
from viewpoint import *
from smap import *
from imagedata import *
pygame.init()
(s_w, s_h) = pygame.display.list_modes()[0]
s_dimen = (s_w, s_h)
FPS = 40
clock = pygame.time.Clock()
screen = pygame.display.set_mode(s_dimen)
pygame.display.toggle_fullscreen()
f... |
"""
Zawiera algorytm minimax.
"""
import copy
import math
import random
import properties
def alphabeta(current_board, depth):
"""
Zwraca ruch wykonany przez przeciwnika.
:param current_board: Aktualna plansza.
:param depth: Głębokość algorytmu.
:return: Ruch wykonany przez przeciwnika.
"""
... |
from copy import deepcopy
import random
def find_path(scanner, memory):
DIR_reverse = {"N": 'S', "S": 'N', "W": 'E', "E": 'W'}
DIR = {"N": (-1, 0), "S": (1, 0), "W": (0, -1), "E": (0, 1)}
memory_binary = bin(memory)[2:]
memory_binary = '0'*(100-len(memory_binary)) + memory_binary
memory_list = [[j ... |
#!/usr/bin/python3
import sys
import os
import shutil
if len(sys.argv) != 3:
print("Zla ilosc paramaterow")
raise SystemExit()
dirDeleteFrom = sys.qrgv[1]
dirCopyTo = sys.argv[2]
for file in os.listdir(dirDeleteFrom):
if os.path.isdir(dirDeleteFrom + "/" + file):
for file2 in os.listdir(dirDe... |
#!/bin/python3
import sys
def nim(heaps, misere=False):
if heaps==[0,1]: return (1,1)
X = reduce(lambda x,y: x^y, heaps)#gives the xor of all the elements of the list
if X == 0: # Will lose unless all non-empty heaps have size one
# if max(heaps) > 1:
# print "You will lose :(... |
from preprocess_utilities import *
raw_m = mne.io.read_raw_bdf(askopenfilename(title="Please choose "),preload=True)
raw_m.drop_channels(["A24", "C31", "D6", "D30"]) # bridged/noisy channels we choose to remove ##n
raw_m.drop_channels(['Ana' + str(i) for i in range(1, 9)])
raw_m.load_data().filter(l_freq=1., h_freq=N... |
'''
1. Write a program that asks the user to enter a word that contains the letter a. The program should then print the
following two lines: On the first line should be the part of the string up to and including the first a, and on the
second line should be the rest of the string.
Sample output is shown below:
... |
# 迭代器练习
it = iter([1,2,3,4,5])
while True:
try:
x = next(it)
print(x)
except StopIteration:
break
|
from django import template
from capweb.helpers import reverse
from django.urls.resolvers import NoReverseMatch
register = template.Library()
@register.simple_tag()
def process_link(link, *args, **kwargs):
"""
:param link: Either a link or a route
:return: Either the original link, or the link made from... |
from pygame.sprite import Group
from Enemy import *
from Player import *
from Projectile import ProjectileEnemy
from plateforme import Plateforme
from Move import *
class GameState:
def __init__(self):
self.player = Player(20, self) # On a un personnage
self.enemy = Enemy(700) # Un ennemi
... |
from math import tanh
from sqlite3 import dbapi2 as sqlite
def dtanh(y):
return 1.0-y*y
class searchnet:
def __init__(self,dbname):
self.con = sqlite.connect(dbname)
def __del__(self):
self.con.close()
def maketables(self):
self.con.execute('create table hidd... |
# -*- coding: utf-8 -*-
from pyramid.response import Response
from pyramid.view import view_config
import model
import colander
import deform
from colanderalchemy import SQLAlchemySchemaNode
from deform import Form, ValidationFailure
from pyramid.renderers import render_to_response
from pyramid.renderers import get_re... |
from stack import Stack
import time
p='{}{{{}}{{{{}}}}}'
s=Stack()
for item in p:
if item=="{" :
if s.peek()!=item and not s.is_empty():
s.pop()
elif s.peek()==item or s.is_empty():
s.push(item)
print(s.stack())
elif item=="}":
if s.is_empty() or s.p... |
print("hola alumnos")
print("hola mundo") ; print("adios bbys")
#para ayudarme
nombre = "mi nombre es dubian"
nombre
nombre ="mi nombre es \
dubian"
nombre
5+6
10%3
10**3
9//2
hola ="""esto es u mensaje
con tres saltos
de linea """
print(hola)
n1=2
n2=4
if n1<n2:
print("el numero 2 es mayor")
def mensaje():
... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
number=20 # which number in fibonacci list do you want?(take the 20th as an example)
fibo=[1,1] #set up a basic list
for i in range(2,1000): #set up a cycle
a=fibo[i-1]+fibo[i-2] #get the fibonacci list
fibo.append(a) #add the new number into the list
print(fib... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os,sys
import traceback
import re
from bs4 import BeautifulSoup
from openpyxl.reader.excel import load_workbook
from openpyxl import Workbook
from openpyxl.cell import get_column_letter
from openpyxl.styles import colors, Style, PatternFill, Border, Side, Alignment,... |
# 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 json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EFXPaths.ui'
#
# Created by: PyQt5 UI code generator 5.7.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("... |
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SITE_ID = 1
DEBUG = True
TEMPLATE_DEBUG=DEBUG
ALLOWED_HOSTS = ['']
ROOT_URLCONF = 'HelpingHandServer.urls'
STATIC_URL = '/static/'
WSGI_APPLICATION = 'HelpingHandServer.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILE_DIRS = (... |
# coding=utf-8
import discord
import json
import random
from discord.ext import commands
# Store the clues card info
class Card:
"""
This class is only for data generation
Args:
name_en,
name_tw,
url
"""
def __init__(self, name_en, name_t... |
from django.contrib.auth.models import User
from django_extensions.db.models import TimeStampedModel
from django.db import models
class Store(TimeStampedModel):
owner = models.ForeignKey(User)
name = models.CharField(max_length=50)
code = models.CharField(max_length=20, unique=True)
address_line_1 = m... |
from django.contrib import admin
from django.conf.urls.defaults import *
from models import Sequence, TestStep, StepTemplate
class TestStepInline(admin.TabularInline):
model = Sequence.tests.through
class SequenceAdmin(admin.ModelAdmin):
inlines = [
TestStepInline,
]
exclude = ('tests',)
adm... |
import numpy as np
import math
from scipy import optimize as op
import matplotlib.pyplot as plt
class NonlinearTimeVaryingMPC:
def __init__(self):
self.Nx=3 #状态量个数
self.Np=15 #预测时域
self.Nc=2 #控制量个数
self.L=1 #轴距
self.Q=10*np.eye(self.Np+1)
self... |
"""
@author : macab (macab@debian)
@file : assert
@created : Sunday Mar 17, 2019 00:28:58 IST
"""
'''
Python provides the assert statement to check if a given logical expression is true or false. Program execution proceeds
only if the expression is true and raises the AssertionError when it is false. The ... |
# Chapter 5 Exercise 4
# Python 3 version
import os
start_time = 0
LOOP_COUNT = 200
words = []
words_dict = {}
########################################################
# TIMER FUNCTIONS
def start_timer():
global start_time
(utime, stime) = os.times()[0:2]
start_time = utime+stime
def end_timer(txt):
... |
import numpy as np
import matplotlib.pyplot as plt
def Plotter():
Y1 = np.loadtxt("WICC_2_yValues_QL_5.txt")
Y1 = Y1[81:]
array_y = []
gap = len(Y1) / 91
rewardsForEveryHundred = np.split(np.array(Y1), len(Y1) / gap)
for r in rewardsForEveryHundred:
array_y.append(sum(r / gap))
Y1... |
from pysnooper import snoop
class Solution:
"""
s = '226'
set[0] = 2
set[1] = [[2,2],[22]]
set[2] = [[2,26],[22,6],[2,2,6]]
"""
@snoop()
def numDecodings(self, s: str) -> int:
if not s or s.startswith('0'): return 0
dp = [0] * len(s)
dp[0] = 1
for i in ra... |
from .account_api import route as accounts_router
from app.commons.common_util import TypedAPIRouter
accounts_router = TypedAPIRouter(router=accounts_router, prefix='/v1', tags=['登录/校验相关 API'])
|
#!/usr/bin/python
from collections import defaultdict
def get_input(filename):
data = []
with open(filename) as fp:
for line in fp:
if line.strip():
start, end = line.split('->')
x1, y1 = start.split(',')
x2, y2 = end.split(',')
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import shopApp.models
class Migration(migrations.Migration):
dependencies = [
('shopApp', '0027_auto_20160212_1426'),
]
operations = [
migrations.AlterField(
model_name='... |
from flask import render_template, request, redirect, url_for, session
from app import userUI
from management import managerUI
from app.tools import validate
from app.tools.dbTools import DataBaseManager
from app.tools.hashTools import Hash
@userUI.route('/newuser')
@managerUI.route('/newuser')
def create_user_landin... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# license removed for brevity
import rospy
from geometry_msgs.msg import Twist
import random
def flowfield_generator():
# ROS节点初始化
rospy.init_node('flowfield_generator', anonymous=False)
#创建一个Publisher,发布名为/person_info的topic,消息类型为learning_topic::Person,队列... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 02:35:49 2020
@author: Asad PC
"""
##through vscode 2
from pandas_datareader import data
#from pandas_datareader.utils import RemoteDataError
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime
START_DATE = '2015-01-01... |
from cx_Freeze import setup, Executable
base = None
includefiles = [
('database/server_schema.sql','database/server_schema.sql'),
('config/magicked_admin.conf.example','magicked_admin.conf'),
('config/server_one.init.example','server_one.init'),
('config/server_one.motd.example','server_one.motd')
]
... |
from downloader import download
download(2017, 9)
with open('aoc2017_9input.txt') as inputfile:
data = inputfile.read()
print(data)
score = 0
level = 0
skip = False
garbage = False
remove = 0
for c in data.strip():
if skip:
skip = False
elif c == '!':
skip = True
elif c == '>':
... |
# LP written by GAMS Convert at 12/13/18 10:24:46
#
# Equation counts
# Total E G L N X C B
# 52 27 9 16 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-06-08 14:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('disturbance', '0071_temporaryuseapiarysite_selected'),
... |
def solve(n):
ch=str(n) #création d'une chaine de caractères composée du nombre
b=0 #initialisation de la variable
for k in ch: #On parcourt chaque élément de la chaine
b+=int(k) #On convertit chaque élément en entier et on le somme à b
return(b) #La fonction renvoie la somme
def so... |
#!/usr/bin/env python
#
# Created by: Alex Leach, November 2012
#
import numpy as np
from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal, \
assert_array_almost_equal_nulp
from scipy.linalg.expokit import expm
#from scipy.linalg.expokit import dgchbv, dgexpv, dgpadm, dgphiv, dmexpv, d... |
#!/usr/bin/env python3
from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests
# set up bitrequest client for BitTransfer requests
wallet = Wallet()
requests = BitTransferRequests(wallet)
# server address
server_url = 'http://localhost:5000/'
def buy_fortune():
url = server_url+'buy?payo... |
# ***********************************************************************
# Import libraries
# ***********************************************************************
import sys
import os
import time
import datetime
import numpy as np
import pandas as pd
sys.path.append( os.path.abspath( '../../opti-trade' ) )
from ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-03 19:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pedido', '0002_auto_20180203_0503'),
]
operations = [
migrations.AddField(
... |
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
"""Hash Table
Running time: O(n) where is the number of files.
"""
from collections import defaultdict
d = defaultdict(list)
for path in paths:
parts = path.split(' ')
... |
def consumo(distancia, quantidade_litros):
if distancia / quantidade_litros < 8:
return print('Venda o carro')
elif distancia / quantidade_litros <= 12:
return print('Econômico')
else:
return print('Super econômico')
retorno = consumo(100,10)
retorno2 = consumo(30, 4.5)
|
# Generated by Django 3.1 on 2020-08-31 22:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pages', '0006_auto_20200817_0419'),
]
operations = [
migrations.AddField(
model_name='webpage',
... |
# coding:utf-8
class Foo(object):
def __enter__(self):
print("enter called")
def __exit__(self, exc_type, exc_val, exc_tb):
print("离开方法")
# 上下文管理器
with Foo() as foo:
print("hello python") |
from useless.sqlgen.admin import grant_public, grant_user
from tables import primary_sequences
from tables import primary_tables
#from tables import SCRIPTS, MACHINE_SCRIPTS
from tables import TRAIT_SCRIPTS, MACHINE_SCRIPTS
from pgsql_functions import create_pgsql_functions
class SchemaError(RuntimeError):
pass
... |
# """
# Topological Sort
# Difficulty: Hard
# Given a list of tasks and a list of dependencies return
# a list of tasks in valid order. If no such order exists
# return an empty array.
#
# tasks = [1,2,3,4]
# deps = [
# [2, 3],
# [2, 4],
# [4, 3],
# [1, 3],
# [1, 4],
# ]
#
# topological_sort(tasks, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.