text stringlengths 38 1.54M |
|---|
def subset_sum(in_list, target, start, end):
if target == 0:
return '{0},{1}'.format(start, end-1)
if target < 0 or end == len(in_list):
return '-1,-1'
target -= in_list[end]
return subset_sum(in_list, target, start, end+1)
def solution(l, t):
# Your code here
for i, each_num i... |
#!/usr/bin/env python
#original: https://github.com/haroldsultan/MCTS/blob/master/mcts.py
import math
import hashlib
import rospy
import logging
import argparse
import numpy as np
import matplotlib.pyplot as plt
import random
import scipy.stats as stats
from dt_comm.enums import Ground
import time
costMat = np.zeros((... |
"""
Author: linnil1
Objective: Image Processing HW1
Description: This program 1)read a spectial format called 64, which represented
a image, 2)do some operation (multiply, add, avg) on it and 3)draw histogram.
"""
import numpy as np
import matplotlib.pyplot as plt
import utils
def limitImg(func):
"""
Limit t... |
n = int(input())
a,b = map(int,input().split())
k = int(input())
pk = [int(i) for i in input().split()]
if a not in pk and b not in pk and (len(pk) == len(set(pk))):
print('YES')
else:
print('NO')
|
# -*- coding: UTF-8 -*-
"""
relaxed_spec.py
Copyright 2019 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is dis... |
import torch
import torchaudio
import random
def pad_tensor(tensor, max_length):
# input tensor (1, n) --> (1, max_length)
n = tensor.size(1)
zeros = torch.zeros(1, max_length)
zeros[:, :n] = tensor
return zeros
def padding_batch(sequences):
"""
sequences is a list of tensors
"""
num = len(s... |
from .views import EmployeeViewSet, TaskViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'employee', EmployeeViewSet)
router.register(r'task', TaskViewSet)
|
#!/usr/bin/python
# Raspberry Pi based system for recording and transmitting data from a lone long distance walker.
# Being built for http://thelongwellwalk.org/
#Import the supporting code we need
import picamera # Controlling the Camera
import time # Time and Date functions
import os ... |
# I modelled this problem as a bipartite graph
# where each vote is a vertex. All votes in favor of cats
# go on one side and all votes in favor of dogs go to the other
# side of the graph.
# Two vertices/votes are connected if they exclude one another,
# in a way that they cannot both be satisfied (e.g. C1 D1 and D1 ... |
# -*- coding: utf-8 -*-
"""
@File : _aiofile.py
@Time : 2021/6/14 0:07
@Author : my-xh
@Version : 1.0
@Software: PyCharm
@Desc : 文件异步IO库(旧版)
"""
import asyncio
class AsyncFunWrapper:
def __init__(self, blocked_func):
# 封装阻塞型IO函数
self._blocked_func = blocked_func
def __call__(self,... |
"""API microservice porviding the activities and model APIs"""
from connexion import App
from flask import Flask
def setup_app(flask_app: Flask) -> None:
"""
Setup the flask modules used in the app
:param flask_app: the app
"""
from ..flask_modules.celery import setup_celery
from ..flask_modu... |
from film_details_searcher.models.movie import Movie
from film_details_searcher.scrappers.custom_headers import CUSTOM_HEADERS
from film_details_searcher.scrappers.movie_service import MovieService
from bs4 import BeautifulSoup
import requests
class FilmwebMovieService(MovieService):
def _fetch_movie_from_link(s... |
"""
****************************************
Create a folder named "Original_image"
And put the carrier image in that folder
To get more information see line no. 75
****************************************
"""
import os
import shutil
from PIL import Image
from pathlib import Path
#encoding part :
def enco... |
SERIAL = 5235
SIZE = 300
def power_level(x, y, serial):
rack_id = x + 10
power = rack_id * y
power += serial
power *= rack_id
power = (power % 1000) // 100
return power - 5
def get_powers(serial):
return {
(i, j): power_level(i, j, serial)
for i in range(1, SIZE + 1)
... |
WINDOWS_KERNEL_BOUND = 0x80000000
WINDOWS_SYSENTER = None
WINDOWS_SYSEXIT = None #0x804de904
ins_count = 0
ctx_switches = 0
class StopExecution(BaseException):
pass
def init():
gdb.execute("set height 0")
gdb.execute("set pagination off")
gdb.execute("set logging redirect on")
gdb.execute("set logging file /de... |
""" pop removes the last item, or the item at a particular index.
pop returns the item that was removed
You can ignore the item, if you don't need it, or use it if you do.
"""
colleges = ['Minneapolis College',
'Metro State',
'Saint Paul College',
'North Hennepin Community College',... |
# solved
import sys
for line in sys.stdin:
cpf = list(map(int, line.replace('.', '')[:9]))
digits = list(map(int, line.replace('\n', '')[-2:]))
first = (sum([cpf[i] * (i + 1) for i in range(len(cpf))]) % 11) % 10
second = (sum([cpf[i] * (len(cpf) - i) for i in range(len(cpf))]) % 11) % 10
if first == digits[0] ... |
# Filters twitter json file text field
# python -OO twep.py TWITTER_FILE REGEX
import sys
import re
import json
import datetime
#Wed, 12 Aug 2009 01:23:04 +0000
#Wed, 12 Aug 2009 01:23:04 +0000
e = datetime.datetime.strptime("Wed, 12 Aug 2012 01:23:04 +0000", "%a, %d %b %Y %X +0000")
def main():
f = file (sys.a... |
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import tensorflow as tf
from tensorflow.python.framework import ops
import cnn_utils
np.random.seed(1)
def create_placeholders(n_H0, n_W0, n_C0, n_y):
X = tf.placeholder(tf.float32,[None, n_H0, n_W0, n_C0... |
# O(n*log(k))
# n = n | k = len(primes)
import heapq
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
uglyHeap = [(primes[i], i, 0) for i in range(len(primes))]
superUgly = [1]
while len(superUgly) < n:
nextUgly, primeUsed, multiplierIndex = heap... |
"""
Homework 9 Errors
"""
class InvalidCharactersError(Exception):
pass
class NumberTooBigError(Exception):
pass
class NumberTooSmallError(Exception):
pass
class NumberLessThanLowerLimitError(Exception):
pass
class NumberGreaterThanUpperLimitError(Exception):
pass
class NumberOutOfRangeErro... |
import unittest
from rgen import *
from xml.etree.ElementTree import Element, SubElement, tostring
from collections import namedtuple
import os
Field = namedtuple('Field', ['name', 'width', 'default'])
class create_xml_reg_file:
def __init__(self, filename, name, asize=16, dsize=16):
self.filename = file... |
import numpy as np
import matplotlib.pylab as plt
import pandas as pd
from scipy.optimize import fmin,fmin_slsqp,minimize,differential_evolution
from scipy.signal import hilbert,savgol_filter
from scipy import stats
import seaborn as sns
import sys
sys.path.insert(0, '../Helper')
sys.path.insert(0, '../Supe... |
# -*- coding: utf-8 -*-
"""
Created on 2018/2/4 10:24
statsmodels模块示例
在统计学中,普通最小二乘法(OLS)用于估计线性回归模型参数的一个常用方法
目标是选择参数使得观测值和模型的预测值之间的差值的平方之和最小
@author: wangdongsong1229@163.com
"""
import numpy as np
import statsmodels.api as sm
y = [1, 2, 3, 4, 2, 3, 4]
x = range(1, 8)
x = sm.add_constant(x)
result = sm.OLS(y, x).... |
def numberguessgame():
import random
num = random.randint(1,10)
print('I have chosen a number from 1 to 10. Please guess it. (5 Guesses)')
i = 1
gl = 5
for i in range(1,6):
guess = input()
guess = int(guess)
gl = 5 - i
if guess < 0 or guess >10:
... |
from django.core.management.base import BaseCommand, CommandError
from django.shortcuts import get_object_or_404
from pdfgenerator.models import Queue, Converted_Pdf
from pdfgenerator.helpers import convert_doc_to_pdf
class Command(BaseCommand):
help = "Converts file to pdf"
def handle(self, *args, **options... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader.processors import MapCompose, TakeFirst
class TopligaItem(scrapy.Item):
# define the fields for your item here like:
_id = ... |
import pandas as pd
import numpy as np
from foodkm import config
import os
def update_column_names(df, COL_RENAME_DICT):
df_ = df[list(COL_RENAME_DICT.keys()) + ['ingredients'] + config.PRICES + config.LOCATION_COL].copy()
return df_.rename(columns=COL_RENAME_DICT)
def clean_and_rename(df):
# Drop non n... |
from sympy.plotting import plot
import sympy as sym
import xlsxwriter
from xlrd import open_workbook
from sympy.plotting import plot3d
print("Q1..................................")
x = sym.Symbol('x')
y, i ,n, a, b, z = sym.symbols('y i n a b z')
expr=x**2+x**3+21*x**4+10*x+1
print (expr.subs(x, 7))
#........ |
import numpy as np
import matplotlib.pyplot as plt
DIR_ = ['AL_results/projection_bad/projection_bad', 'AL_results/projection_good/projection_good',
'AL_results/p_projection_bad/p_projection_bad', 'AL_results/p_projection_good/p_projection_good']
LABEL = ['AL-PFP with bad demo', 'AL-PFP with bad demo','SAL with ba... |
import cv2
import imutils
from imutils.video import FPS
import argparse
import serial
import time
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--tracker", type=str, default="mosse",
help="OpenCV object tracker type")
args = vars(ap.parse_args())
OPENCV_OBJECT_TRACKERS = {
"csrt": cv2.TrackerCSRT_create,... |
# phuong thuc dem mot phan tu trong list xuat hien bn lan
a= [1,2,3,4,5,6]
c = a.count(2)
print(c)
# index dua ra vi tri cua phan tu trong list
d = a.index(3)
print(d)
# copy : sao chep 1 list tuong tu
list_moi = [2,3,4,5]
#clear : xoa moi phan tu
#append: them phan tu
list_them = list_moi.append([5,6])
print(list_moi... |
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> L = []
>>> type(L)
<class 'list'>
>>> L = ['red', 'green', 12, 45.6, True, False, ['a', 'b', 'c']]
>>>
>>> # Accessability : subscripting
>>>... |
# -*- coding:utf-8 -*-
"""
作者:xiaodingrong
日期:2021年10月21日
"""
get_number = int(input("Please input a number: "))
for column in range(0,get_number):
for rank in range(0,column+1):
print("*",end="")
print("") |
# Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# 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 ... |
# coding=utf-8
from lxml import etree
from Queue import Queue
import threading
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from bs4 import BeautifulSoup
import json, re, cto
from models import Train, Train_course, Course_lesson
from cto import Login
login = Login()
session = login.login... |
# -*- coding: utf-8 -*-
import openpyxl
from loyolaCD import employee as E
def get_info(filename, new, wb, ws):
#save data from filename
tmp = filename.split('_')
tmp2 = tmp[2].split('.')
new.student_num = tmp[1]
new.name = tmp2[0]
new.major = ws['E22'].value
n... |
from collections import defaultdict
from random import randint
# Bucket Sort
# Time: O(n + klogk) ~ O(n + nlogn)
# Space: O(n)
class BucketSort(object):
def topKFrequent(self, words, k):
counts = defaultdict(int)
for ws in words:
for w in ws:
counts[w] += 1
b... |
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import traceback
import logging
from django.db import models
from django.contrib.contenttypes.models import ContentType
from chroma_core.lib.job import job_log
from ch... |
# paramiko需要通过pip下载
import paramiko
# import time的目的是为了保证不会因为输入命令或者回显内容过快而导致SSH终端速度跟不上,仅能显示部分命令,而netmiko已经自动解决了此问题
import time
def qytang_ssh(ip, username, password, port=22, cmd='dis cu\n'):
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(parami... |
import torch
import torch.nn as nn
import torch.nn.functional as F
# Define LPD_Net
class LPD_Net(nn.Module):
def __init__(self, LayerNo):
super(LPD_Net, self).__init__()
self.name = "LPD_Net"
self.LayerNo = LayerNo
self.filter_size = 3
self.conv_size = 32
self.et... |
#!/usr/bin/python
import sys
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
# Example using a Raspberry Pi with DHT sensor
pin = 4
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0... |
from django.urls import path
from lineab.views import LineaCreate, LineaList, LineaUpdate, LineaDelete, linea_list_total
app_name = 'lineab'
urlpatterns = [
path("registrar/", LineaCreate.as_view(), name="registrar_linea"),
path("listar/<int:id>", LineaList.as_view(), name="listar_linea"),
path('listaDe... |
# [Prefix-Sum]
# https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/
# 1893. Check if All the Integers in a Range Are Covered
# History:
# 1.
# Jul 19, 2021
# You are given a 2D integer array ranges and two integers left and right.
# Each ranges[i] = [starti, endi] represents an inclusive ... |
import logging
from django_filters import rest_framework as filters
from rest_framework import mixins, status
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.permissions import AllowAn... |
#!/usr/bin/python
# This does not do anything useful: it just wastes a random
# amount of time to produce a random result.
import os
import random
import sys
i = int(sys.argv[1])
DIR = os.path.expanduser('~/tmp/example')
resultfile = os.path.join(DIR, "result-%u" % i)
random.seed(i)
j = 0
K = 9
L1 = range(K)
L2 = ... |
import logging
import torch.nn as nn
import torchvision.models as tvmodels
logger = logging.getLogger(__name__)
from ..tresnet import TResnetM, TResnetL, TResnetXL
from ..vision_transformer import *
def create_model(args):
"""Create a model
"""
model_params = {'args': args, 'num_classes': args.num_class... |
import pickle
class SessionService:
def __init__(self):
self.SESSION_FILENAME = ".session"
def save_program_parameters(self, cmd):
with open(self.SESSION_FILENAME, 'wb') as f:
pickle.dump(cmd, f, pickle.DEFAULT_PROTOCOL)
def load_last_program_parameters(self):
with op... |
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class AdsManagerUpdateStructureCommand:
client_manager_id: str
client_customer_id: str
edit_details: List
campaign_id: Optional[str] = None
ad_group_id: Optional[str] = None
keyword_id: Optional[str] = None
|
import logging
import pickle
class HumanClassification:
'Class ensures that all human input wont be lost after changing for instance word tokenization.'
def __init__(self, pickle_filename):
self._logger = logging.getLogger()
self.filename = pickle_filename + '.pickle'
self.classification = {}
de... |
import random
N = 15
L = 10.0
sigma = 0.1
n_configs = 100
for config in range(n_configs):
x = []
while len(x) < N:
x.append(random.uniform(sigma, L - sigma))
for k in range(len(x) - 1):
if abs(x[-1] - x[k]) < 2.0 * sigma:
x = []
break
print(x)
|
#!/usr/bin/env python3
# -*-encoding: utf-8-*-
"""
модуль з функціями для лінійної апроксимації
розв'язання системи лінійних рівнянь проводиться методом квадратного кореня
"""
import numpy as np
import random
from numpy import sign
from math import sqrt
def print_system(a, b):
"""
Виводить на екран систему... |
import pygame
import pygame.midi
pygame.init()
pygame.midi.init()
for x in range(0, pygame.midi.get_count()):
print pygame.midi.get_device_info(x)
inp = pygame.midi.Input(1)
while True:
if inp.poll():
print inp.read(1000)
pygame.time.wait(10) |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 21 12:51:47 2017
@author: juang
"""
from difflib import SequenceMatcher
from utils import normalize, similar
from dateutil import parser
def Repetidos(Lista, Influ):
co=0
IndRep=list();
for m in range(1,len(Lista)):
for n in range(0,m):
... |
from pandas.core.frame import DataFrame
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
import time
st.sidebar.title("streamlit 入門")
st.write("ゆいこさん こんばんは")
st.write("プログレスバーの表示")
"start!!"
latest_iteration = st.empty()
bar = st.progress(0)
for i in... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "operating-humor",
"metadata": {},
"outputs": [],
"source": [
"# USAGE\n",
"# python train_model.py --embeddings output/embeddings.pickle \\\n",
"#\t--recognizer output/recognizer.pickle --le output/le.pickle\n",
"\n... |
from django import forms
class admin_user_form(forms.Form):
error_css_class = 'error'
username=forms.CharField(max_length=90)
|
#!/usr/bin/python3
'''
Top-level script to start the deployment language processor ('depl')
Created on Oct 15, 2016
Arguments:
model : Name of deployment model file to be processed
@author: riaps
'''
from riaps.lang.depl import main
if __name__ == '__main__':
main(True)
|
from flask import Blueprint, request, jsonify
from api.models import User, Blacklist
from api.global_functions import response_message, get_user
from api.v1.validation import check_email, check_password, check_name
from flask_cors import CORS, cross_origin
auth = Blueprint('auth', __name__)
'''Implementing Register, l... |
import sys
sys.path.append('utils/')
from data_utils import *
import argparse
parser = argparse.ArgumentParser(
description="Train a seq2seq model and save in the specified folder.")
parser.add_argument(
"-f",
dest="ori_file",
type=str)
parser.add_argument(
"-r",
dest="ref_file",
type=st... |
"""empty message
Revision ID: 0bf2391a921d
Revises: 91c22e93edd7
Create Date: 2017-06-17 14:58:04.986219
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0bf2391a921d'
down_revision = '91c22e93edd7'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import requests
import pprint
payload = {}
r = requests.get('https://api.acrcloud.com/v1/monitor-streams/11578/results?access_key=ACCESS_KEY&limit=5')
pprint.pprint(r.json()) |
import tensorflow as tf
import pretrain
import datasource
from bert_parts import layers
# config和pretrain的是一样时,可以读取预训练模型的bert层参数
config = {
'seq_max_len': 100,
'vocab_size': 7364,
'embedding_size': 128,
'num_transformer_layers': 6,
'num_attetion_heads': 8,
'intermediate_size': 32
}... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import copy
import os
import time
import json
import logging
import torchvision
from torchvision import models, transforms
import mat... |
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model=Post
fields=('title','title_tag','author','body','header_image')
widgets={
'title':forms.TextInput(attrs={'class':'form-control'}),
'title_tag':forms.TextInput(attr... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import DetailView
from django.views.generic import ListView
from .models import Book
class BookListView(LoginRequiredMixin, ListView):
model = Book
context_object... |
# Список неприемлемых слов
bad_words = [
'порно',
'porno',
'pron',
'прон',
'порнуха',
'секс',
'эротика',
'хуй',
'пизда',
'ебля',
'влагалище',
'ебал',
'ебет',
'ебать',
'шлюха',
'минет',
'сосет',
'трах',
'кончает',
'кончил',
'выебал',
'вагина',
'жесткое порно',
'анал',
'милфа',
'трахнул',
'инце... |
from tkinter import *
import datetime
import pandas as pd
from generateWindow_5 import *
from generateWindow_6 import *
# stallList = pd.read_csv('stallList.csv')
allStallMenu = pd.read_csv('stallMenu.csv')
# Author: Le Quang Anh
def showMenu(frame, stallMenu, meal):
''' Input:
1) frame: the frame... |
import itertools
T = int(raw_input())
Trees = {}
def generate_match(winner, N):
def get_next_level_element(el):
if el == 'R':
return ['S', 'R']
elif el == 'S':
return ['S', 'P']
elif el == 'P':
return ['P', 'R']
def get_next_level(cur_level):
... |
# -*- coding: utf-8 -*-
"""Unit-tests for pyfun/core/chebfun.py"""
from __future__ import division
from operator import __add__
from operator import __mul__
from operator import __neg__
from operator import __pos__
from operator import __sub__
from operator import truediv
binops = [__add__, __mul__, __... |
# This file is part of the Reproducible Open Benchmarks for Data Analysis
# Platform (ROB).
#
# Copyright (C) 2019 NYU.
#
# ROB is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Helper methods for workflow template parameters."""
fr... |
import datetime
from urllib.error import URLError
import xmltodict
from django.db import transaction
from Bio import Entrez
from bioseq.models.Taxon import Taxon, TaxonName
from bioseq.models.Term import Term
from bioseq.models.Ontology import Ontology
from bioseq.models.Bioentry import Bioentry
from bioresources.mo... |
import mxnet as mx
import mxnet.ndarray as nd
data_shape = 304
batch_size = 32
rgb_mean = nd.array([123, 117, 104])
def get_iterators(data_shape, batch_size):
"""256, 32"""
train_iter = mx.image.ImageDetIter(
batch_size=batch_size,
data_shape=(3, data_shape, data_shape),
... |
from django.shortcuts import render
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import auth
from models import Reply_Thread, Reply, UserData
from django.core.mail import send_mail
from forms import ReplyForm
import outmail
def base(request):... |
def merge_sort(arr):
fir = arr[:len(arr)//2]
las = arr[len(arr)//2:]
#print(fir, las)
if min(len(fir), len(las)) == 1:
# print([min(int(fir[0]), int(las[0]))])
li = []
while (any(fir) and any(las)):
if fir[0] < las[0]:
li.append(fir.pop(0))
... |
#!/usr/bin/env python3
"""
.. module:: testReweighting
:synopsis: Tests the function of lifetime reweighting
.. moduleauthor:: Alicia Wongel <alicia.wongel@gmail.com>
"""
import sys
sys.path.insert(0,"../")
import unittest
from smodels.share.models import SMparticles, mssm
from smodels.theory.branch import Branch
f... |
#!/usr/bin/python3
def format_mac_to_type_1(addr):
"""
Transform MAC address to specified format.
example:
00-2B-67-59-47-0E --> 002b.6759.470e
00:2B:67:59:47:0E --> 002b.6759.470e
"""
mac_without_delimiter = addr.strip().replace("-", "").replace(":", "").lower()
mac = list()
... |
class Game:
def __init__(self):
self.throwBalls = []
def throwBall(self, number):
self.throwBalls.append(number)
def isStrike(self):
return self.throwBalls[self.ball] == 10
def isSpare(self):
return self.throwBalls[self.ball] + self.throwBalls[self.ball+1] == 10
d... |
#!/bin/python
import random
def available_moves(board):
zz = 0
moves = []
for v in (board):
if v == "_":
moves.append(zz)
zz+=1
return moves
def get_squares(board, player):
zz = 0
moves = []
for v in (board):
if v == player:
moves.app... |
#!/usr/bin/env python3
# -*-coding: utf-8-*-
"""The neptune class"""
from __future__ import (division, absolute_import, unicode_literals,
print_function)
import os
# Since these modules depend on the above variable, load after
from .system import System
from .local import Local
# do not impo... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Link
@contact: zheng.long@sfy.com
@module: service.py
@date: 2018-12-14
@usage:
$>nameko run service --broker amqp://guest:guest@localhost
$>nameko shell --broker amqp://guest:guest@localhost
"""
import yagmail
from nameko.rpc import rpc, RpcProxy
class Ma... |
import gym
import sys
import itertools
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
import common.tf_util as U
import logger
import deepq
from deepq.replay_buffer import ReplayBuffer
from deepq.utils import ObservationInput
from common.schedules import LinearSchedule
### 라이브러리 환... |
from __future__ import absolute_import, division, print_function
from datetime import datetime
from rfc822 import parsedate_tz, mktime_tz
from urlparse import urlparse
from time import time
from typing import Any, Optional # NOQA
from changes.utils.http import build_patch_uri
from .base import Vcs, RevisionResult, ... |
#!/usr/bin/python
from collections import Counter
import sys, subprocess, math, re, os, os.path, marshal
import parse_wiki_xml, annotator, listWikiSenses
"""
Counters for sense
'cur_word': Counter of cur words
'cur_word_pos': Counter of POS for cur word
'context_words': Counter of how often a word is a context word... |
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# import datasets (images: 55,000, test: 10,000, validation: 5,000)
## images: 784 (28*28 pixels) values between 0 and 1
## labels: 10 one-hot vector
def main():
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
s... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Recursively find :file:`info` and :file:`pickle` files within a directory
This module can be called from the shell, it will recursively look for
:file:`info` and :file:`pickle` files in the current working directory::
$ python pathtococo/bbob_pproc/findfiles.py
S... |
import threading
import time
from playsound import playsound
import pyttsx3
import random
import warnings
warnings.filterwarnings("ignore")
engine = pyttsx3.init()
def bgm():
playsound('music.mp3')
t_bgm = threading.Thread(target=bgm) # 后台播放bgm
t_bgm.start()
word1 = ['Python、', 'Java、', '数据库、', '.Net、', 'G... |
import functools
def rsetattr(obj, attr, val):
pre, _, post = attr.rpartition('.')
return setattr(rgetattr(obj, pre) if pre else obj, post, val)
def rgetattr(obj, attr):
return functools.reduce(getattr, [obj]+attr.split('.'))
|
https://leetcode.com/problems/add-binary/
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = ""
carry = 0
n1 = len(a)
n2 = len(b)
if n2 > n1:
a = '0'*(n2-n1) + a
elif n1 > n2:
b = '0'*(n1-n2) + b
for i in range(... |
import time
import pytest
from selenium import webdriver
@pytest.mark.baidu
class TestBaidu:
def setup_method(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
self.base_url = "http://www.baidu.com/"
"""pytest.mark.parametrize 多参数"""
@pytest.mark.parametrize(... |
from dataclasses import dataclass
from project_management.entities.task import Task
from project_management.basecamp3 import util
from datetime import datetime, timezone
@dataclass
class Basecamp3Task(Task):
due_date: str = None
created_date:str = None
def __post_init__(self):
if not (self.due_d... |
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, then pick the next
song to be the one with the lowest file size not already picked, repeat
... |
import logging
logging.basicConfig(level=logging.INFO)
def partition(array, start, end):
p_idx = start
p = array[p_idx]
print('p -> array:', array)
while start < end:
while start < len(array) and array[start] <= p:
start = start + 1
while array[end] > p:
end = ... |
#!/usr/bin/python3
##############################################################################
# (c)Copyright 2019 IBM Corp.
#
# 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... |
from estructuras import *
def ucs(g, s, m):
frontera = ColaPriorizada()
frontera.put(0, s)
anteriores = {}
anteriores[s] = None
acumulado = {}
acumulado[s] = 0
while not frontera.esVacia():
actual = frontera.get()
if actual == m:
break
for vecino in g.... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'UDP server' #doc comment
__autor__ = 'myth'
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#绑定端口:
s.bind(('127.0.0.1',9999))
print('Bind UDP on 9999...')
while True:
#接收数据:
data,addr = s.recvfrom(1024)
print('Received from %s:%s.' %addr)
s.sendto(b... |
class Solution:
def binSearch(self, nums, target):
if len(nums) <= 0:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
... |
#own for loop and range function
def special_for(iterable):
iterator=iter(iterable)
while True:
try:
print(iterator)
print(next(iterator))
except StopIteration:
break
special_for([1,2,3])
#own range function
class MyGen():
current=0
d... |
import math
def productPrimeFactors(n):
product = 1
# Handle prime factor 2 explicitly so that
# can optimally handle other prime factors.
if (n % 2 == 0):
product *= 2
while (n%2 == 0):
n = n/2
# n must be odd at this point. So we can
... |
import requests
class InvalidTokenException(Exception):
pass
class Config(object):
def __init__(self, github_token):
if not github_token:
raise InvalidTokenException()
self.github_token = github_token
self.github_username = self.fetch_github_username()
def fetch_gith... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.