text stringlengths 38 1.54M |
|---|
import asyncio
import aiohttp
from bs4 import BeautifulSoup
from sanic.exceptions import Forbidden, ServerError, Unauthorized
from yarl import URL
from spider.ua import ua
def auth_server_dump_cookies(session: aiohttp.ClientSession) -> dict:
""" 导出 AuthServer 的 Cookies """
cookies = {}
for cookie in ses... |
from framework import entities, numbers, movement, timers, shapes, flags, pathfinding
import ai_squad_director
import ai_factions
import ai_debugger
import mapgen
import zones
import life
import ai
import time
def get_nearest_entity_in_list(entity, entity_list):
_nearest_entity = {'entity': None, 'distance': 0}
... |
#!/usr/bin/python3.7
import sys
def longest(dice):
if len(dice) <= 4:
return len(dice) # pick them all
# if more than 4.. i can pick at least 4.
# I can pick a 5th if there's at least one >= 5
# I can pick a 6th if i can pick
dice = sorted(dice)
ans = 1
for d in dice:
if d >= ans:
ans +=... |
from services.tradehub import TradeHub
from control.sanctioned_customer import SanctionedCustomer
class Runner(object):
def __init__(self):
self.trade_service = TradeHub()
self.queue = self.trade_service.get_trades()
def execute_queue(self):
for element in self.queue:
sanct... |
# 62. Unique Paths
# https://leetcode.com/problems/unique-paths/
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# in grid[m][n], the number of paths = grid[m-1][n] + grid[m][n-1]
grid = [([0]*(n+1)) for line in range(m+1)]
grid[1][1] = 1
for i in range(1, m+1... |
# Testing
import csv
import random
from os import path
user_orderlist = []
absolute_path = path.abspath(path.curdir)
def table_reservation():
total_tables = 20
reserved_tables = random.randint(0, 21)
empty_tables = total_tables - reserved_tables
if total_tables == reserved_tables:
... |
from flask import Flask, jsonify, send_from_directory, render_template
import pandas as pd
import os
app = Flask(__name__)
CSV_URL = 'https://data.cityofnewyork.us/resource/uvpi-gqnh.json'
CSV_PATH = 'data.csv'
def get_df():
#If the data is already saved to disk
if os.path.isfile(CSV_PATH):
re... |
#!/usr/bin/env python3
def bits(hexc):
return bin(int(hexc, 16))[2:].zfill(4)
def run(lengths):
position = 0
skip = 0
sequence = list(range(256))
for _ in range(64):
for l in lengths:
for i in range(l // 2):
now = (position + i) % len(sequence)
later = (position + l - 1 - i) % len(sequence)
s... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 11:18:30 2020
@author: Martin Jessen
"""
import matplotlib.pyplot as plt
import os
import numpy as np
from skimage import transform
from PIL import Image
def load_images_from_folder(folder):
images=[]
for filename in os.listdir(folder):
img = Image.op... |
import numpy as np
from pprint import pprint
import os
class Stats():
def top_level_stats(self, path):
count = 0
file_exts = []
for dirname, _, filenames in os.walk(path):
for filename in filenames:
count += 1
file_ext = filename.split(".")[-1]... |
import pandas
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from... |
from bs4 import BeautifulSoup
import networkx as nx
import json
from urllib.request import urlopen
from datetime import datetime
import time
import pandas as pd
import numpy as np
class TweetJob:
def __init__(self):
self.twitter_handle = None
self.follower_limit = 1
self.foll... |
# 程序文件Pex17_2.py
import numpy as np
from numpy.random import randint, rand, shuffle
from matplotlib.pyplot import plot, show, rc
a = np.loadtxt("../data/Pdata17_2.txt")
xy, d = a[:, :2], a[:, 2:];
N = len(xy)
w = 50;
g = 10 # w为种群的个数,g为进化的代数
J = [];
for i in np.arange(w):
c = np.arange(1, N - 1);
shuffle(c)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('assets', '0001_initial'),
('accounts', '0001_initial'),
]
operations = [
migrations... |
import sys
from pprint import pprint
sys.stdin = open('input.txt', 'r')
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def isField(i, j):
return 0 <= i < n and 0 <= j < n
def bfs(i, j):
global max_road
visited = [(i, j)]
queue = [(i, j)]
road = 1
while queue:
temp = queue[:]
queue ... |
# encoding: utf-8
BATCH_SIZE = 50
def readMNIST():
import torchvision
from torchvision import transforms
import torch.utils.data as data
train_data = torchvision.datasets.MNIST(
root='./MNIST/',
train=True, #training set
#transform=torchvision.transforms.ToTensor(),#converts a PI... |
from diagnnose.attribute.decomposer import ShapleyDecomposer
from diagnnose.attribute.explainer import Explainer
from diagnnose.config import create_config_dict
from diagnnose.models import LanguageModel
from diagnnose.models.import_model import import_model
from diagnnose.tokenizer import create_tokenizer
from diagnno... |
# pylint: disable=no-self-use
class TestOverview:
def test_get_overview(self, client):
response = client.get("/overview")
assert response.status_code == 200
assert response.mimetype == 'text/html'
assert '<img src="' in response.get_data(as_text=True)
|
# -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals, \
with_statement
import logging
import argparse
from jenkinstask import taskload
from jenkinstask.api import JenkinsApi
from jenkinstask.confFile import generator, loadConfig
logger = logging.getLogger(__na... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 University of Liège
#
# 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
#
# ... |
while 1:
ess1 = int(input("Essay 1(/22) :"))
ess2 = int(input("Essay 2(/22) :"))
ess3 = int(input("Essay 3(/22) :"))
pres = int(input("Oral Presentation(/8) :"))
diss = int(input("Student Led Discussion(/7) :"))
ascr = int(input("ASCR(/10) :"))
refl = int(input("Self-progress Reflecti... |
# Copyright 2019 The TensorFlow Authors. 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 required by applica... |
import unittest
class MyTestCase (unittest.TestCase):
def test_something ( self ):
self.assertEqual (True, False)
if __name__ == '__main__':
unittest.main ()
|
"""
Postfix relay domains extension forms.
"""
from django import forms
from django.core.urlresolvers import reverse
from django.http import QueryDict
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib import events
from modoboa.lib.form_utils import DynamicForm, DomainNameField, TabFor... |
# -*- coding: utf-8 -*-
# author : anthony
# version : python 3.6
import os
import json
import time
from core import db_handler
from conf import settings
from core import logger
def login_required(func):
"""
验证用户是否登陆
:param func:
:return:
"""
def wrapper(*args, **kwargs):
if args[0].... |
import re
import numpy as np
import matplotlib.pyplot as plt
import h5py
text = open("/Users/mac/Desktop/ca1_step1_input_data.txt")
#处理字符
line1 = text.readline()
#print(line1)
line2 = text.readline()
#print(line2)
line1 = line1.replace("#","")
line1 = line1.replace(" ","")
line1 = line1.replace("\n","")
line1 = line... |
# -*- coding: utf-8 -*-
import subprocess
import win32api
import win32con
from pykeyboard import PyKeyboard
import time
__author__ = 'Kan'
k = PyKeyboard()
# 启动qq
qq_exe = r"C:\Program Files (x86)\Tencent\QQ\Bin\QQ.exe"
subprocess.Popen([qq_exe])
time.sleep(5)
# 定位qq密码输入框
'''windll.user32.SetCursorPos(969, 583)'''
... |
# encoding:UTF-8
########################################################################
class AndRule:
""""""
#----------------------------------------------------------------------
def __init__(self, *args):
"""Constructor"""
self.rules = args
#----------------------------... |
# -*- coding: utf-8 -*-
import requests_mock
from lib.UpcomingProductsHandler import UpcomingProductsHandler
from tests.fixtures import Fixtures
class TestUpcomingProductsHandler:
def test_can_handle(self):
uph = UpcomingProductsHandler()
assert uph.can_handle(Fixtures.event('!upcoming')) == (Tru... |
# Generated by Django 2.0 on 2018-03-15 18:39
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),
]
opera... |
import requests
import datetime
import time
import json
from bs4 import BeautifulSoup
Terkini={
"time":"",
"kategori":"",
"judul":"",
"waktu":""
}
data = []
page = requests.get("https://www.republika.co.id/")
obj = BeautifulSoup(page.text,'html.parser');
for headline in obj.find_al... |
# Generated by Django 3.2.4 on 2021-07-06 00:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_alter_post_fecha_creacion'),
]
operations = [
migrations.AlterField(
model_name='categoria',
name='id',... |
#Start Import Area
from os import system, name
from time import sleep
import time, pyautogui
from bronzium_opener import text
import bronzium_opener
#End Import Area
print(text.INTRO)
input('\nPress ENTER to continue...')
def clear():
# Windows
if name == 'nt':
_ = system('cls')
# Uni... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pylab
from mpl_toolkits.mplot3d import Axes3D
import random
stock1 = pd.read_csv('C:/Users/ECEM YAMAN/Desktop/MATLAB/FİNANSAL ANALİZ/marketing_data.csv') # dosyamızı okuduk
stock3 = stock1.drop(stock1.columns[[0]], axis=1, inplace... |
#
# (C) 2013 coolo@suse.de, openSUSE.org
# Distribute under GPLv2 or GPLv3
#
# Copy this script to ~/.osc-plugins/ or /var/lib/osc-plugins .
# Then try to run 'osc checker --help' to see the usage.
def _group_find_request(self, package, opts):
url = makeurl(opts.apiurl, ['request'], "states=new,review,declined&pro... |
#!/usr/bin/env python
#
# Author: andrew.galloway@nexenta.com
# Created On: 2013-09-26
# Last Updated: 2016-11-10
# Description: ingestor python script template
#
import sys
import os
from functions import * # include generic functions file
#
# name of this script
# could be filename, or something... |
# This class define the Monte-Carlo agent
class MC_agent(object):
# [Action required]
# WARNING: make sure this function can be called by the auto-marking script
def get_action(self, state_policy, epsilon):
max_val = np.argmax(state_policy)
rand_val = np.random.uniform(0,1)
if rand_val < (1-epsilon... |
import bot_header
def main(cmd):
print("main")
print(":\n %d LP requests\n %d messages received\n %d messages sent."
"\n %s API requests done"
"\n %s API requests failed"
"" % (
bot_header.LP_REQUESTS_DONE,
bot_header.LP_MESSAGES_RECEIVED,
... |
import json
from django.shortcuts import render
from django.views import generic
from django.contrib.auth import mixins
class PredictionHub(mixins.LoginRequiredMixin, generic.TemplateView):
template_name = 'prediction_hub.html'
|
import json
from django.http import HttpResponse
from curling.lib import HttpClientError
import mock
from nose.tools import eq_
from test_utils import RequestFactory, TestCase
from ..views import ProxyView, NoReference
class FakeView(ProxyView):
def get(self, request, *args, **kwargs):
raise NoReferen... |
'''
>>> base_convert(2555,2)
'100111111011'
>>> base_convert(42,2)
'101010'
>>> base_convert(0,2)
'0'
>>> base_convert(2555,10)
'2555'
>>> base_convert(0,10)
'0'
>>> base_convert(4711,10)
'4711'
>>> base_convert(2555,16)
'9fb'
>>> base_convert(0,16)
'0'
>>> base_convert(10,16)
'a'
>>> base_convert(2555,36)
'1yz'
>>> ba... |
from urllib.parse import quote_plus as urlencode
from urllib.request import urlopen
import json
def words(context):
""" Convert word array to string. """
return " ".join(context['word'])
def make_url(corpus, req_type, param):
""" Build a BLS URL. """
paramparts = [urlencode(k) + "=" + urlencode(str(v)... |
from reconocer_rostros_cam import *
from reconocer_rostros_imagen import *
from codificar_rostros import *
import os
while True:
print("""\n1. Entrenar modelo
2. Reconocer una imagen
3. Reconocer imágenes
4. Reconocer video
5. Salir\n""")
op = input("Elija una opción: ")
if op not in ['1', '2', '3', '4', '5']:
... |
from django.test import TestCase
from django.core.urlresolvers import resolve
from partials.controller.user_management import user_collection_partial, add_user_partial
class UserManagementPartialTestCase(TestCase):
def test_user_collection_partial_resolve_correctly(self):
resolved_func = resolve('/part... |
# -----------------------------------------------------------------------
"""
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example :
Input : 1 -> 5 -> 4 -> 3
Returned list : 1 -> 3 -> 4 -> 5
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
... |
from mod_user import User
class Privileges:
def __init__(self):
self.privileges = ['can add post', 'can delete post', 'can ban user']
def show_privileges(self):
print("Privileges are as follows:")
for privilege in self.privileges:
print(privilege)
class Admin(User):
... |
N = int (input())
list =[]
i = 1
while i<=N:
M =int(input())
list.append(M)
i= i +1
for j in list:
if j %2 ==0 and j < 0:
print("EVEN NEGATIVE")
elif j % 2==1 and j <0:
print("ODD NEGATIVE")
elif j == 0:
print("NULL")
elif j % 2 ==1:
print("ODD POSITIVE")
... |
J, K, L = raw_input().split()
J = int(J)
K = int(K)
L = int(L)
count = 0
for i in range(J, K+1):
if i % L == 0:
count = count + 1
else:
continue
print count |
# Generated by Django 2.0.7 on 2018-09-23 21:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ficha', '0014_auto_20180923_1823'),
]
operations = [
migrations.AlterField(
model_name='ficha',
name='exfisico',
... |
#! /usr/bin/env python
import sys
import numpy as np
sys.path.append('./')
# my module
from xyzStruct import xyzStruct
from xyzTraj import xyzTraj
from bMolShape import bMolShape
def process_traj():
"""
process traj of xyz file
"""
line = raw_input("enter the filename (xyz format): \... |
#!/usr/bin/python3
import socket
import sys
# 创建 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = '120.79.47.182'
# 设置端口好
port = 8081
# 连接服务,指定主机和端口
s.connect((host, port))
# 接收小于 1024 字节的数据
msg = s.recv(1024)
print (msg.decode('utf-8'))
sendmsg = bytes(socket.gethostname(), enco... |
from __future__ import print_function
from pyimagesearch.cbir import HSVDescriptor
from imutils import paths
import progressbar
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help = "Path to the directory that contains the images to be indexed")
ap.add_argum... |
#!/usr/bin/env python
import sys
import json
from datetime import datetime
from collections import OrderedDict
import copy
import operator
from itertools import chain
def split_data(line):
rec = line.strip().split("|")
current_student = rec[0]
class_name = rec[1]
current_date = datetime.strptime(rec[2]... |
#!/usr/bin/python3
## HumanShell created by Rohit Kumar . This is Cross platform it will work on both Linux and Windows ##
import os
import platform
import smtplib, ssl
try :
import twilio
import pyttsx3
#import pyaudio
#import speech_recognition as sr
except:
print("install required libr... |
class ConsensusStage:
def __init__(self):
# TODO
return
# types:
# preVote
# preCommit
# newRound
# nil (fraud or no response) |
# -*- coding: utf-8 -*-
# flake8: noqa
"""Then step definitions."""
from behave import then
from behave.runner import Context
from tests.functional.steps.then_impl import (
fab_company_should_be_verified,
fab_should_be_asked_about_verification_form,
fab_should_not_see_collaborator,
fab_should_see_case_... |
#!/usr/bin/env python3
import sys
import os
import svgwrite
import math
class Target:
def __init__(self, name, pid):
self.name = name
self.pid = pid
self.start = None
self.end = None
self.booking_index = None
def duration(self):
assert self.end >= self.start
... |
#!/usr/bin/env python
import re
pattern = re.compile(r'world')
match = pattern.match('hello world!')
search = pattern.search('hello world!')
if match:
print match.group()
else:
print 'match failed'
if search:
print search.group()
else:
print 'search failed'
|
#!/usr/bin/env python
# USAGE: temp.py
# Michael Chambers, 2017
# from sys import stdin
import sys
import itertools
def func(vals):
return(vals[0] + vals[1] * vals[2] ** 2 + vals[3] ** 3 - vals[4])
def main():
x = [2,3,5,7,9]
for i in itertools.permutations(x):
# print(func(i))
if func(i) == 399:
print(i)... |
import unittest
from popular_artifacts import popular_artifact_generator
def test_get_maven_artifacts():
results = popular_artifact_generator.get_maven_artifacts()
assert len(results) > 0
def test_get_file_stats_for_artifacts():
download_list = popular_artifact_generator.get_file_stats_for_artifacts()
... |
liste = [['chat'], ['chien'], [['.']], ['voiture']]
c = 0
for i in range(4):
print(liste[c][0])
c+=1
|
from django.urls import path
from question import views
urlpatterns = [
# 書籍
path('question/<int:category_id>/<int:question_no>', views.QuestionView.as_view(), name='question'),
path('category', views.CategoryView.as_view(), name='category'),
path('answer_result/<int:category_id>/<int:question_id>/<int... |
from clikit.api.io import Input
from clikit.api.io import Output
from clikit.formatter import AnsiFormatter
from clikit.formatter import PlainFormatter
from clikit.io import ConsoleIO
from clikit.io.input_stream import StandardInputStream
from clikit.io.output_stream import ErrorOutputStream
from clikit.io.output_strea... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QSDM
Species distribution modelling support for the QGIS Processing toolbox
-------------------
begin : 2014-03-31
copyright : (C) 2014 by M... |
"""
Python RPC Client for Discord
-----------------------------
By: qwertyquerty and LewdNeko
"""
from .client import Client
from .presence import Presence
from .exceptions import *
__title__ = 'pypresence'
__author__ = 'qwertyquerty'
__copyright__ = 'Copyright 2018 qwertyquerty'
__license__ = 'MIT'
__v... |
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
I = Image.open('a.png')
a = np.asarray(I)
plt.imshow(a) |
from django.contrib import messages
from django.db.models import Count
from django.shortcuts import get_object_or_404, redirect, render
from .models import Collection, Person, Face
def index(request):
collection = Collection.objects.first()
if not collection:
return render(request, 'face/index.html')
... |
# Generated by Django 3.2.4 on 2021-06-22 13:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapi', '0002_auto_20210615_1628'),
]
operations = [
migrations.CreateModel(
name='Room_detail',
fields=[
... |
#coding:utf-8
from __future__ import division, print_function, unicode_literals
import os
import sys
if sys.version_info.major == 2:
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append(os.path.dirname(__file__))
import pyexts
# pyexts = os.path.dirname(__file__) + "/pyexts"
# for root, dirs, files... |
m=int(input())
if m>=80 and m<=90:
print("A Grade")
elif m>=60 and m<80:
print("B grade")
elif m>=40 and m<60:
print(" C Grade")
else:
print("Fail")
|
"""
Created on Tue Feb 13 10:04:09 2018
@author: davidhull
"""
### Exercise 1 ###
class Person:
def __init__ (self, name, email, phone, friends =[], count = 0):
self.name = name
self.email = email
self.phone = phone
self.friends = []
self.count = count
def gre... |
from .go_out import Option
from . import _test
def test_from_menu():
with _test.screenshot("go_out_menu.png") as img:
res = Option.from_menu(img)
support_card, character = sorted(res, key=lambda x: x.position[1])
assert support_card.type == Option.TYPE_SUPPORT, support_card.type
assert suppo... |
import sys
import requests
import threading
class LocalAgent:
def __init__(self, machine_no, time_interval, increment):
self.machine_no = machine_no
self.time_interval = time_interval
self.current_temp = 200
self.increment = 1
self.incremental_value = increment
self.set_interval(self.send_te... |
from django.urls import path, re_path, reverse_lazy, include
from django.contrib.auth import views as auth_views
from accounts.views import activate_view
from . import views
from django.conf import settings
urlpatterns = [
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name... |
#-*- coding: utf-8 -*-
'''
Created on 15 de mai de 2017
@author: alisson
'''
import pandas
import math
import numpy
import keras
from keras.models import Sequential
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.layers.core impo... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
import time
import os
MAX_WAIT = 10
class NewVisitorTest(StaticLiveServerTestCase):
def setUp(self)... |
# -*- coding: utf-8 -*-
""" ---------------------------------------------------------
バーコードリーダから入力された値の数をカウントします。
このアプリの権利は全て影山裕一(兵庫県たつの市)及びAlice Electronicsに帰属します。
アプリ及びソースコードはBSD 3-Clause Licenseで公開しています。
お問い合わせはEmail: contact@alicle.jp へお願いします。
--------------------------------------------------------- """
# -... |
a=[10,20,30,40,60]
print(a[0])
b=['a','b','c']
print(b[1])
del (a[0])
# delete the values in the list
a.insert(5,87)
for i in a:
print (b)
print(len(a))
c=("a","b","def")
print(c)
#these are tuples. we cant add elements to it
print(a)
|
$NetBSD$
Fix path.
--- SABnzbd.py.orig 2020-02-12 20:18:12.258920844 +0000
+++ SABnzbd.py
@@ -42,6 +42,10 @@ import ssl
import time
import re
+# Force python to load the patched version of cherrypy included with the port,
+# instead of any version that may be installed otherwise.
+sys.path.insert(0,'@PREFIX@/shar... |
import argparse
from collections import namedtuple
from pathlib import Path, PurePosixPath
import tempfile
from subprocess import check_call
from urllib.parse import urlparse
import os.path
import sys
Repo = namedtuple('Repo', 'url branch')
def sr(repo):
return 'git://studentrobotics.org/{}.git'.format(repo)
REP... |
from django.conf.global_settings import SECRET_KEY
import base64
from itsdangerous import URLSafeTimedSerializer
class Token:
def __init__(self):
self.security_key = SECRET_KEY
self.salt = base64.encodebytes(self.security_key.encode(encoding='utf-8'))
def generate_email_active_token(self, use... |
class Solution(object):
def maxRotateFunction(self, A):
sum1,n=sum(A),len(A)
if n==0:
return 0
max_index=temp=sum (A[i]*i for i in range(n))
for i in range(n-1,0,-1):
temp=temp+sum1-n*A[i]
max_index=max(max_index,temp)
return max_index
s=So... |
#Print odd numbers between 1 and 10
number_count = 0
while number_count < 9:
should_run = True
number_count = number_count + 1
if number_count%2 == 1:
print(number_count)
|
#临床参数+基因+预测转移时间
import pandas as pd
from pandas import read_csv
import pandas as pd
from sklearn import datasets
from pandas.plotting import scatter_matrix
from matplotlib import pyplot
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection ... |
#!/usr/bin/env python3
"""
melt - a visual cat-like file viewer with syntax highlighting
supporting 2-file views
The syntax highlighting is done with the bat tool
that you need to install first (see https://github.com/sharkdp/bat).
Author: Laszlo Szathmary, alias Jabba Laci, 2019
E-mail: jabba.laci@gmail.com... |
# coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import unittest
from programy.storage.stores.nosql.mongo.dao.oob import OOB
class OOBTests(unittest.TestCase):
def test_init_no_id(self):
oob = OOB(name="test", oob_class="test.oobclass")
self.assertIsNotNone(oob)
self.assertIsNone(oob.id)
self.assertEqual("test", oob.name)
... |
from django.contrib.auth.hashers import check_password
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from django.conf import settings
import smtplib
def mailer(reciever,token):
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.starttls()
mail.ehlo()
# change this
mail.login(se... |
from datetime import datetime, timezone
from django.contrib.auth import user_logged_in
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.db.models.signals import post_save
from django.dispatch import receiver
class Player(models.Model):
u... |
from collections import namedtuple
SqueakProfile = namedtuple(
"SqueakProfile",
"profile_id, profile_name, private_key, address, sharing, following, whitelisted",
)
|
import queue
import threading
import urllib.request
def getUrl(q, url):
print('getUrl(' + url + ') called from a thead.')
q.put(urllib.request.urlopen(url).read())
theurls = ["http://google.com", "http://google.de", "http://google.ca"]
threadQueue = queue.Queue()
for u in theurls:
t = threading.Thread... |
import urllib2
import csv
from bs4 import BeautifulSoup
def get_seasons( number_of_seasons ):
i = 1
all_seasons = []
while i < number_of_seasons + 1:
all_seasons.append(scrape_page(i))
i += 1
write_seasons(all_seasons)
def scrape_page( season_num ):
imdb_page = 'https://www.im... |
def main():
min_val = 1
max_val = 1000
int_list = list(range(min_val, max_val+1,1))
sum = 0
for num in int_list:
val = num ** num
sum += val
print('The sum is:', sum)
digits = [int(x) for x in str(sum)]
i = -1
last_ten= []
while i >= -11:
digit = digits... |
from PythonFiles import constants as cs, initialization as init
########################################################################################
# FUNCTIONS USED DURING GAME LOOP UPDATES
########################################################################################
def gradual_status_bar_fluctuatio... |
import tkinter as tk
import socket
import time
import re
HOST = '192.168.71.128'
PORT = 29999
command = [
'robotmode',
'get serial number',
'get loaded program',
'programState'
]
# Connect to port 29999 (dashboard)
def dashboard_connection():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.... |
import time
from selenium import webdriver
# webdriver from Chrome
PATH = "C:\Program Files (x86)\chromedriver.exe"
chrome = webdriver.Chrome(PATH)
# Link to the page
PAGE = "https://www.bestbuy.com/site/madden-nfl-21-playstation-4-playstation-5/6407594.p?skuId=6407594"
chrome.get(PAGE)
purchaseButton = F... |
'''
Created on Jan 29, 2015
@author: Jerry
'''
def repeat(word, number):
"""
return the word with the first part of it repeated
if it is a valid part to repeat. The part to be
repeated must be repeated "number" times.
If the first letter is not a vowel, and the third
letter is a vo... |
# Generated by Django 2.2.4 on 2019-11-27 01:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogs', '0024_user_otp_secret'),
]
operations = [
migrations.AlterField(
model_name='post',
name='content',
... |
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
land = set()
res = 0
def dfs(r, c):
if (r, c) in land:
land.remove((r, c))
dfs(r-1, c)
dfs(r+1, c)
dfs(r,... |
import heapq
from queue import Queue
def get_int():
return int(input())
def get_line():
return input().strip()
def get_ints():
return [
int(i)
for i in input().split()
]
class NumberStream:
def __init__(self, num_list):
self.num_list = num_list
self.index = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.