text stringlengths 38 1.54M |
|---|
import os
import re
import tempfile
from io import BytesIO
import networkx as nx
import requests
from bs4 import BeautifulSoup
ACCEPTED_CLASSES = [
"Actinopterygii",
"Amphibia",
"Aves",
"Insecta",
"Mammalia",
"Reptilia",
]
BASE_CLASS_URL = "https://github.com/bansallab/asnr/tree/master/Netw... |
import turtle
# create a list of colors
rainbow_colors = ['grey', 'yellow', 'green', 'blue', 'purple', 'orange', 'red']
# width for single rainbow color
rainbow_width = 30
# the radius of most inner rainbow color
rainbow_size = 100
# set up turtle painter
painter = turtle.Turtle()
painter.shape('turtle')
painter.pens... |
import argparse
import codecs
import pickle
import os
import sys
from escapewords import escape_words
from stopwords import stopwords
import stems
#from stemming.porter2 import stem
inverted_index = {}
ignore_list = set(['c++', 'md5', 'sha1', 'sha2', 'sha256', 'sha512'])
def remove_special_chars(word):
if word in... |
#!/usr/bin/python3
import csv
import itertools
import os
import re
import sys
import tempfile
from collections import OrderedDict
from pathlib import Path
from shutil import copyfile
class bcolors:
PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YEL = '\033[93m'
RED = '\033[91m'
ENDC... |
import torch.nn as nn
import torch
class Biaffine(nn.Module):
def __init__(self,n_input,n_output=1):
super().__init__()
self.n_in=n_input
self.n_out=n_output
self.weight=nn.Parameter(torch.Tensor(self.n_out,self.n_in+1,self.n_in))#1x501x500
self.reset_parameters(... |
import scrapy
import csv
import os
class OilTraceSpider(scrapy.Spider):
name = "oiltrace"
def start_requests(self):
urls = [
'https://g1.globo.com/natureza/noticia/2019/10/08/lista-de-praias-atingidas-pelas-manchas-de-oleo-no-nordeste.ghtml'
]
for url in urls:
... |
from datetime import datetime
from django.core.management import BaseCommand
from core.facade import get_usd_cny_exchange
from core.models import CotacoesMoedas
class Command(BaseCommand):
help = '''Atualiza cotações no banco de dados'''
def handle(self, *args, **options):
cotacoes_moedas = get_usd... |
from gtav_properties import properties, columns
import os
out = open('out.html', "w+")
for p in properties:
d = dict(zip(columns, p))
out.write("""%s (%s) """ % (d["personid"], d["gender"]))
for idx in xrange(1, 5):#d['numimages']+1):
fname = "jpgs/%s_%03d.jpg" % (d["personid"], idx)
out.... |
#!/usr/bin/env python
# /data3/wk/MPTopo/src/select_paircmp.py
import os
import sys
import libtopologycmp as lcmp
import myfunc
import copy
import subprocess
DEBUG_UNMAPPED_TM_POSITION = 0
BLOCK_SIZE = 100000
progname = os.path.basename(sys.argv[0])
usage="""
Usage: %s paircmp-file [-o OUTFILE]
Description:
Sel... |
from multiprocessing import Pool, TimeoutError
import time
import os
def f(x):
return os.getpid(), x*x
if __name__ == '__main__':
# start 4 worker processes
with Pool(processes=8) as pool:
# print "[0, 1, 4,..., 81]"
print(pool.map(f, range(100)))
print(pool.imap(f, range(10)))
|
import modeTest #导入模块 第一种导入方式
# # from modeTest import add #第二种
# # from modeTest import * #第三种
# re = modeTest.add(1,2) #模块中的测试代码也被执行了 如果想要测试的代码不执行就需要加上一个判断(见原模块中)
# print(re)
# print(modeTest.diff(3,4))
# #此时的 运行结果中就不包含测试中的代码
print(modeTest.printInfo()) #使用第一种方式引入模块则即使不在__all__函数中也可以执行
#使用此方式引入模块,若模块中有__a... |
"""General monte carlo simulation helper."""
import os
from time import time
import multiprocessing
from collections import OrderedDict
from pathos.multiprocessing import ProcessPool
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm
from mpmath import mpf
global_fn_multi... |
import ttg
import prettytable
class truthTable:
def __init__(self, AST):
self.AST = AST
self.proposition = []
self.propVar = []
self.operations = ["and", "or", "=>", "~"]
self.convertProposition()
print(self.proposition)
print(self.propVar)
... |
"""Copyright (c) 2018 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
After squashing our image, verify that it has the media types that
the registry expects
"""
from __future__ import unicode_literals
from atomic_... |
import calendar
year=2021
for month in range(1,13):
print(calendar.month_name[month])
|
import vgg16; reload(vgg16)
from vgg16 import VGG16
#from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
from keras.utils.np_utils import to_categorical
from keras.models import Sequential, load_model
from keras.laye... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from models import Post
from models import Family
from django.http import HttpResponse,Http404
from django.template.loader import get_template
from django.shortcuts import redirect
import sys
reload(sys)
sys.setdefaulte... |
# coding=utf-8
import unittest
import logging
from sgcharts.nlp import ngram_gen, ngram_from_tokens_gen
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
class TestNgramGenerator(unittest.TestCase):
def test_bigram(self):
inp = "Apple is looking at buying U.K. startup for $1 bill... |
from PyCov19.beta_models import exp, tanh
def reproduction_number (beta_model, epd_model, **kwargs):
# must have the following
# model, beta_0, alpha, mu, tau, tl
for k in kwargs:
try:
kwargs[k] = float(kwargs[k])
except:
pass
beta = eval(beta_model) (kwargs['num_day... |
# coding: UTF-8
import sys
# python filenames
args = sys.argv
"""
ohtoさん提供の棋譜をpos形式に変換する
データの形式:
dealt { d3 c4 s4 h6 h9 ct hj hk d2 h2 jo } { c3 s6 h7 c8 s8 ht cj dq ca ha c2 } { d5 d7 s7 dt st sj sq ck sk da } { d4 h4 c5 h5 s5 c7 c9 d9 dj dk sa } { h3 s3 c6 d6 d8 h8 s9 cq hq s2 }
changed { h6 ct } { } { sk da } {... |
from .InputEngine.InputEngineInterface import IInputEngine
from .OutputEngine.OutputEngineInterface import IOutputEngine
class IOEngine(object):
def __init__(self, inputEngine: IInputEngine, outputEngine: IOutputEngine):
assert isinstance(inputEngine, IInputEngine)
assert isinstance(outputEngine, IOutputEng... |
import os
import random
import sys
import zipfile
from operator import itemgetter
import numpy
import numpy as np
import prettytable
from prettytable import PrettyTable
from nupic.frameworks.opf.model_factory import ModelFactory
import csv
import matplotlib.pyplot as plt
PAGE_CATEGORIES = [
'04f2', '00a0', '0370',... |
from django.db import models
from web.models.mixins import Archivable
class ProductLegislation(Archivable, models.Model):
name = models.CharField(max_length=500, verbose_name="Legislation Name")
is_active = models.BooleanField(default=True)
is_biocidal = models.BooleanField(
default=False,
... |
'''
후위 표기 수식 계산
- 수식을 왼쪽부터 차례로 읽음
- 피연산자가 나타나면 스택에 push
- 연산자가 나타나면 스택에 들어있는 피연산자를 두개 pop후 연산을 적용,
그 결과를 다시 스택에 넣음
'''
class ArrayStack:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def push(self,... |
from torchvision import datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.data import SubsetRandomSampler
import sys
# We split the total dataset to four equal parts. Half of the dataset is Dshadow, from which half is Dshadow_train
# used for training ... |
h = input('請輸入身高(cm):')
w= input('請輸入體重(kg):')
h = float(h)
w = float(w)
h = h / 100 #換算成m
bmi = w / h / h
print(bmi)
if bmi < 18.5:
print('你的bmi值為', bmi, '體重過輕')
elif bmi >= 18.5 and bmi < 24:
print('你的bmi值為', bmi, '正常範圍')
elif bmi >= 24 and bmi < 27:
print('你的bmi值為', bmi, '過重')
elif bmi >= 27 and bmi < 30:
print(... |
# Improting Image class from PIL module
from PIL import Image
# Opens a image in RGB mode
im = Image.open(r"test_image.jpg")
# Size of the image in pixels (size of orginal image)
# (This is not mandatory)
width, height = im.size
print(width, height)
newsize = (1500, 800)
im1 = im.resize(newsize)
# Sho... |
#
# @lc app=leetcode.cn id=917 lang=python3
#
# [917] 仅仅反转字母
#
# @lc code=start
class Solution:
def reverseOnlyLetters(self, S: str) -> str:
# "ab-cd"
'''
# 1.字母栈:遍历S,字母放入栈;再次遍历,是字母就弹出,不是就加入本身符号 O(n) O(n)
leters = [c for c in S if c.isalpha()]
# print(leters) # ['a', 'b', '... |
import os
import numpy as np
from itertools import product
import sys
sys.path.append('../')
from utils import partitions, weak_partitions
import pandas as pd
PYRAMINX_GROUP_SIZE = 11520 * 4
def alpha_parts():
irreps = []
for alpha in weak_partitions(6, 2):
for parts in product(partitions(alpha[0]), pa... |
'''
풀이
R,B,V 가 있다.
V 는 좌우에 있는게 같으면 안된다.
R,B,V는 같은게 연속으로 올 수 없다.
'''
N=int(input())
S=input()
top = S[0]
cnt=1
max_cnt=1
for i in S[1:]:
if top == i or i == "V" or top =="V":
max_cnt=max(cnt,max_cnt)
cnt=1
top=i
else:
cnt+=1
top=i
max_cnt=max(cnt,max_cnt)
print(m... |
import gc, argparse, sys, os, errno
import numpy as np
import pandas as pd
import seaborn as sns
#sns.set()
#sns.set_style('whitegrid')
import h5py
from PIL import Image
import os
from tqdm import tqdm as tqdm
import scipy
import sklearn
from scipy.stats import pearsonr
import warnings
warnings.filterwarnings('ignore'... |
"""
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
# do not change their names.
NTRIALS = 100 # Number of trials to run
SCORE_CURRENT = 1.0 # Score for... |
import csv
import json
import os
import re
import sys
import time
import operator
#define and create folder for output
folderoutput = "_output"
if not os.path.exists(folderoutput):
os.mkdir(folderoutput)
#create JSONs files if not exist
dictallfiles = {"0":"extracted_ks","1":"extracted_bl","2":"extracted_top... |
import os
import struct
BUFFER_SIZE = 8388608
#reads buffer sized data from the unsorted file and generates a list from it
def create_list_of_nums(bin_file):
list_of_nums = []
buf = bin_file.read(BUFFER_SIZE)
if not buf:
return "done",list_of_nums
fmt = '%si' % (len(buf) // 4)
list_of_n... |
import math, os, pickle, re
class Bayes_Classifier:
#positive files = 11129
#positive frequency = 631382
#percentage positve = 0.8027264858626659
#percentage of frequencies that are positive = 0.825
#negative files = 2735
#negative frequency = 134120
#percentage negative = 0.1972735141373341
#... |
print('hello world')
def hellogit():
print('hello git!')
hellogit()
print('the files changes')
print('maybe merge conflict')
print('try to modify the file and commit again')
print('what is the problem')
"""
clone , add, commit,
push , pull, reset
this is how we use git.
"""
print('edit from cloud')
def push()... |
#Break and Continue in Loops
#Break -- breaks the loop
for i in range(10):
if i == 4:
print('Breaking at 4')
break
#Continue -- this will skip the current execution of further lines
i = 0
while i < 10:
print(i)
i += 1
if i == 4:
print('Skipping 4')
continue
print('... |
#!/usr/bin/env python
'''
Author: Eli Moss elimoss@stanford.edu, Prag Batra prag@stanford.edu
Purpose:
Modify the output of bedtools' intersectbed utility in order to contain only one instance of each genomic locus.
Explanation:
The left outer join functionality of intersectbed will output one line per match... |
#https://www.dataquest.io/blog/python-api-tutorial/
import requests
import json
from time import sleep
from datetime import datetime
# #test 404 error code, this api doesnt exist!!!
# response = requests.get("http://api.open-notify.org/this-api-doesnt-exist")
# print(response.status_code)
# #tests success status code... |
#-*- coding:utf-8 -*-
import os
import json
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from config import config
# import torch
def main():
traindatapath = os.path.join(config['Datapath'], 'train_set')
# train_path = os.path.join(traind... |
class Phone():
def __init__(self,name,color):
self.name = name
self.color = color
def call(self):
print('打电话')
class meizi(Phone):
pass
class huawei(Phone):
pass
mz = meizu('魅族','白色')
print(mz.name)
print(mz.color)
mz.call(()
hw = huawei('华为','黑色')
print(hw.name)
print... |
# Generated by Django 3.1.1 on 2020-09-23 17:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
consumer_key = '<consumer_key>'
consumer_secret = '<consumer_secret>'
access_token = '<access_token>'
access_secret = '<access_secret>'
|
import functools
from collections import Counter
from sympy import *
from sympy.physics.quantum import TensorProduct, tensor_product_simp, Ket
import numpy as np
import measurements
import gates
import utils
class Barrier(object):
"""Create a barrier in the circuit.
This prevents optimization of opera... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import Select
from django.test.testcases import LiveServerTestCase
from django.test.testcases import TestCase
from users.models import My_cus... |
# -*- coding: utf-8 -*-
"""
create by caijinxu on 2019/6/4
"""
from app.forms.base import BaseForm, DataRequired
from wtforms import StringField, IntegerField, SubmitField, BooleanField
from wtforms.validators import Length, NumberRange
__author__ = 'caijinxu'
class SearchForm(BaseForm):
KeyWord = StringField(
... |
from appkernel import AppKernelEngine
from checkout import InventoryService
app_id = f"{InventoryService.__name__}"
kernel = AppKernelEngine(app_id)
if __name__ == '__main__':
inventory_service = InventoryService(kernel)
kernel.run()
|
import numpy as np
from fbm import *
from variables import *
class Sender(object):
def __init__(self, debug = False):
self.debug = debug
self.digit_to_hurst = dict({
"0": hurst1, "1":hurst2, "2":hurst3
})
self.letter_to_digits = dict({
"a":"000", "b"... |
import os
import sys
from loguru import logger as log
from botleague_helpers.db import get_db
from box import Box
import utils
from problem_constants.constants import JOB_STATUS_FINISHED, \
JOB_STATUS_ASSIGNED, JOB_TYPE_EVAL, JOB_TYPE_SIM_BUILD, \
JOB_TYPE_DEEPDRIVE_BUILD
from common import get_worker_insta... |
import os
import os.path
from wikimetrics.exceptions import PublicReportIOError
# TODO ultils imports flask response -> fix
from wikimetrics.utils import ensure_dir
class PublicReportFileManager():
"""
Encapsulates access to filesystem and application level
operations related to public reports.
S... |
# Author: zhangshulin
# Email: zhangslwork@yeah.net
# Date: 2018-04-18 10:41:10
# Last Modified by: zhangshulin
# Last Modified Time: 2018-04-18 10:41:10
import tensorflow as tf
import numpy as np
import helper
class CoupletsDataGenerator:
def __init__(self, set_array, shuffle=True, buffer_size=10000):
... |
import itertools
from functable import FunctionTableProperty
from twisted.internet import defer
from thinserve.api.referenceable import Referenceable
from thinserve.api.remerr import RemoteError
from thinserve.proto.shuttle import Shuttle
from thinserve.proto.error import InternalError
class Session (object):
def... |
#!/usr/bin/env python
# grw-wrangle
# Takes the CSV file from Google Drive and creates the required JSON data.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Fri May 29 15:28:50 2015 -0400
#
# Copyright (C) 2015 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: grw-wrangle.py [] benja... |
from django import forms
class ProfileForm(forms.Form):
#Usand el parametro label puede cambiar el nombre a otro idioma manualmente
first_name = forms.CharField(max_length=100, required=True)
last_name = forms.CharField(max_length=100, required=True)
bibliography = forms.CharField(max_length=500, requi... |
import pytest
from works import tasks
pytestmark = pytest.mark.django_db
@pytest.fixture(autouse=True)
def change_settings(settings):
settings.DISABLE_NOTIFICATIONS = False
settings.EMAIL_ENABLED = True
settings.OUR_EMAIL = 'stepik@stepik.stepik'
@pytest.fixture
def email(mailoutbox):
return lambd... |
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
import dynet as dy
import dynet_modules as dm
import numpy as np
import random
from utils import *
from data import flatten
from time import time
from modules.seq_encoder import SeqEncoder
from modules.bag_encoder imp... |
# Create your views here.
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from book.models import Book
from book.forms import addBookForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpRe... |
def persistenciaAditiva(numero):
contador = 0
acumulador = 0
while (numero >= 10):
while (numero != 0):
acumulador += (numero %10)
numero //= 10
contador+=1
numero = acumulador
acumulador = 0
return contador
print(persistenciaAditiva(7865))
prin... |
import numpy as np
MAX_NUM=0x7fffffff
class Merge(object):
@staticmethod
def show():
# 石子堆数
n = int(input())
N = 41000
v = np.array(np.arange(N).reshape(N,1))
ans = 0
v[0] = MAX_NUM
v[n + 1] = MAX_NUM
# 每堆石子数
for i in range(1, n + 1) :
... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
config.config_app(app)
# see: https://stackoverflow.com/questions/33241050/trailing-slash-triggers-404-in-flask-path-rule
app.url_map.strict_slashes = False
d... |
import os
#Get absolute path of file
current_file_path = os.path.abspath(__file__)
BASE_DIR = os.path.dirname(current_file_path)
ROOT_PROJECT_DIR = os.path.dirname(BASE_DIR)
#Join BASE_DIR with folder and filename
email_text = os.path.join(BASE_DIR, 'templates', 'email.txt')
content = ''
with open(email_text, 'r') as... |
import copy
import h5py
import numpy
import pickle
import os
import torch
import platform
import logging
import nmtpytorch
from nmtpytorch import logger
from nmtpytorch import models
from nmtpytorch.mainloop import MainLoop
from nmtpytorch.config import Options, TRAIN_DEFAULTS
from nmtpytorch.utils.misc import setup_e... |
import os
import sys
import setuptools
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'simplejson',
'psycopg2',
'pyparsing',
]
#
# egg... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from subscriptions.views import get_user_membership, get_user_subscription
# Create your views here.
def index(request):
return render(request, 'index.html')
def strange(request):
return render(request, 'index.html')... |
import pygame
class ButtonSet:
def __init__(self, window):
self.buttons = {}
self.window = window
self.hidden = False
def add_button(self, name, button):
self.buttons[name] = button
def check_pressed(self, mouse_x, mouse_y):
for button in self.buttons:
... |
import nltk
from nltk.sentiment import SentimentAnalyzer
from nltk.classify import NaiveBayesClassifier
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.corpus import subjectivity
from nltk.sentiment.util import *
from nltk.corpus import stopwords
from flask import Flask
from flask import request
i... |
import os
import click
import gin
import tensorflow as tf
import numpy as np
from mlagents_envs.environment import UnityEnvironment
from tf_agents.agents import PPOAgent
from tf_agents.drivers import driver
from tf_agents.drivers.dynamic_step_driver import DynamicStepDriver, is_bandit_env
from tf_agents.environments.t... |
#!/usr/bin/env python
runToFbset = {
273158 : "fb_all_withuTCA_consolidated3_no1240_TOTEM",
275832 : "fb_all_withuTCA_with_CTPPS_TOT",
273301 : "fb_all_withuTCA_consolidated3_no1240_TOTEM",
276870 : "fb_all",
282092 : "/daq2/eq_160913_01/fb_all_with1240_withCASTOR",
283171 : "/daq2/eq_160... |
NUM_OF_NODES = 10
BLOCK_SIZE = 10
MINING_DIFFICULTY = 4
KEY_LEN = 2048
BOOTSTRAP_IP = '127.0.0.1' #For local use
#BOOTSTRAP_IP = '192.168.0.1' #For okeanos use
BOOTSTRAP_PORT = '5000'
|
import enum
from collections import namedtuple
class Room(object):
def __init__(self, rows, slots):
self.rows = [Row(self, y, slots) for y in range(rows)]
def __getitem__(self, pos):
y = pos
x = None
if isinstance(pos, (tuple)):
(y, x) = pos
row = self.r... |
# !/usr/bin/env python
# encoding: utf-8
import sys
import pandas as pd
def get_login_information():
"""
读取表中存取的用户名密码
:return:
"""
get_data = pd.read_csv("basic_information", sep=" ")
deal_data = get_data.groupby("username")["password"].apply(list).to_dict()
return deal_data
def locking... |
'''
Given a N X N matrix Matrix[N][N] of positive integers. There are only three possible moves from a cell Matrix[r][c].
1. Matrix[r+1][c]
2. Matrix[r+1][c-1]
3. Matrix[r+1][c+1]
Starting from any column in row 0, return the largest sum of any of the paths up to row N-1.
Input:
The first line of the input conta... |
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from time import strftime
import csv
bloggerList = []
class r(object):
def __init__(self,r0=0, r1=0, r2=0, r3=0, r4=0):
self.r0, self.r1, self.r2, self.r3, self.r4 = r0, r1, r2, r3, r4
def getHref(user_info):
r... |
MAX = 100 + 1
NEG_INF = -10**9
T = int(input())
def bellmanFord(n, edges):
dist = [NEG_INF]*n
dist[0] = 0
for _ in range(n-1):
for v, u, w in edges:
if dist[v] == NEG_INF: continue
if dist[u] < dist[v] + w:
dist[u] = dist[v] + w
for v, u, w in edges:
if dist[v] == NEG_INF: continue... |
import json
import socket
print('Server started.')
NUM_OF_TURNS = 10
# VICTORIES_CONDITIONS = ['Max', 'Min', 'Linear', 'Quadratic', 'ZeroM', 'SumNeg', 'SumPos']
# VICTORIES_CONDITIONS = ['Max', 'Min']
# VICTORIES_CONDITIONS = ['ZeroM']
VICTORIES_CONDITIONS1 = ['Min']
VICTORIES_CONDITIONS2 = ['Min']
# VICTORIES_CONDIT... |
import numpy as np
from task import Task
from collections import defaultdict, deque
import sys
class Quadcop_Policy():
def __init__(self, task):
# Task (environment) information
self.task = task
self.state_size = task.state_size
self.action_size = task.action_size
self.acti... |
# -*- coding: utf-8 -*-
"""Parser has another main Curly's function, :py:func:`parse`.
The main idea of parsing is to take a stream of
tokens and convert it into `abstract syntax tree
<https://en.wikipedia.org/wiki/Abstract_syntax_tree>`_. Each node in the
tree is present by :py:class:`Node` instances and each instanc... |
from flask import Flask,render_template,redirect,request,url_for,flash
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SECRET_KEY'] = 'dev'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a basic calculator that can do four operations; addition, subtraction, summation and division.
"""
def addition(a, b):
""" Addition Operator """
return a + b
def subtraction(a, b):
""" Subtraction Operator """
return a - b
def summation(a, b)... |
'''
Write ts.data.new file, deleting transition states that connect a minimum with ID greater than the argument
'''
import sys
max_min_id = int(sys.argv[1])
tdnew_f = open("ts.data.new","w")
with open("ts.data","r") as td_f:
for line in td_f.readlines():
line = line.split()
if not ((int(line[3]) ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 17 00:52:23 2018
AMAC:
1-Olen insanlarin F-M sayilari
2-Silah çeşitlerine göre ölüm sayıları
3- Yaşı 25ten küçük/Büyük olanların sayıları
4-Irklara gore olum sayıları
Bu sayi olaylarını Visualization ypamaya yarar
"""
#%% GENEL KUTUPHANELER VE CSV
import numpy as np
impor... |
#!/usr/bin/python3
"""
Something is weird about this library or maybe I'm not getting something.
It seems from the old code that we do the following:
a) make the PICC_REQIDL request
b) ignore its return value
c) do the anti-collision routine
d) extract a UID and ignore other statuses...
Going to start with this for... |
import pygame
import cfg
import os
images = []
for i in range(0, 12):
images.append(pygame.image.load(os.path.join('sprite', 'piece_'+str(i)+'.png')))
class Piece:
#(x,y) coords not pixel coords, i.e. (1,2) instead of (100,200)
def __init__(self, x, y, white, img, moved = False, pickedUp = False... |
#coding=utf-8
import requests
from lxml import etree
def getMovieData():
movies = []
url = r'https://movie.douban.com/top250'
parameter = r'?start=0&filter='
# 经过观察可以知道网站链接的特点是url加上下面这个参数
# 而这个参数可以从每一页的“后一页>”的a标签中获得
# 另外由于最后一页没有parameter这个参数,所以还需要做个条件判断
try:
while str(parameter[0]):
# 生成链接
urls = url ... |
import motor.motor_asyncio
async def init_pg(app):
# conf = app['config']['postgres']
# engine = await aiopg.sa.create_engine(
# database=conf['database'],
# user=conf['user'],
# password=conf['password'],
# host=conf['host'],
# port=conf['port'],
# minsize=conf[... |
# coding: utf-8
import json
import itertools
from django.core.exceptions import ValidationError
from django.core.validators import validate_ipv46_address
from django.utils.encoding import force_text
def pretty_data(request):
if request.META.get('CONTENT_TYPE', None) == 'application/json':
# json encoded ... |
import boto3
import logging
from configparser import ConfigParser
from botocore.exceptions import ClientError
from tweepy import StreamListener, Stream, OAuthHandler
class TweetListener(StreamListener):
"""
Streams the recent tweets related to the query to AWS Kinesis
"""
def __init__(self, config):
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
n,m = map(int,sys.stdin.readline().split())
mid =int(n/2)
mid2=int(m/2)
for i in range(0,mid2):
if(i%2!=0):
if (i == n):
break
else:
print("---"*mid+".|."*(i) + "---"*mid)
... |
#!/usr/bin/env python3
grid = {}
def sum_neighboors(x, y):
sum = 0
for i in range(-1, 2):
for k in range(-1, 2):
sum = sum + grid.get((x + i, y + k), 0)
return sum
def print_grid(grid):
print("---")
for i in range(-10, 10):
for k in range(-10, 10):
print(... |
import numpy as np
import matplotlib.pyplot as plt
def generateMVNRandData(Npts, mu, sigma):
data = np.random.multivariate_normal(mu, sigma*np.eye(len(mu)), Npts)
return data
def plotLine(weights, range):
x = np.array(range)
y = -(weights[0]/weights[1])-(weights[2]/weights[1])*x
plt.plot(y,x)
plt.pause(2)
def... |
import RPi.GPIO as GPIO
class LED:
def __init__(self, pin):
self.__pin = pin
def on(self):
GPIO.setup(self.__pin, GPIO.OUT)
GPIO.output(self.__pin, GPIO.HIGH)
def off(self):
GPIO.setup(self.__pin, GPIO.OUT)
GPIO.output(self.__pin, GPIO.LOW)
|
import random
import math
import operator
def objective(chromosome, target):
# Returns the fitness score for the given chromosome
score = 0
for i in range(0, len(chromosome)):
score += math.pow(chromosome[i] - target[i], 2)
return score
def crossover(chromosome1, chromosome2):
# Performs crossover on the ... |
题目类似于一个正整数可以拆成其他正整数的和,求这些正整数的最大连乘积。
将绳子 以相等的长度等分为多段 ,得到的乘积最大。
y=x^[(1/x)*n],n是常数,对y=x^(1/x)求导得知2.7几时有极大值。
x取整数3.
x对3取余得到b。对3整除得到a。
当b=0 时,直接返回 3^a,
当b=1 时,要将一个1+3 转换为2+2,因此返回 3^(a−1)×4,
当b=2 时,返回3^a×2。
class Solution:
def cuttingRope(self, n: int) -> int:
if n<=3:
return n-1
a = n//3
... |
__all__ = ('GameWorld',)
from appuifw import Canvas, EEventKey, EEventKeyUp, app, popup_menu
from e32 import ao_yield, ao_sleep
from graphics import Image
from sysinfo import free_ram, total_ram
from pyboom.colors import BLACK, WHITE
from pyboom.types import SingletonType
FPS_DEFAULT = (1.0 / 60.0) # ~60FPS
COLOR_... |
# encoding:utf-8
import re
from utils.fileUtil import FileUtil
# from fileUtil import FileUtil
class ReportUtil(object):
# 异常类型
# 1空指针异常
NullPointerException="java.lang.NullPointerException"
NullPointerExceptionCounter=0
# 2数组溢出
ArrayIndexOutOfBoundsException="java.lang.ArrayIndexOutOfBounds... |
# Generated by Django 2.2.6 on 2021-04-09 10:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='newsarticle',
options={'permissions': (('add_ar... |
from datetime import datetime
from rest_framework import serializers
# from rest_framework_cache.serializers import CachedSerializerMixin
# from rest_framework_cache.registry import cache_registry
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
owner = serializers.StringRelatedField... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 15 11:26:51 2017
@author: Administrator
"""
# Import modules
from OCC.gp import *
from OCC.GC import *
from OCC.BRep import *
from OCC.BRepAlgoAPI import *
from OCC.BRepBuilderAPI import *
from OCC.BRepFilletAPI import *
from OCC.BRepPrimAPI import *
from ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 22 10:50:05 2019
Example for reading fire output
@author: Mika Peace
"""
import matplotlib
matplotlib.use('Agg')
import matplotlib as mpl
import time
from datetime import datetime, timedelta
import numpy as np
from matplotlib.backends.backend_pdf import P... |
from django import forms
from django.forms import PasswordInput
from .models import *
class UserForm(forms.ModelForm):
class Meta:
model= userInfo
fields = [
# 'firstName',
# 'lastName',
'email',
'password',
# 'age',
# 'addr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.