index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
2,300 | 5d3f7d74cf1cc2612d599c65393abed11181c981 | team = input("Wymien wszystkich czlonkow swojego zespolu: ").split(",")
for member in team:
print("Hello, " + member)
|
2,301 | 400f9b6fb0ab73a920e6b73373615b2f8d1103bb | #!/usr/bin/env python3
#coding=utf-8
"""
dfsbuild.py
单Git仓库多Dockerfile构建工具,提高了构建效率
快速使用:
chmod +x ./dfsbuild.py
只构建Git最近一次修改的Dockerfile
./dfsbuild.py -a auto -r registry.cn-shanghai.aliyuncs.com/userename
构建所有的Dockerfile
./dfsbuild.py -a all -r registry.cn-shanghai.aliyuncs.com/userename
构建特定的Dockerfile
./dfsbuil... |
2,302 | 3ba9ff00b0d6a2006c714a9818c8b561d884e252 | import boto3
import pprint
import yaml
#initialize empty dictionary to store values
new_dict = {}
count = 0
new_dict2 = {}
# dev = boto3.session.Session(profile_name='shipt')
mybatch = boto3.client('batch')
#load config properties
with open('config.yml') as f:
content = yaml.load(f)
# pprint.pprint(content) #to... |
2,303 | 255cdbce1f9f7709165b1a29362026ad92ba4712 | #day11
n = int(input("Enter a number: "))
c = 0
a,b = 0, 1
list = [a, b]
for i in range(2,n+1):
c = a+b
list.append(c)
a,b = b, c
print(n,"th fibonacci number is ",list[n])
|
2,304 | a6d5552fa0648fcf9484a1498e4132eb80ecfc86 | import sys, warnings
if sys.version_info[0] < 3:
warnings.warn("At least Python 3.0 is required to run this program", RuntimeWarning)
else:
print('Normal continuation')
|
2,305 | 502f405f48df92583757ebc9edb4b15910c1f76a | # Copyright (c) Facebook, Inc. and its affiliates.
from .build import build_backbone, BACKBONE_REGISTRY # noqa F401 isort:skip
from .backbone import Backbone
from .fpn import FPN
from .resnet import ResNet, ResNetBlockBase, build_resnet_backbone, make_stage
__all__ = [k for k in globals().keys() if not k.star... |
2,306 | d81e8478d60c9ee778e1aeb0dd7b05f675e4ecad | import pymarc
from pymarc import JSONReader, Field, JSONWriter, XMLWriter
import psycopg2
import psycopg2.extras
import time
import logging
import json
#WRITTEN W/PYTHON 3.7.3
print("...starting export");
# constructing file and log name
timestr = time.strftime("%Y%m%d-%H%M%S")
logging.basicConfig(filename=timestr ... |
2,307 | 8db952ba5bf42443da89f4064caf012036471541 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 11:51:49 2019
@author: Christian Post
"""
# TODO: row index as an attribute of Data?
# make iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace(... |
2,308 | c2069113f322c97e953fba6b9d21b90a8b13a066 | from django.apps import AppConfig
class BoletoGerenciaNetConfig(AppConfig):
name = 'boletogerencianet' |
2,309 | e4a66617adbe863459e33f77c32c89e901f66995 |
import numpy as np
class settings:
def __init__(self, xmax, xmin, ymax, ymin, yrange, xrange):
self.xmax = xmax
self.xmin = xmin
self.ymax = ymax
self.ymin = ymin
self.yrange = yrange
self.xrange = xrange
pass
def mapminmax(x, ymin=-1.0, ymax... |
2,310 | e5e516b6a39a6df03f1e5f80fe2d9e3978e856aa | # What is the 10 001st prime number?
primes = [2]
def is_prime(a, primes):
b = a
for x in primes:
d, m = divmod(b, x)
if m == 0:
return False
else:
return True
a = 3
while len(primes) <= 10001:
# There's something faster than just checking all of them, but this
... |
2,311 | 49f1b4c9c6d15b8322b83396c22e1027d241da33 | from tkinter import *
root = Tk()
ent = Entry(root)
ent.pack()
def click():
ent_text = ent.get()
lab = Label(root, text=ent_text)
lab.pack()
btn = Button(root, text="Click Me!", command=click)
btn.pack()
root.mainloop()
|
2,312 | 454fd88af552d7a46cb39167f21d641420973959 | # python2.7
#formats for oracle lists
import pyperclip
text = str(pyperclip.paste()).strip()
lines = text.split('\n')
for i in range(len(lines)):
if (i+1) < len(lines):
lines[i] = str('\'')+str(lines[i]).replace("\r","").replace("\n","") + str('\',')
elif (i+1) == len(lines):
lines[... |
2,313 | bc536440a8982d2d4a1bc5809c0d9bab5ac6553a | import os
import time
import uuid
import subprocess
# Global variables. ADJUST THEM TO YOUR NEEDS
chia_executable = os.path.expanduser('~')+"/chia-blockchain/venv/bin/chia" # directory of chia binary file
numberOfLogicalCores = 16 # number of logical cores that you want to use overall
run_loop_interval = 10 # seconds ... |
2,314 | 23c75840efd9a8fd68ac22d004bfe3b390fbe612 | from connect_to_elasticsearch import *
# returns the name of all indices in the elasticsearch server
def getAllIndiciesNames():
indicies = set()
for index in connect_to_elasticsearch().indices.get_alias( "*" ):
indicies.add( index )
print( index )
return indicies
|
2,315 | 614d6484678890df2ae0f750a3cad51a2b9bd1c6 | from django.contrib import admin, messages
from django.conf.urls import url
from django.shortcuts import render
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect, HttpResponse
from website_data.models import *
from website_data.forms import *
import logging
# Get an instance of ... |
2,316 | 730fc527f3d2805559e8917e846b0b13f4a9f6ee | from django.apps import AppConfig
class QuadraticEquationsSolverConfig(AppConfig):
name = 'quadratic_equations_solver'
|
2,317 | e6ac742eb74d5d18e4c304a8ea1331e7e16e403d | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
sum = 0
def sumNumbers(self, root):
def dfs(root,sofar):
... |
2,318 | 0f03ff63662b82f813a18cc8ece3d377716ce678 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/4
@function:
32. Longest Valid Parentheses (Hard)
https://leetcode.com/problems/longest-valid-parentheses/
题目描述
在给的字符串里面找到 最大长度的 有效 括号字符串
输入输出示例
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"... |
2,319 | 6f356840944e11f52a280262697d7e33b3cca650 | import cv2 as cv
img = cv.imread('images/gradient.png', 0)
_,th1 = cv.threshold(img, 127,255, cv.THRESH_BINARY)
_,th2 = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
_,th3 = cv.threshold(img, 127, 255, cv.THRESH_TRUNC) #freeze the pixel color after the threshold
_,th4 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO... |
2,320 | 38be4e75c2311a1e5a443d39a414058dc4d1879b | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def distribution():
##testing_results = pd.read_csv('https://raw.githubusercontent.com/dsfsi/covid19za/master/data/covid19za_timeline_testing.csv')
confirmed_results = pd.read_csv('https://raw.githubusercontent.com/dsf... |
2,321 | 2251a6064998f25cca41b018a383053d73bd09eb | #!/usr/bin/env python2.7
# Google APIs
from oauth2client import client, crypt
CLIENT_ID = '788221055258-j59svg86sv121jdr7utnhc2rs9tkb9s4.apps.googleusercontent.com'
def fetchIdToken():
url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token='
f = urllib.urlopen(url + urllib.urlencode(CLIENT_ID))
i... |
2,322 | c30b0db220bdacd31ab23aa1227ce88affb79daa | from __future__ import absolute_import, division, print_function
import time
from flytekit.sdk.tasks import python_task, dynamic_task, inputs, outputs
from flytekit.sdk.types import Types
from flytekit.sdk.workflow import workflow_class, Input
from six.moves import range
@inputs(value1=Types.Integer)
@outputs(out=T... |
2,323 | 4bb973b598a9c35394a0cd78ed9ba807f3a595d7 | from celery_app import celery_app
@celery_app.task
def demo_celery_run():
return 'result is ok' |
2,324 | d6a73365aa32c74798b6887ff46c0ed2323ed1a6 | import glob
pyfiles = glob.glob('*.py')
modulenames = [f.split('.')[0] for f in pyfiles]
# print(modulenames)
for f in pyfiles:
contents = open(f).read()
for m in modulenames:
v1 = "import " + m
v2 = "from " + m
if v1 or v2 in contents:
contents = contents.replace(v1, "im... |
2,325 | bf73e2109f11b2214fae060bc343b01091765c2a | from ..IReg import IReg
class RC165(IReg):
def __init__(self):
self._header = ['REG',
'COD_PART',
'VEIC_ID',
'COD_AUT',
'NR_PASSE',
'HORA',
'TEMPER',
... |
2,326 | a47ffd5df49ec627442a491f81a117b3e68ff50b | # Copyright (c) 2019 NVIDIA Corporation
from nemo.backends.pytorch.nm import DataLayerNM
from nemo.core.neural_types import *
from nemo.core import DeviceType
import torch
from .datasets import BertPretrainingDataset
class BertPretrainingDataLayer(DataLayerNM):
@staticmethod
def create_ports():
input... |
2,327 | 7336b8dec95d23cbcebbff2a813bbbd5575ba58f | from collections import namedtuple
from os import getenv
from pathlib import Path
TMP = getenv("TMP", "/tmp")
PYBITES_FAKER_DIR = Path(getenv("PYBITES_FAKER_DIR", TMP))
CACHE_FILENAME = "pybites-fake-data.pkl"
FAKE_DATA_CACHE = PYBITES_FAKER_DIR / CACHE_FILENAME
BITE_FEED = "https://codechalleng.es/api/bites/"
BLOG_FE... |
2,328 | e690587c9b056f8d5a1be6dd062a2aa32e215f50 | import os
import json
import requests
from fin import myBuilder, myParser
import time
def open_config():
if os.path.isfile('fin/config.json') != True:
return ('no config found')
else:
print('config found')
with open('fin/config.json') as conf:
conf = json.load(conf)
return conf
conf = open_config()
logf... |
2,329 | 044e3479c32357e22ca3165d8601d8bd2a439fcb | from django.forms import ModelForm, ChoiceField, Form, FileField, ModelChoiceField, HiddenInput, ValidationError
from market.models import *
class OrderForm(ModelForm):
"""Order form used in trader view."""
# from http://stackoverflow.com/questions/1697702/how-to-pass-initial-parameter-to-djangos-modelform-ins... |
2,330 | fab15d34d29301e53a26577725cdd66dca7507bc | # PySNMP SMI module. Autogenerated from smidump -f python DS0BUNDLE-MIB
# by libsmi2pysnmp-0.1.3 at Thu May 22 11:57:37 2014,
# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imports
( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer",... |
2,331 | b5ec6e0fc4239a53a882b455a113eaac4db6cef5 | from Graph import *
from PrioQueue import *
from GShortestPath import *
from GSpanTree import *
from User import *
infinity = float("inf")
# 这是根据关键字找地点的方法,已经形成了某个依据属性的表后,通过关键词匹配来解决问题
# 最终输出一个yield出的迭代器,将其list化后就可以向末端输出了
def find_by_word(lst, word):
# 这个是字符串匹配函数,word是客户输入,lst是循环的东西
# 最好排成优先队列
... |
2,332 | 582f2e6972bad85c2aaedd248f050f708c61973b | from django.contrib import admin
from students.models import Child_detail
class ChildAdmin(admin.ModelAdmin):
def queryset(self, request):
"""
Filter the Child objects to only
display those for the currently signed in user.
"""
qs = super(ChildAdmin, self).queryset(reque... |
2,333 | edd98e3996b0fce46d33dd33340018ab5b029637 | import csv
import os
from collections import namedtuple
from typing import List, Dict
from config import *
HEADER = ['File', 'LKHContigs', 'LKHValue', 'LKHTime', 'APContigs', 'APValue', 'APTime', 'ActualObjectiveValue']
Assembly_Stats = namedtuple('Assembly_Stats', HEADER)
dir = '/home/andreas/GDrive/workspace/spars... |
2,334 | 6d032df195854703f36dce7d27524c8f5089c04d | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import config
import web
import hashlib
import sys
db = web.database(dbn="mysql", db=config.db, user=config.user, pw=config.passwd)
def signIn(user, pw):
pwhash = hashlib.md5(pw).hexdigest()
uid = db.insert("users", uname=user, passwd=pwhash)
r... |
2,335 | b5e9af166f3b55e44d9273077e5acd05b1fd68fa | import random #importing the random library from python
answers = ["It is certain", "Without a doubt", "Yes, definitely",
"You may rely on it", "As I see it, yes", "Most likely",
"Outlook good", "Yes", "Signs point to yes", "Reply hazy, try again",
"Ask again later", "Better not tell yo... |
2,336 | 151cc71ff1a63897238e2cc55269bd20cc6ee577 | import logging
from typing import List, Optional
import uuid
from pydantic import BaseModel
from obsei.payload import TextPayload
from obsei.preprocessor.base_preprocessor import (
BaseTextPreprocessor,
BaseTextProcessorConfig,
)
logger = logging.getLogger(__name__)
class TextSplitterPayload(BaseModel):
... |
2,337 | 49cdeb59e75ed93122b3a62fbdc508b7d66166d6 | import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
# add DenseNet structure
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# self.x = x
self.block0 = nn.Sequential(
# input image 96x96
nn.ReLU(),
... |
2,338 | 4b622c7f9b5caa7f88367dd1fdb0bb9e4a81477b | from StringIO import StringIO
import gzip
import urllib2
import urllib
url="http://api.syosetu.com/novelapi/api/"
get={}
get["gzip"]=5
get["out"]="json"
get["of"]="t-s-w"
get["lim"]=500
get["type"]="er"
url_values = urllib.urlencode(get)
request = urllib2.Request(url+"?"+url_values)
response = urllib2.urlopen(reque... |
2,339 | 73bf31e43394c3f922b00b2cfcd5d88cc0e01094 | import cv2 as cv
from threading import Thread
class Reader(Thread):
def __init__(self, width, height, device=0):
super().__init__(daemon=True)
self._stream = cv.VideoCapture(device)
self._stream.set(cv.CAP_PROP_FRAME_WIDTH, width)
self._stream.set(cv.CAP_PROP_FRAME_HEIGHT, height)... |
2,340 | c7dacdb53efb6935314c5e3718a4a2f1d862b07d | from .file_uploader_routes import FILE_UPLOADER_BLUEPRINT |
2,341 | e5f8301ae22e99c967b2ff3d791379deba7d154a | # module for comparing stats and making recommendataions
"""
Read team names from user input, retrieve features of teams from MySQL DB, compute odds of winning and recommend features to care
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pymysql as mdb
def FeatureImprove(tgtName, yo... |
2,342 | 5f0e6f6dc645996b486f1292fe05229a7fae9b17 | import unittest
import achemkit.properties_wnx
class TestDummy(unittest.TestCase):
pass
|
2,343 | 98db990f406cc6815480cca33011c8b0b2ad67c7 | # fabric이 실행할 대상을 제어.
from fabric.api import *
AWS_EC2_01 = 'ec2-52-78-143-155.ap-northeast-2.compute.amazonaws.com' # Running
PROJECT_DIR = '/var/www/kamper'
APP_DIR = '%s/app' % PROJECT_DIR
"""
# the user to use for the remote commands
env.user = 'appuser'
# the servers where the commands are executed
env.ho... |
2,344 | bfc4f5e90b7c22a29d33ae9b4a5edfb6086d79f4 | # Представлен список чисел.
# Необходимо вывести элементы исходного списка,
# значения которых больше предыдущего элемента.
from random import randint
list = []
y = int(input("Введите количество элементов в списке>>> "))
for i in range(0, y):
list.append(randint(1, 10))
new = [el for num, el in enumerate(list) if... |
2,345 | 360813a573f672e3ec380da4237a6e131dbcb7e6 | """
Users model
"""
# Django
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
class User(AbstractUser):
"""User model"""
email = models.EmailField(
'email address',
... |
2,346 | 66e77b8237850a29127402310bfab3061f7ebca4 | # Comic Downloader
#! python3
import urllib, bs4, requests
url = 'http://explosm.net/comics/39/'
base_url = 'http://explosm.net'
for i in range(1,4000):
req = requests.get(url)
req.raise_for_status()
soup = bs4.BeautifulSoup(req.text, "lxml")
comic = soup.select('#main-comic')
comicUrl = 'http:'... |
2,347 | 25fcf162306b3d6d6307e703a7d829754cba2778 | """
Constant types in Python.
定数上書きチェック用
"""
import os
from common import const
from datetime import timedelta
from linebot.models import (
TemplateSendMessage, CarouselTemplate, CarouselColumn, MessageAction,
QuickReplyButton, CameraAction, CameraRollAction, LocationAction
)
const.API_PROFILE_URL = 'https://... |
2,348 | 57935b560108ef0db59de9eee59aa0c908c58b8f | from __future__ import annotations
from abc import ABC, abstractmethod
class AbstractMoviment(ABC):
@abstractmethod
def move(self, dt) -> None:
pass
class Mov_LinearFall(AbstractMoviment):
def move(self, coordinates, speed, lastcoordinate, dt):
coordinates[1] = round(coordinates[1] + spe... |
2,349 | 94100d0253ee82513fe024b2826e6182f852db48 | import os.path
class State:
def __init__(self):
self.states=[]
self.actions=[]
class Candidate:
def __init__(self,height,lines,holes,bump,fit):
self.heightWeight = height
self.linesWeight = lines
self.holesWeight = holes
self.bumpinessWeight = bump
... |
2,350 | ae72d832039f36149988da02d8a4174d80a4ecfb |
# __ __ __ ______ __
# / | / | / | / \ / |
# $$ | $$ |_$$ |_ ______ ______ _______ /$$$$$$ | ______ $$/ _______ _______
# $$ \/$$// $$ | / \ / \ / \ ... |
2,351 | 1e83fedb8a5ed51704e991aeaa4bde20d5316d11 | # Generated by Django 3.0.3 on 2020-04-27 07:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0002_profile_favorites'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='favorites',
... |
2,352 | 8c6169bd812a5f34693b12ce2c886969542f1ab8 | class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
def count(node: ListNode) -> int:
if node is None:
return 0
else:
return count(node.next) + 1
# Test Cases
LL1 = ListNode(1, ListNode(4, ListNode(5)))
print(count(None)) # 0
print(co... |
2,353 | 2d65ffa3fc8a5360702337d749884903b2cb0423 | from django.shortcuts import render, HttpResponse
from django.views.generic import TemplateView
from .models import Person, Stock_history
from django.http import Http404, HttpResponseRedirect
from .forms import NameForm, UploadFileForm
from .back import handle_uploaded_file, read_file
class IndexView(TemplateView):
... |
2,354 | 488d20a86c5bddbca2db09b26fb8df4b6f87a1dc | import warnings
from re import *
from pattern import collection
warnings.filterwarnings("ignore")
def test():
raw_text = "通化辉南县经济适用房_通化辉南县经适房_通化辉南县经济适用房转让_通化去114网通化切换城市var googlequerykey ='二手经适房 二手房买卖 二手房地产公司' ; var AdKeyWords = 'j... |
2,355 | 91ac4a23573abcb0ab024830dbc1daebd91bd40d | """ OCR that converts images to text """
from pytesseract import image_to_string
from PIL import Image
print image_to_string(Image.open('/Users/williamliu/Desktop/Screen Shot 2014-09-27 at 11.45.34 PM.png'))
#print image_to_string(Image.open('/Users/williamliu/Desktop/Screen Shot 2014-09-27 at 11.45.34 PM.png'))
#pr... |
2,356 | f2ad95574b65b4d3e44b85c76f3a0150a3275cec | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 10:04:05 2019
@author: cristina
"""
import numpy as np
from itertools import chain
from numpy import linalg as LA
diag = LA.eigh
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 13})
import time
pi = np.pi
exp = np.exp
t1 = tim... |
2,357 | 4b8038ddea60f371aa8da168ea4456372d6f0388 | """
Subfunction A31 is responsible for inputting the component parameters
and then using the information about the component to determine
the pressure drop across that component
----------------------------------------------------------
Using data structure from /SysEng/jsonParameterFileFormat/ recall that each
cell is... |
2,358 | 3747e45dcba548060f25bd6d6f0e0e96091ca3df | s1 = {10, 20, 30, 60, 70, 80, 90}
s2 = set()
print(s2)
s1.add(100)
print(s1.pop())
print(10 in s1)
print(10 not in s1) |
2,359 | b4593b3229b88db26c5e200431d00838c357c8e0 | # MolecularMatch API (MM-DATA) Python Example Sheet
# Based on documentation at https://api.molecularmatch.com
# Author: Shane Neeley, MolecularMatch Inc., Jan. 30, 2018
import requests
import json
import numpy as np
import sys
resourceURLs = {
"trialSearch": "/v2/search/trials",
"drugSearch": "/v2/search/drugs",
... |
2,360 | 9c478c59398618d0e447276f9ff6c1c143702f12 | import pygame
import os
from network import Network
from card import Card
from game import Game, Player
pygame.font.init()
# Initializing window
WIDTH, HEIGHT = 700, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Zole")
CARD_WIDTH = 60
############################## Uploading cards
de... |
2,361 | 041a5bf205c1b3b3029623aa93835e99104464b2 | n,k = map(int,raw_input().split())
nums = list(map(int,raw_input().split()))
if k==1:
print min(nums)
elif k==2:
print max(nums[0],nums[-1])
else:
print max(nums)
|
2,362 | 9bd1fd2df7da068ac8aa4e6e24fe14d163a7e6b3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 7/02/2014
@author: marco
Generador de ambientes FACIL 2014
'''
import wx
from formgenerador import FrameGeneral
from Dial_Pagina import ObjPagina
class IncioInterface(FrameGeneral):
def __init__(self):
#self.log = ObLog('Inicio programa')
#self.lo... |
2,363 | 6d18aa585c656b244d1e4272caa8419c04b20b6c | #----------------------------
# |
# Instagram Bot- Devesh Kr. Verma
# instagram- @felon_tpf
# |
#----------------------------
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
import random
import string
from time import sleep
from selenium import we... |
2,364 | 3f22bf954a8c4608ec4bd4a28bea3679a664a99a | field = [['*', '1', '2', '3'], ['1', '-', '-', '-'], ['2', '-', '-', '-'], ['3', '-', '-', '-']]
def show(a):
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=' ')
print()
def askUserZero():
while True:
inputX = input('Введите номер строки нолика'... |
2,365 | cb742701094a8060e524ba22a0af2f969bdbf3d9 | import vk_loader.vk_api as vk
from config import config
import uuid
import requests
from models import session, Meme
import os
PHOTO_URL_FIELDS = [
'photo_75',
'photo_130',
'photo_604',
'photo_807',
'photo_1280',
'photo_2560'
]
conf = config('loader', default={
'access_token': 'Enter VK a... |
2,366 | 7998c4e0ed2bb683f029342554730464f8ac2a09 | """
TODO
Chess A.I.
"""
import os, pygame, board, math, engine, sys, gSmart
from pygame.locals import *
import engine, board, piece, copy
class gSmart:
def __init__(self):
self.e = engine.engine()
self.mtrlW = .75
self.dvlpW = 2
self.aggnW = 2
self.defnW = .5
self.thrndW = 2
sel... |
2,367 | 6657f0b51bc021e6b5867bbdd1a520c2b0cb92b3 | import logging.config
import os
import sys
import yaml
sys.path.append(os.path.join(os.path.abspath('.'), '..', '..'))
def setup_logging(default_path='common/config/logging.yaml'):
path = default_path
if os.path.exists(path):
with open(path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.... |
2,368 | ef6f91af5f500745fdcc23947a7e1764061c608c | import data
import sub_vgg19
import time
import tensorflow as tf
model_syn = sub_vgg19.vgg19_syn
model_asy = sub_vgg19.vgg19_asy
train_x = data.train_x
train_y = data.train_y
test_x = data.test_x
test_y = data.test_y
def input_fn(images, labels, epochs, batch_size):
data = tf.data.Dataset.from_tensor_slices((ima... |
2,369 | 734fd4c492f2fd31a0459e90e5c4a7468120b4cd | # http://www.dalkescientific.com/writings/diary/archive/2007/10/07/wide_finder.html
'''
Making a faster standard library approach
As I was writing an email to Fredrik describing these results,
I came up with another approach to speeding up the performance, using only the standard library.
Fredrik showed that using a ... |
2,370 | 16738e7d89bee8074f39d0b3abc3fa786faf081f | import random
prime=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
t=100
print(t)
n=25
for _ in range(t):
a=random.randint(1,n)
b=random.choice(prime)
print(a,b)
for _ in range(a):
print(random.randint(1,n),end=" ")
print("")
|
2,371 | f96c9753f3cbb0e554f9f05591e23943009c8955 | from classifier import classifier
from get_input_args import get_input_args
from os import listdir
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/calculates_results_stats_hints.py
#
# PRO... |
2,372 | 80819ec83572737c89044936fc269154b190751a | import pymysql
def get_list(sql, args):
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='chen0918', db='web')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql, args)
result = cursor.fetchall()
cursor.close()
conn.close()
return result
def ... |
2,373 | b61bb47f3e059c607447cea92ce1712825735822 | # -*- coding:utf-8 -*-
from src.Client.Conf.config import *
class SaveConfigFile():
"""
该类负责保存配置文件,属于实际操作类
"""
def __init__(self, fileName='../conf/main.ini'):
self.config = ConfigParser.ConfigParser()
self.fileName = fileName
def saveConfigFile(self, configMainName, configSubN... |
2,374 | ff67ef77958e78335dc1dc2c7e08bf42998387c6 |
SPACE = 0
MARK = 1
def frame_to_bit_chunks(frame_values, baud_rate=45.45, start_bit=SPACE, stop_bit=MARK):
"""フレームごとの信号強度からデータビットのまとまりに変換する"""
binary_values = frame_to_binary_values(frame_values)
bit_duration_values = binary_values_to_bit_duration(binary_values)
bit_values = bit_duration_to_bit_value... |
2,375 | 6f951815d0edafb08e7734d0e95e6564ab1be1f7 | from __future__ import unicode_literals
import frappe, json
def execute():
for ps in frappe.get_all('Property Setter', filters={'property': '_idx'},
fields = ['doc_type', 'value']):
custom_fields = frappe.get_all('Custom Field',
filters = {'dt': ps.doc_type}, fields=['name', 'fieldname'])
if custom_fields:
... |
2,376 | bdf819d8a5bc3906febced785c6d95db7dc3a603 | import math
def solution(X, Y, D):
# write your code in Python 3.6
xy = Y-X;
if xy == 0: return 0
jumps = math.ceil(xy/D)
return jumps
|
2,377 | cc74163d5dbcc2b2ca0fe5222692f6f5e45f73fe | import os
from pathlib import Path
import shutil
from ament_index_python.packages import get_package_share_directory, get_package_prefix
import launch
import launch_ros.actions
def generate_launch_description():
cart_sdf = os.path.join(get_package_share_directory('crs_support'), 'sdf', 'cart.sdf')
cart_spaw... |
2,378 | 4100415b0df52e8e14b00dd66c7c53cd46c0ea6e | #!/usr/bin/python3
# -*- coding:utf-8 -*-
import re
def main():
s = input().strip()
s = s.replace('BC', 'X')
ans = 0
for ax in re.split(r'[BC]+', s):
inds = []
for i in range(len(ax)):
if ax[i] == 'A':
inds.append(i)
ans += sum([len(ax) - 1 - ind for ind in inds]) - sum(range(len(ind... |
2,379 | 65264f52f641b67c707b6a827ecfe1bf417748e8 | # -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.s... |
2,380 | 181e9ac4acf0e69576716f3589359736bfbd9bef | """
Ниже на четырёх языках программирования записана программа, которая вводит натуральное число 𝑥,
выполняет преобразования, а затем выводит результат. Укажите наименьшее значение 𝑥,
при вводе которого программа выведет число 10.
Тупо вручную ввёл. Крч 9. Хз, как на экзамене делать))
"""
x = int(input())
a = 3 * x ... |
2,381 | e7c454b2bf6cf324e1e318e374e07a83812c978b | a = ord(input().rstrip())
if a < 97:
print('A')
else:
print('a')
'''
ord(A)=65
ord(Z)=90
ord(a)=97
ord(z)=122
'''
|
2,382 | 0e3c6e14ff184401a3f30a6198306a17686e6ebe | #!python3
"""
I1. a
Ex1
5
1 3 5
2 1 4
3 2 4
4 1 5
5 2 3
"""
n = int(input().strip())
t = [None] * n
for i in range(n):
x,x1 = [int(i) for i in input().strip().split(' ')]
x,x1 = x-1, x1-1
t[i] = [x, x1]
res = [0]
while len(res) < n:
a = res[-1]
b = t[a][0]
... |
2,383 | ee4fd4aef7ecdfbc8ff53028fdedc558814f46a7 | #!/usr/bin/env python3
import sql_manager
import Client
from getpass import getpass
from settings import EXIT_CMD
def main_menu():
print("""Welcome to our bank service. You are not logged in.
Please register or login""")
while True:
command = input("guest@hackabank$ ")
if command =... |
2,384 | 330df4f194deec521f7db0389f88171d9e2aac40 | """
Author: Eric J. Ma
Purpose: This is a set of utility variables and functions that can be used
across the PIN project.
"""
import numpy as np
from sklearn.preprocessing import StandardScaler
BACKBONE_ATOMS = ["N", "CA", "C", "O"]
AMINO_ACIDS = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
... |
2,385 | 4f3908e12102cfd58737952803c710772e960b0e | animal = 'cat'
def f():
global animal
animal = 'dog'
print('local_scope:', animal)
print('local:', locals())
f()
print('global_scope:', animal)
print('global:', locals())
|
2,386 | 5df42a024e1edbe5cc977a814efe580db04b8b76 | import struct
def parse(message):
return IGENMessage.from_bytes(message)
class IGENMessage(object):
def __init__(self):
self.serial = None
self.temperature = None
self.pv1 = 0
self.pv2 = 0
self.pv3 = 0
self.pa1 = 0
self.pa2 = 0
self.pa3 = 0
... |
2,387 | 64fb006ea5ff0d101000dd4329b3d957a326ed1a | def test(name,message):
print("用户是:" , name)
print("欢迎消息是:",message)
my_list = ['孙悟空','欢迎来疯狂软件']
test(*my_list)
print('*****')
# ###########################
def foo(name,*nums):
print("name参数:",name)
print("nums参数:",nums)
my_tuple = (1,2,3)
foo('fkit',*my_tuple)
print('********')
foo(*my_tuple)
print(... |
2,388 | 57027cd638a01a1e556bcde99bcbe2a3b2fa0ef8 | # -*- coding:utf-8 -*-
import easygui as eg
import time as tm
import numpy as np
import thread
import os
from urllib2 import urlopen, Request
import json
from datetime import datetime, timedelta
URL_IFENG='http://api.finance.ifeng.com/akmin?scode=%s&type=%s'
NUM_PER_THREAD=100#单线程监控的股票数
SCAN_INTERVAL=10
FILE_PATH=u'.\... |
2,389 | 67b101df690bbe9629db2cabf0060c0f2aad9722 | """
Type data Dictionary hanya sekedar menghubungkan KEY dan VALUE
KVP = KEY VALUE PAIR
"""
kamus = {}
kamus['anak'] = 'son'
kamus['istri'] = 'wife'
kamus['ayah'] = 'father'
print(kamus)
print(kamus['ayah'])
print('\nData ini dikirimkan server gojek, memberikan info driver di sekitar pemakai aplikasi')
data_server_g... |
2,390 | 755eeaf86ebf2560e73869084030a3bfc89594f6 | # Author: Omkar Sunkersett
# Purpose: To fetch SPP data and update the database
# Summer Internship at Argonne National Laboratory
import csv, datetime, ftplib, MySQLdb, os, time
class SPP():
def __init__(self, server, path, start_dt, end_dt, prog_dir):
self.files_cached = []
try:
self.ftp_handle = ... |
2,391 | 5f5e314d2d18deb12a8ae757a117ef8fbb2ddad5 | import os
os.mkdir("作业")
f=open("D:/six3/s/作业/tet.txt",'w+')
for i in range(10):
f.write("hello world\n")
f.seek(0)
s=f.read(100)
print(s)
f=open("D:/six3/s/作业/tet2.txt",'w+')
for i in s:
f.write(i)
f.close() |
2,392 | b34ce3ac87a01b8e80abc3fde1c91638f2896610 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from functools import reduce
def element_wise_op(x, operation):
for i in np.nditer(x, op_flags=['readwrite']):
i[...] = operation[i]
class RecurrentLayer(object):
def __init__(self, input_dim, state_dim, activator, learning_rate):
se... |
2,393 | e361215c44305f1ecc1cbe9e19345ee08bdd30f5 | skipped = 0
class Node(object):
"""docstring for Node"""
def __init__(self, value, indentifier):
super(Node, self).__init__()
self.value = value
self.identifier = indentifier
self.next = None
class Graph(object):
"""docstring for Graph"""
def __init__(self, values, edg... |
2,394 | d85261268d9311862e40a4fb4139158544c654b3 | from pathlib import Path
from typing import Union
from archinst.cmd import run
def clone(url: str, dest: Union[Path, str]):
Path(dest).mkdir(parents=True, exist_ok=True)
run(
["git", "clone", url, str(dest)],
{
"GIT_SSH_COMMAND": "ssh -o UserKnownHostsFile=/dev/null -o StrictHostK... |
2,395 | f54d0eeffa140af9c16a1fedb8dcd7d06ced29f2 | import math
import pendulum
from none import *
@on_command('yearprogress')
async def year_progress(session: CommandSession):
await session.send(get_year_progress())
def get_year_progress():
dt = pendulum.now()
percent = year_progress(dt)
year = dt.year
return f'你的 {year} 使用进度:{percent}%\n' \
... |
2,396 | 62018b32bf0c66fa7ec3cc0fcbdc16e28b4ef2d6 | rate=69
dollar=int(input("enter an dollars to convert:"))
inr=dollar*rate
print('INR :Rs.',inr,'/-') |
2,397 | 149f8b453786ec54668a55ec349ac157d2b93b5d | #Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the data
dataset=pd.read_csv('Social_Network_Ads.csv')
X=dataset.iloc[:,0:2].values
y=dataset.iloc[:,2].values
#spiliting the data into training data and testing data
from sklearn.model_selection impo... |
2,398 | 0553bd4c7261197a1a80c5551305a16e7bfdc761 | import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
def weights_init(m):
if type(m) == nn.Linear:
m.weight.data.normal_(0.0, 1e-3)
m.bias.data.fill_(0.)
def update_lr(optimizer, lr):
for param_gr... |
2,399 | b95eadd60093d5235dc0989205edff54ef611215 |
import sys
sys.path.insert(0, ".") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.