index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
997,300 | 49ab4b2fb16cbcace513dca65f2305ad1512bf78 | def common_letters(string_one,string_two):
common=[]
for one in string_one:
if (one in string_two) and not (one in common):
common.append(one)
return common
print(common_letters("manhattan","san francisco"))
|
997,301 | fffcd26acddac85a193151231f8f832e9dfc2138 | #Libreria
import base64
##Encriptado base 64
#Texto para encriptar
texto = "cifrado base 64"
#Funcion que encripta
encriptar = base64.b64encode(texto.encode("utf-8"))
textoEncriptado = str(encriptar, "utf-8")
##Desencriptado base 64
#Funcion que desencripta
desencriptar = base64.b64decode(textoEncripta... |
997,302 | 0d2b3d3e6b4bef6b292da8ce539dce13f33b5a83 | from flask import request
from api_handlers import users
from app_init import app
from util import POST_REQUEST, ParsedRequest, api_response, json_response
# user registration route
# POST request
@app.route("/users/register/", **POST_REQUEST)
@app.route("/register", **POST_REQUEST)
@api_response
def register():
... |
997,303 | c9f92ef5280aaa4a4330513c2a906bfe9f4e4921 | #coding=utf-8
import sys
from twisted.internet.protocol import ServerFactory
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from twisted.internet import reactor,task
from ss import cfgshell
import db
from twisted.cred import checkers,credentials,portal
from zope.interface import Interfa... |
997,304 | d29deb748bcc6ad7a8c4be40410668d2b3014766 | # Template used to print a Trello board. Uses pystache.
board_template = """
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="style... |
997,305 | d8bff60e49d099361e04af3e52846edfe116d5d8 | # 9613
from itertools import combinations
from math import gcd
count = int(input())
gcd_list = []
for i in range(count):
number_list = list(map(int, input().split()))
gcd_sum = 0
number_list = number_list[1:]
for a, b in combinations(number_list, 2):
gcd_sum += gcd(a, b)
gcd_list.append(g... |
997,306 | 9955ced6cb3379840006cd9ca438b7a5bbf8bd5e | import unittest,paramunittest
import warnings
from common.testdata_utils import TestdataUtils
from common.requests_utils import RequestsUtils
case_info = TestdataUtils().get_testcase_data_list() # excel数据
# case_info = TestdataUtils().get_testcase_data_list_by_mysql() #mysql数据
@paramunittest.parametrized(
*case_in... |
997,307 | 4805cf482dc5fb4d193a4d624c64efd7d157d660 | prnt 'hello'
|
997,308 | be1b3eee0ac331a43100d71c2574b9e1f9130a04 | from collections import OrderedDict
import sys
python_ver = sys.version_info[0]
def main():
table = {}
for i in range(24):
key = chr(ord('a') + i)
value = chr(ord('A') + i)
table[key] = value
print(len(table))
print(table)
assert('a' in table)
if 'a' in table:
... |
997,309 | 41afde9165bd9425503b2cb7ef61e5616068f80d | '''
리스트의 항목 중 유일한 값으로만 구성된 리스트를 반환하는 함수를 정의하고
이 함수를 이용해 리스트의 중복 항목을 제거하는 프로그램을 작성하십시오.
출력
[1, 2, 3, 4, 3, 2, 1]
[1, 2, 3, 4]
'''
def arr_l(no_arr):
y_arr=list(set(no_arr))
return y_arr
l=[1,2,3,4,3,2,1]
arrange_l=arr_l(l)
print(arrange_l)
|
997,310 | d118e9275143c691d717093c64304d00d53fb224 | #raise (lanza exepciones de forma voluntaria)
dato = int(input("ingresa cuantas veces has estado en la carcel :"))
if dato <=1 :
print("FELICIDADES QUEDASTE REGISTRADO")
else:
raise ValueError ("EL PROGRAMA CALLO INESPERADAMENTE")
#se coloca cualquier nombre de error reservado y se le le
#puede asignar un me... |
997,311 | f4023185c263dc41721b27cba685dc32639eaf34 | import os
import torch
import numpy as np
import pandas as pd
from scipy.misc import imresize
from PIL import Image
from skimage import io, transform
from skimage.color import rgba2rgb
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
class RetinaDataset(Dataset):
def __ini... |
997,312 | bb9c443e40439d79b848e12c292b57d947518d07 | #!/usr/bin/env python
'''
Check access to Azure API
'''
__author__ = "Leonid Vasilyev, <vsleonid@gmail.com>"
import json
import sys
import os
import azure.servicemanagement as smgmt
def print_locations_and_services(sms):
print "Available locations & services:"
print "=============================="
... |
997,313 | 6851dc5eaa74b5c439cf352c3ab801ea5cb2e8c0 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
from flask import Flask, url_for, request
from sqlalchemy import text
import cgi
arguments = dict()
args = cgi.FieldStorage()
for key in args.keys():
arguments[key] = args[key].value
from dbhelper import query_database, result_to_json
import cgihelper
# Marks a... |
997,314 | 8fdac789dbde85ef80535e6cc1a687db1a49a839 | import sys, getopt, os, errno, re, string
opts, args = getopt.getopt(sys.argv[1:], "i:o:")
for opt, arg in opts:
if opt == '-i':
inFile = arg
elif opt == '-o':
outFile = arg
input = open(inFile, "r").readlines()
arr = []
i = 0.0
sum = 0.0
sumOfSquares = 0.0
for line in input:
newLine = re... |
997,315 | 875740d6e65fc9fbe55b2905d0b148591c9a5c1c | #! /usr/bin/env/ python3
# -*- coding:utf-8-*-
#meetstation > sensor > bh1750 > meet.py
from bin import conf, db
import logging
import threading
import time
import sensor.bh1750.bh1750 as bh1750
class Meet:
def __init__(self, rowid=0, args=[]):
self.logObj = logging.getLogger('meetlog')
self.rowid = rowid
sel... |
997,316 | ad1a1ffc94ad4761a0ecf250efbc57dc811646b0 | from typing import List, Tuple, Iterable
from gamestate import GameState
N: int = 3
PuzzleBoard = Tuple[Tuple[int, ...], ...]
Move = Tuple[int, int, str]
State = Tuple[PuzzleBoard, str]
GOAL_STATE: GameState = GameState(board=((0, 1, 2), (3, 4, 5), (6, 7, 8)))
class InvalidPuzzleError(Exception):
'''
Error ... |
997,317 | 8846023ee26b40b36e0d3c3bd6140e6898579052 | from . import FrameUtils, Lowered, Code
|
997,318 | 354f9a431b6e37ab425ffe686fdafe9e689a06f5 | # implement an algo to determine if a string has all unique characters
def all_unique(input_string):
if len(set(input_string)) != len(input_string):
return False
else:
return True
# better version
# return len(set(input_string)) == len(input_string)
def all_unique_without_data(input_... |
997,319 | 194db06ce5a196d98c6d746e30df4a7b92f30676 | #predicted
print(-6 // 4)
print(6. // -4) |
997,320 | 7354bc0769b4397c123761707cd472c2545add5e | from Compiler.Globals import *
"""
This file holds functions that generate general Brainfuck code
And general functions that are not dependent on other objects
"""
# =================
# Brainfuck code
# =================
def get_readint_code():
# res, tmp, input, loop
# tmp is used for multiplication
... |
997,321 | 34e6312163a1ba1c5aae225623fc2cdb764c08f7 | import re
# file_to_search = open('us-500.csv', 'r')
# print(file_to_search.readlines())
# newfile = open('mailist.txt', 'w')
with open("us-500.csv") as f:
for line in f:
email_search = re.findall(r'([\w.-]+@+[\w.]+)', line)
print(email_search)
# email_list.append(email_search)
# pri... |
997,322 | ae20ee322ac8805604eb9489c8931ad51ea46e60 | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
import traceback
import time
class... |
997,323 | 9b2a1a43c469704a8a5c98a19568775e6fc939ca | """
Management of InfluxDB 0.8 users
================================
(compatible with InfluxDB version 0.5-0.8)
.. versionadded:: 2014.7.0
"""
def __virtual__():
"""
Only load if the influxdb08 module is available
"""
if "influxdb08.db_exists" in __salt__:
return "influxdb08_user"
retu... |
997,324 | d8721068beba3bd96bdf0376cbf7f8a838cd13ce | word = input().upper()
arr = [0] * 26
for i in word:
arr[ord(i) - 65] += 1
maxIndex = arr.index(max(arr))
arr.sort()
print("?" if arr[25] == arr[24] else chr(maxIndex + 65)) |
997,325 | bf68336ab8e234e4b705c9b2e4545f0d90d95422 | """__author__ = 余婷"""
"""
在python中,函数就是一种特殊的类型。声明函数的时候,其实就是在声明类型是function的变量。
变量能做的事,函数都可以做
1.函数给其他变量赋值
"""
if __name__ == '__main__':
# 1.使用一个变量给另外一个变量赋值
a = 10
b = a
# 声明一个函数func1(声明了一个函数变量func1, func1就是一个变量)
def func1():
print('hello python')
# c也是一个函数
c = func1
func1()
... |
997,326 | a9647f7dcd06a992d492a82b596193f104501190 | from sklearn.ensemble import RandomForestClassifier
import numpy as np
domainlist = []
class Domain:
def __init__(self,_name,_label):
self.name = _name
self.label = _label
def returnData(self):
return processData(self.name)
def returnLabel(self):
if self.label == "notdga":
return 0
e... |
997,327 | 66a80808b57354612ea2322cb72dd8f19d32ff45 | # -*- coding: utf-8 -*-
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, UserManager
from django.db import models
from django.utils import timezone
from juck.image.models import JuckImage
from django.conf import settings
class State(models.Model):
class Meta:
ve... |
997,328 | d107eac3a3f4a2e720495bb55f16d90bf5fdc073 | import os,sys
import argparse
from collections import Counter
import re
import pdb
filters_detailed = [
("url" , [re.compile(r'^https?[:/]{1,3}(www\.)?[a-z]+(\.?[a-z]+\/?)+.*?$',re.UNICODE),
re.compile(r'^[wW]{3}\.[a-zA-Z]+(\.?[A-Z]+\/?)+.*?$',re.UNICODE),
re.compile(r'^([a-zA-Z][^@])[a-zA-Z.... |
997,329 | b596f049572f2a11d05a10d8e723686f825fcfbd | from django.urls import path, re_path
from .views import (
blog_post_list_view,
blog_post_detail_view,
blog_post_create_view,
blog_post_update_view,
blog_post_delete_view,
)
urlpatterns = [
path('', blog_post_list_view, name='list'),
re_path(r'^create?/$', blog_post_create_view, name='creat... |
997,330 | 317c80fbb69810b3526dbe0dbc186bfec384bfe8 | from django.contrib import auth as django_auth
import base64
from django.http import JsonResponse
from .models import Event,Guest
import time,hashlib
#用户认证
def user_auth(request):
get_http_auth=request.META.get('HTTP_AUTHORIZATION','b')
#获取HTTP认证数据,如果为空,将得到一个空的byte对象
auth=get_http_auth.split()
#通过split... |
997,331 | a800672925ae76411ffac965cca4003dc4a3312b | with open('Q24.txt', 'r') as f:
prompt = f.read()
prompt = prompt.strip()
prompt = prompt.split('\n')
bugs = []
for i in prompt:
bugs.append([])
for j in i:
bugs[-1].append(j)
def get_bug(i, j, bugs):
if 0 <= i < len(bugs) and 0 <= j < len(bugs[i]):
return 1 if bugs[i][j] == '#' el... |
997,332 | 331ef6dfa6e375d16d5f2dc5a5fb79d4bc41295f | #!/usr/bin/env python3
from os import listdir
from os.path import isfile, join
import os
import shutil
def sort_files_in_a_folder(mypath):
"""
A function to sort the files in a download folder
into their respective categories
"""
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
... |
997,333 | 03ef93cb0f9d29e42cf787ab46618f1ada8d6c7f | #! /usr/bin/env python2.7
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# Christoph Gierling
from datetime import date
def store(tracks, country, date):
from sqlalchemy import create_engine, Table, MetaData, Integer, String, Column
engine = 'sqlite:///track_stats_services.db'
db = create_eng... |
997,334 | aed4f5dc4fd84295fc67ca9fff76ade500017f9c | import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__), "img")
WIDTH = 500
HEIGHT = 600
FPS = 60
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set... |
997,335 | 53c626d7614534c759dd186a1bb5da2883f0f367 | # coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.webdriver.support.ui import Select
# レース名入力
race_name = input('レース名を入力してください:')
#ブラウザを開く
driver = webdriver.Chrome()
# netkeibaのデータベースを開く
driver.get('http://db.netkeiba.com/?rf=navi')
#... |
997,336 | d2a98f4a7cb145ccc474f851ed1cc1f1379f4ae0 | '''
Need to update
'''
import cv2
import imutils
import json
import numpy as np
import os
import keras
import numpy as np
from keras.models import Model
from keras.layers import Input, add
from keras.layers.core import Layer, Dense, Dropout, Activation, Flatten, Reshape
from keras.layers.convolutional import Conv2D... |
997,337 | 1ab324ae4b3c03913262b5cd86b31083d7d118c2 | import numpy as np
def hastings_step(f,x,step,p):
xp = x + step
start = -f(x)
end = -f(xp)
alpha = end-start
out = np.copy(x)
i = (p < alpha)
out[i] = xp[i]
frac = np.mean(i)
return [out,f(out),frac]
def ham_hastings_step(f,g,x,mom,r,eps,L):
Q = np.copy(x)
P = ... |
997,338 | 976236a825b932f8a181fdaf172156f7f6475456 | #sys.argv[1] should be the path of the file with input sequences
#sys.argv[2] should be the path of the file where to save sequence
import sys
import azimuth.model_comparison
import numpy as np
def getAzimuth(sequences):
predictions = azimuth.model_comparison.predict(sequences, None, None)
return predictions
seque... |
997,339 | 249bb51d04a08e065f3f1139812bb51b4cf6882f | """
File: figureS08.py
Purpose: Generates figure S08.
Figure S08 analyzes heterogeneous (2 state), uncensored,
single lineages (no more than one lineage per population).
"""
import numpy as np
from .figureCommon import (
getSetup,
subplotLabel,
commonAnalyze,
pi,
T,
E2,
max_desired_num_cell... |
997,340 | 7694e7339e95ec5d7a437fa12363c5537265ef7a | import os
import yaml
def load_config_or_die(config_dir, config_basename):
config = dict()
for filename in ['models.yaml', 'policies.yaml', 'agents.yaml']:
filepath = os.path.join(config_dir, filename)
with open(filepath, 'r') as file:
config.update(yaml.safe_load(file))
basepa... |
997,341 | 29686bf0ae1b6ac880f30a9d99e329a1127dc6aa | import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
class BasePU:
@staticmethod
def _make_propensity_weighted_data(x,s,e,sample_weight=None):
weights_pos = s/e
weights_neg = (1-s) + s*(1-1/e)
if sample_weight is not None:
weigh... |
997,342 | 8a552e5e7f68eae05d9e50fb7b88152ac74544d3 | from _typeshed import Incomplete
from influxdb_client.service._base_service import _BaseService
class LegacyAuthorizationsService(_BaseService):
def __init__(self, api_client: Incomplete | None = ...) -> None: ...
def delete_legacy_authorizations_id(self, auth_id, **kwargs): ...
def delete_legacy_authoriz... |
997,343 | b8698b49a1b35c78a72ec12dd0db661798333750 | import os
from . import BaseTest
from click.testing import CliRunner
from virl.cli.main import virl
from virl.swagger.app import app
try:
from unittest.mock import patch
except ImportError:
from mock import patch
class Tests(BaseTest):
@patch("virl.cli.swagger.commands.subprocess.Popen", autospec=False)
... |
997,344 | 16bf8345840f72bb3a50c03ca986c47870bf5ffb | import pygame.display
|
997,345 | 818f8e9f1cc29c1274bae9788e0f6820674863e9 | from .cms_metatags import CMSMetaTags
__all__ = [
CMSMetaTags,
]
|
997,346 | edd66ab7bc8def989337f3754c6c61175a5435f5 | #!/usr/bin/env python
# coding: utf-8
# In[16]:
import numpy as np
import netsquid as ns
from netsquid.qubits.qubitapi import *
'''
function:
Generate a GHZ set with customized length and entangled qubits.
input:
num_qubits: Numbers of qubits in a column.
num_sets: Numbers of qubits in a raw.
output... |
997,347 | d9b69c27742fdc5ea2aa923e210214b226d8ebd7 | # 爬取小说
import requests
from bs4 import BeautifulSoup
from python.study.other.config.logger import Logger
from time import sleep, time
from python.study.other.config.readconfig import MyConfig
import python.study.other.util.fileutil as fileutil
import python.study.other.util.strutil as strutil
logger = Logger().get_lo... |
997,348 | 39d68c07de4f7e2f5d78aa9de395f0ea03ac02a5 | import math
from wpilib.joystick import Joystick
from wpilib.buttons.joystickbutton import JoystickButton
from commands.extendall import ExtendAll
from commands.retractall import RetractAll
from commands.extendfront import ExtendFront
from commands.extendback import ExtendBack
from commands.retractfront import RetractF... |
997,349 | 5ae4a4dc869198bebbb7ffbb015dae04ae4adb78 | from peewee import *
from datetime import datetime
base = SqliteDatabase('adressess.db')
fields = ['Id', 'Description', 'Add date', 'Is done', 'Remove']
class BaseModel(Model):
class Meta:
database = base
class Person(BaseModel):
login = CharField(null=False, unique=True)
password = CharField()
... |
997,350 | 8c787aec2d78e704a4b6b335c640534afc46deba | import os
import pandas as pd
import streamlit.components.v1 as components
_RELEASE = True
if not _RELEASE:
_custom_table = components.declare_component(
"custom_table",
url="http://localhost:3001",
)
else:
parent_dir = os.path.dirname(os.path.abspath(__file__))
build_dir = os.path.joi... |
997,351 | 7e638f7c0ee34a6ea44083808d4c3f691704bcf6 | from typing import Tuple, Union, Dict, List
from jsonpath_ng import parse
Mapping = Dict[str, Union["Mapping", str]]
def get_from_list(ls, index=0):
try:
return ls[index]
except IndexError:
return None
def map_jsonpath(source: dict, mapping: Mapping):
res = {}
mappings: List[Tuple[... |
997,352 | f67434f911508507d5412ccf5156da2f46975981 | from heapq import heappop,heappush
def dijkstra(s,n,edge):
"""
始点sから各頂点への最短距離を返す
Parameters
----------
s : int
視点とする頂点(0-indexed)
n : int
グラフの要素数
eage:list
グラグ
Returns
-------
dist :list
始点sから各頂点への最短距離
"""
dist=[float("inf")]*n
dist[s]=0
used=[-1]*n
hq=[[dist[s],s]]
... |
997,353 | 5385f05d189a9359f9d63d9f82c63bdcf6198928 | def make_quesadilla(protein, topping="sour cream"):
quesadilla = f"Here is a {protein} quesadilla with {topping}"
print(quesadilla)
make_quesadilla("chicken")
make_quesadilla("beef", "guacamole")
make_quesadilla(topping="ranch dressing", protein="chicken")
|
997,354 | e1a42c8541d4c8be2d211148c11e500de42a5999 | #!/usr/bin/env python
import csv
#import seaborn as sns
import numpy as np
#import matplotlib.mlab as mlab
#import matplotlib.pyplot as plt
import sys
#from matplotlib import rcParams
fid_list = [0,1,2,3,4,5,6,7,10,11,12,13,
22,23,24,28,29,33,35,37,39,40,
41,42,43,44,45,48,49,50,51,52,
... |
997,355 | f0f630f6edc4f473ff2cfd01e6941768721ae30b | from django.contrib.sessions.backends.db import SessionStore
from django.shortcuts import render, redirect
from django.conf import settings
from rest_framework import authentication
from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_fra... |
997,356 | e6a41fce674ecde154461ce4f9fb990df22bfdf3 | def trap(arr):
left = max(arr)
copy = arr
arr.remove(left)
right = max(arr)
total = 0
for i in range(len(copy)):
total = total + min(left,right) - copy
trap([3,0,2,0,4])
|
997,357 | f36d8d821fcc1e8c77c04fbc1fbfb127d9691c3d | import re, functools, unittest
# RECURSION EXERCISES
#
# Each one of these can be solved using recursion
##### Problem 1 #####
# choose via Pascal's Triangle
# The "choose" operation in combinatorics means the number of ways you can
# choose k items. For example: The number of unique pairs of socks you can
# gener... |
997,358 | 2473dc0697d2d46d9f8d6b8d0dc5a613f12acb97 | import json
basecamp_project_id = '4075148'
basecamp_url = f'https://3.basecampapi.com/{basecamp_project_id}'
class NotFoundError(Exception):
pass
def get_software_project(sess):
proj_resp = sess.get(f'{basecamp_url}/projects.json')
projects = proj_resp.json()
for proj in projects:
if proj... |
997,359 | 6f058c5f0b248eead29043f36c05c0237b94aa70 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import xlrd
import glob
import time
import openpyxl
import subprocess
from optparse import OptionParser
def cell2str(data):
if data == None or data == '':
return '.'
elif isinstance(data, (int, long, float)) :
return str(data)
else:
return da... |
997,360 | b26a2602c837702b737f84b4a55d240839725333 | # Copyright 2015 Google Inc. 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 applicable law or a... |
997,361 | 8eb9e92bf9db8b1c55028d2eaecd34fd2c4e1958 | from torch import autograd, eye, argmax, multinomial
from torch.nn import functional as F
class GreedySelection(autograd.Function):
@staticmethod
def forward(ctx, scores):
"""Select the weight corresponding to the highest score"""
idx = argmax(scores, dim=-1)
scores_net = eye(scores.si... |
997,362 | fc04f626cabdab50f8f1d15f2c356ecb3e10a0d2 | """Field mappings for Access Preliminary Technical Data"""
from cases.forms import (
AttachmentImportForm,
PersonImportForm,
PreliminaryCaseImportForm,
PreliminaryFacilityImportForm,
)
from django_import_data import OneToOneFieldMap, ManyToOneFieldMap, FormMap
from importers.converters import (
co... |
997,363 | 8828de27eaebfe8b5853cbb39440650da9cbf4a6 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright(c) 2019 Nippon Telegraph and Telephone Corporation
# Filename: JuniperDriverMX240.py
'''
Individual section on driver (JuniperDriver's driver (MX240))
'''
import re
import ipaddress
from lxml import etree
import copy
import traceback
import GlobalMo... |
997,364 | 676ad6182800d6d47f8f59d09abd5dabd487bed5 | #! /root/anaconda3/bin/python
print(dir(str))
|
997,365 | df2f1f8f2bbb1d8efe1010a178521331c9a25980 | from random import *
l=['R','P','S']
def game(n):
x = randint(1,3)
if (x==1):
k='Rock'
if (x==2):
k='Paper'
if (x==3):
k='Scissors'
if(n==l[0] and (x==3)):
print("You Win")
print("Computer: "+ k)
return ()
if(n==l[1] and x==1):
print("You Win")
print("Computer: "+ k)
return ()
if(n==l[2] an... |
997,366 | c84f84358424e7ecd513aee4fc3649d62dda4696 | # -*- coding: utf-8 -*-
import scrapy
class InfoqSpider(scrapy.Spider):
name = 'infoq'
allowed_domains = ['infoq.com']
start_urls = [
'http://infoq.com/cn/AI/articles'
]
def parse(self, response):
articles = response.xpath("//ul[@class='l l_large']/li")
... |
997,367 | 19940524f035f02ee4de1b29326e0c794d62ddf6 | # -*- coding: utf-8 -*-
from WeatherForecast import WeatherForecast
data = WeatherForecast.get_weather("980-0871")
print(WeatherForecast.calc_average(data)) |
997,368 | 6105d1bb87fd720d4269870593579b33e58abbfc | # Copyright (c) 2016. Mount Sinai School of Medicine
#
# 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 applicable law o... |
997,369 | d4cd020ecebb745d721e9f2d37f7e99841fa8304 | #coding=utf-8
import copy
import tensorflow as tf
import lr_base
def tfTrain(data_x, data_y):
# 构造线性模型
tf_w = tf.Variable( tf.zeros([1, len(data_x)]) )
tf_y = tf.matmul(tf_w, data_x)
loss = tf.reduce_mean( tf.square( tf_y - data_y ) )
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minim... |
997,370 | 55669dd15c77ef5f8126e13a41182bb5212b5cab | import pickle as pkl
import numpy as np
import tensorflow as tf
from beam import BeamSearchDecoder
import re
from tensorflow.contrib import rnn
import os
from copynet import CopyNetWrapper
import string
with open("/data/shrey/copynet/pickle_data.txt",'r') as file:
dic = pkl.load(file)
with open("/data/shrey/copynet... |
997,371 | 384de4ad03fa2426e4c2d4e50ca35bc8d425a3f3 | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '10/7/2020 4:12 PM'
import nltk
grammar = nltk.CFG.fromstring("""
NP -> NP NP
NP -> NP PP
NP -> Det N
PP -> P NP
NP -> 'Mexico'
NP -> 'funding'
Det -> 'the'
N -> 'wall'
P -> 'with'
""")
tokens = ['funding', 't... |
997,372 | a84c322bdce85217b9a7bf14d0c0d5c6e3290d6e | import sys
from . import logger
from . import env
from . import client
from . import db
from . import filters
from . import processors
from . import output
def main():
logger.init_logger()
try:
env.init_env()
client_obj = client.init_client()
coupons = client.handle_pagination(client... |
997,373 | ab15ceae545a87d1b49403ca26030ed1d6d0f3c7 | from django.conf.urls import url
from . import views
app_name = 'service'
urlpatterns = [
# Home page
url(r'^$', views.main_home, name='main_home'),
# Login authentication
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
# Sets up the user profile ... |
997,374 | 71e03b8d614ff8d36968b66b3356c70fbf40ad83 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-19 03:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tutorial', '0004_auto_20171105_1914'),
]
operation... |
997,375 | 42b68c4bd598e299315b4bae575e16b0a1999c59 | # Values of team with names to pass to scraper function in correct format
teams = {
'Arizona Cardinals': 'Arizona',
'Atlanta Falcons': 'Atlanta',
'Buffalo Bills': 'Buffalo',
'Baltimore Ravens': 'Baltimore',
'Carolina Panthers': 'Carolina',
'Cincinnati Bengals': 'Cincinnati',
'Cleveland Br... |
997,376 | afb758aead5eae6638e5de5843ed58bf5df8da50 | import csv
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
import datetime
import re
import sys
debug = True
if len(sys.argv) < 2 :
print "Usage: python <progName> <csvFile> <includeIfCC>"
sys.exit(2)
input_filename = sys.argv[1]
qbo_template = "qbo_template_CC.qbo"
acct_id = "9999"
is_C... |
997,377 | e6593de411f0d33d02170c61f77a017be42d0f08 | import requests
import json
import os
import datetime
timestamp = datetime.datetime.utcnow().isoformat()
jsonRequest = { "results":[
{
"fileIds":[],
"keywords": [ "2018springhackathon" ],
"programName":"InsightCM Build",
"properties": {
"currentStatus": os.environ['JOB_BASE_NAME']
... |
997,378 | 7c5f2cd7e345a14e968cb7287cd3c4b840c49d18 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import init_param, normalize, loss_fn
from config import cfg
class Block(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride):
super(Block, self).__init__()
self.n1 = nn.BatchNorm2d(i... |
997,379 | 3effa5b90bbcfae4236261698086ce80a160918c | import torch.nn as nn
import torch.nn.functional as F
class MultiLayerPerceptron(nn.Module):
def __init__(self, input_size):
x= 64
super(MultiLayerPerceptron, self).__init__()
self.fc1 = nn.Linear(input_size,x)
self.fc2 = nn.Linear(x, 1)
#Overfit example
def forward(... |
997,380 | 526771b84dcb18a5a96aa32e072f0e9778d80e7f | # datetime module stores information about dates and times in module classes
# it differs from time module which works with floats for representing seconds since epoch
import datetime
import time
import textwrap
# dates are represented with datetime.date class
# creating date instance:
dt=datetime.date(2008,12,15) ... |
997,381 | c7d79e00f4211554a0055751c3d8fbfb519f1549 | import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
np.random.seed(100)
x = np.random.randint(0, 101, 50)
y = np.random.randint(0, 101, 50)
obj = go.Scatter(x=x, y=y, mode='markers', marker=dict(
size=12,
color='rgb(51,204,153)',
symbol='circle'), line=dict(width=2))
data = [o... |
997,382 | 71ebf6c892ec12e44758e84bf47ae11519eaed5a | # -*- coding: utf-8 -*-
import random
import math
inCircle = 0
distance = 0.0
for _ in range(1000):
x = 1.0 * random.randint(0, 1000) / 100
y = 1.0 * random.randint(0, 1000) / 100
if x * x + y * y > 100:
continue
else:
inCircle += 1
distance += math.sqrt(x * x + y * y)
print(di... |
997,383 | 3d926ccce8ec64060013db3ff5e981a9eb864066 | from collections import Counter
def convert_lists(l):
d = {}
if len(l) == 0:
return d
for item in l:
if item == "":
continue
item = item.split("_")[0]
d[item] = 0
return d
out = open("on_contig_summary_new.csv","w")
out.write("ID, Count, AMR, Num, Vir, Num , Plasmid, Num, Avg_Length, Sd_Length\n")
wi... |
997,384 | eafe85cf9037c5ed1716d17eed2e4dd9ac9b3ef0 | '''
Created on 28 Feb 2014
@author: siva
'''
import sys
if __name__ == '__main__':
tom_relation_file = sys.argv[1]
tom_types_file = sys.argv[2]
freebase_schema_files = sys.argv[3:]
schema = {}
types = set()
for schema_file in freebase_schema_files:
for line in open(schema_file):
... |
997,385 | 8a92823913aae3eb4b816ac362c6215157e20551 | #!usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import scipy
def previous_endpoint(endpoint, linkvec, mainvec):
length = np.linalg.norm(linkvec)
before_pos = endpoint - length * mainvec
return before_pos |
997,386 | c34034a0e230cd20c01bba9ede45b415f2f060a0 | VOCAB_SIZE = 10000
# 测试数据参数
DATA_SIZE = 6949708
TEST_DATA_SIZE = int(6949708)
# 文件路径
DATA0_PATH = '../../model_data/error_origins.'+str(DATA_SIZE)
DATA1_PATH = '../../model_data/data1.'+str(DATA_SIZE)
DATA2_PATH = '../../model_data/data2.'+str(DATA_SIZE)
DATA3_PATH = '../../model_data/nears.'+str(DATA_SIZE)
TARGET_P... |
997,387 | 8ba9259eeb420e3b71a4d4680093feaa8f88cef9 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 18 22:05:02 2017
@author: levy
"""
import os,time
from wifi import Cell, Scheme
from selenium import webdriver
interface='wlp110s0'
#
#net_state=os.system('ping 58.211.162.30 -c 2')
#if net_state:
# print 'false'
#else:
# print 'ok'
#pip=os.... |
997,388 | 8cf35d68910409106415e87f6193bb2e0ae58f6a | Receive_Data()
Verify_Data()
a=test()
Report_Errors()
|
997,389 | d6c2a45b04364872b78c54c7d87e6e7fcad72885 | import random
import pygame
import os
CLOUD = pygame.image.load(os.path.join("../img/Other/Cloud.png"))
class Cloud:
def __init__(self):
self.X = 1280 + random.randint(800, 1000) # So it spawns outside of the screen , 1280 being the width
self.Y = random.randint(30, 80) # Random height
... |
997,390 | 83c6772f7b8efbf42a9989f7b2cdd5d08f51449a | # -*- coding: utf-8 -*-
import unittest
import json
import datetime
from speakers import timespeaker
from speakers.timezone import JST
class TestTimeSpeaker(unittest.TestCase):
"""TestTimeSpeaker
TimeSpeakerのunittest
"""
def test_create(self):
"""test_create
create関数からTimeSpeakerを取得するテス... |
997,391 | 437bcc07f163cef50052c06b145e58eaa9cb443b | from django.contrib import admin
# Register your models here.
from .models import Cliente, Comisionista, Costo, Movimiento, Regreso, Empresa
#admin.site.register(Cliente)
admin.site.register(Comisionista)
admin.site.register(Costo)
admin.site.register(Movimiento)
admin.site.register(Regreso)
admin.site.register(Empr... |
997,392 | d4f7d0305b13c8cd51c6aef83a90379ecedfc7b9 | # begin_generated_IBM_copyright_prolog
#
# This is an automatically generated copyright prolog.
# After initializing, DO NOT MODIFY OR MOVE
# ================================================================
#
# (C) Copyright IBM Corp. 2010,2011
# Eclipse Public License (EPL)
#
# ======================================... |
997,393 | 17f2462dc0e3519e77ab2b58a9bc714204f4f0d9 | import ply.lex as lex
_hextoint = False
tokens = (
"COLON",
"EQUAL",
"SEMICOLON",
"COMMA",
"LBRACE",
"RBRACE",
"LPAREN",
"RPAREN",
"LSQUARE",
"RSQUARE",
"COMMENT",
"INTEGER",
"INTEGER64",
"BOOLEAN",
"HEX",
"HEX64",
"FLOAT",
"STRING",
"NAME"
... |
997,394 | d8242b26faf0978b622d6c8e9ce49cd05c3a2f0a | from django import forms
from .models import Picture
class UserForm(forms.ModelForm):
class Meta:
model = Picture
fields = ['title', 'cover', 'Description']
|
997,395 | db4cd75d0089b6d0a3753197c606d3f0bf7c4f30 | from .aux_input import *
from .common import *
from .ctypes_ import *
from .device import *
from .device_data import *
from .door import *
from .enums import *
from .event import *
from .exceptions import *
from .main import *
from .param import *
from .reader import *
from .relay import *
from .sdk import *
from .tabl... |
997,396 | 643227247d3990671e338715ba1c93967529158d | import cv2
import numpy as np
img = cv2.imread("imori_noise.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.array([[0., 0., 1., 0., 0.], [0., 1., 2., 1., 0.],
[1., 2., -16., 2., 1.], [0., 1., 2., 1., 0.],
[0., 0., 1., 0., 0.]])
log = cv2.filter2D(img, -1, kernel)
cv2... |
997,397 | a5ecdd7ea2524f019fae09e68c82b2da283f1301 | from Pages.home_page import HomePage
from TestCase.base_test import BaseTest
class TestSetCategory(BaseTest):
def test_intro(self):
homepage = HomePage(self.driver)
homepage.test_set_category()
# python3 -m unittest TestCase.test_03_set_category
|
997,398 | d83d99ce026febcfa4994578837c4c093783f9b7 | from .datasets import Datasets
from .reshape import Reshape
from .reshape_config import ReshapeConfig
from .spark_io import SparkIO, SparkIOContext
from .spark_io_config import SparkIOConfig
from .table_name import TableName
__all__ = [
"Datasets",
"Reshape",
"ReshapeConfig",
"SparkIO",
"SparkIOCon... |
997,399 | 232ec02476da3a11cc8f5ab590ff0c099765f320 | def nm_suppression(boxes,scores,overlap=0.50,top_k=200):
cnt=0
keep = scores.new(scores.size(0)).zero_().long()
x1 = boxes[:,0]
y1 = boxes[:,1]
x2 = boxes[:,2]
y2 = boxes[:,3]
area = torch.mul(x2 - x1,y2 - y1)
tmp_x1 = boxes.new()
tmp_y1 = boxes.new()
tmp_x2 = boxes.new()
tmp_y2 = boxes.new()
tmp_w = box... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.