blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
51798a388b3fe2392c3e3bcaf15594836ab91f62 | Python | aliutkus/beads-presentation | /src/beads.py | UTF-8 | 12,302 | 3.25 | 3 | [] | no_license | import numpy as np
from scipy.special import erf
from scipy.stats import norm
import numbers
from copy import copy
from itertools import product
import matplotlib.pyplot as plt
from matplotlib import patches
def cgauss(x, mu, sigma):
return np.real(1./np.pi/sigma*np.exp(-np.abs(x-mu)**2 / sigma))
def vec(z):
... | true |
e04c7e1f8192a52f14b1f56fcc7d90443cf86ca2 | Python | Rambaldelli/SVM-GOR-Secondary-Structure-Prediction-Comparison | /BlindSet_save.py | UTF-8 | 1,939 | 2.546875 | 3 | [] | no_license | import json
import glob
from numpy import argmax
dic = {}
with open('blindSet.json', 'w') as D:
path = 'blindT/dssp/blind_test_dssp/*.dssp'
files = glob.glob(path)
for file in files:
id=file.split('/')[3]
id=id.split(':')[0]
f = open(file, 'r')
F = f.readlines()
dic... | true |
82795d57dc9450901460beaafea0c02694a1f88a | Python | kartiktodi/PolySpider | /src/PolySpider/util/CategoryUtil.py | UTF-8 | 8,661 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
'''
使用方法:
由于不同的应用商店对应的分类不同,抓取到的应用进行分类整理也不能完全按照分类名来新建分类
为了统一分类,采取91助手的分类作为默认分类方式,并为每一个分类定义一个ID
建立一个字典,key为应用市场中抓取的分类名,value为对应的分类ID
当所有市场中的分类名称都已经在字典中定义以后,就可以直接通过抓取分类名来将应用对应到我们的分类列表中来。
'''
'''
应用名称 ID(后两位为00,预留,如果有子分类的话,可以利用,比如游戏有自分类... | true |
589a0036fdef27c6c2eff42184aa328014033f10 | Python | mahasen-s/deepQuantum | /exact/exact_temp.py | UTF-8 | 1,320 | 2.796875 | 3 | [] | no_license | import numpy as np
from scipy import sparse
from scipy.sparse import linalg
def exact_TFI(N,h):
# sparse function
sp_fun = sparse.csr_matrix
# Pauli matrices
sx = sp_fun(np.array([[0,1],[1, 0]]));
sz = sp_fun(np.array([[1,0],[0,-1]]));
eye = sparse.identity(2);
zer = sp_fun(np.array([[0... | true |
ea96feea19ccf0387021024dc490946763cd9b0f | Python | nikolayvoronchikhin/pydrill | /pydrill/client/result.py | UTF-8 | 502 | 2.625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
class ResultQuery(object):
"""
Class responsible for maintaining a information returned from Drill.
It is iterable.
"""
# TODO: create better docs.
def __init__(self, response, data, duration):
self.response = response
self.duration = duration
... | true |
2fd25662d26d1f7aa3e70d89a023f947e565d892 | Python | bhatnagaranshika02/Data-Structures-Python | /Stack/PranthesisOptimized.py | UTF-8 | 176 | 3.40625 | 3 | [] | no_license | s = input()
n=-1
while len(s)!=n:
n =len(s)
s=s.replace('()','')
s=s.replace('[]','')
s=s.replace('{}','')
if len(s)==0:
print("Yes")
else:
print("No")
| true |
29235e38ddeaf47169ad7ce3eefbc6be6629f053 | Python | AK-1121/code_extraction | /python/python_12208.py | UTF-8 | 127 | 2.5625 | 3 | [] | no_license | # Accessing capture groups during substitution
re.sub(r'\d+\.\d*', lambda match: str(int(round(float(match.group(0))))), line)
| true |
1b34412c775e1e20781baa182f15d7a8cb524747 | Python | BorisVV/try-your-luck-app | /games_classes.py | UTF-8 | 4,288 | 3.71875 | 4 | [] | no_license | from game_class import Game
import random
# "Power Ball": 70,
# "Power Play": 27,
# "Gopher Five": 48,
# "North Star": 32,
# "Lotto America": 53,
# "Star Ball": 11,
# "Mega Millions": 71,
# "Mega Ball": 26,
# "Lucky For Life": 49,
# "Lucky Ball": 19,
#For each of the games we'l... | true |
1f67820253e9959c44ee8ce839a9ec3d8bfbf1d2 | Python | rajeshkumarkarra/qml | /implementations/tutorial_rotoselect.py | UTF-8 | 16,801 | 3.609375 | 4 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | r"""
.. _rotoselect:
Quantum circuit structure learning
==================================
"""
##############################################################################
# This example shows how to learn a good selection of rotation
# gates so as to minimize a cost
# function using the Rotoselect algorithm of `Os... | true |
4c56e24d81da12a8a9720cd40819e1d4c0be5424 | Python | rrriiikkk/FormationFlying | /formation_flying/negotiations/japanese.py | UTF-8 | 7,240 | 2.90625 | 3 | [] | no_license | '''
# =============================================================================
# This file contains the function to do a Japanese auction.
# =============================================================================
'''
def do_Japanese(flight):
if not flight.departure_time:
raise Exception... | true |
8efe7e8282737c335870664f59353010ec522595 | Python | insigh/open-cv-study | /windows/Binary Image/Big Image Binary.py | UTF-8 | 1,005 | 2.53125 | 3 | [] | no_license | import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def big_image_binary_demo(image):
print(image.shape)
ch, cw = 256, 256
h, w = image.shape[:2]
gray = cv.cvtColor(src=image, code=cv.COLOR_BGR2GRAY)
for row in range(0, h, ch):
for col in range(0, w, cw):
roi = ... | true |
33d7ac65eda31a9e1cf29ebf471d1f685aaaf344 | Python | cprovencher/dcos-e2e | /src/dcos_e2e_cli/common/options.py | UTF-8 | 14,259 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | """
Click options which are common across CLI tools.
"""
import re
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Union
import click
import yaml
from .utils import DEFAULT_SUPERUSER_PASSWORD, DEFAULT_SUPERUSER_USERNAME
from .validators import (
validate_path_is_directory,
validate... | true |
a6fe7696f63e1f6500232c405fbe6d728b15d855 | Python | lucasebs/TIC | /calc.py | UTF-8 | 685 | 3.375 | 3 | [] | no_license | import numpy as np
from text import Get_words
from print_entropy import Print_entropy
text = raw_input("Texto qualquer para conferencia de Entropia: ")
words, wordset = Get_words(text)
freq={word: words.count(word) for word in wordset}
word_count_information = []
entropy = 0
for word in wordset:
probability = ... | true |
3cf13d705e15b7d0d4969f3d4725152d1acc9379 | Python | liuyuzhou/ai_pre_sourcecode | /chapter2/slice_1.py | UTF-8 | 158 | 3.359375 | 3 | [] | no_license | import numpy as np
# 创建ndarray对象
ar_np = np.arange(10)
# 从索引 2 开始到索引 7 停止,间隔为2
s = slice(2, 7, 2)
print(ar_np[s])
| true |
310788779ea095f2932ae43e6f2bcb08e3df5ae1 | Python | yemikudaisi/Micro-GIS | /geometry/scale.py | UTF-8 | 462 | 3.203125 | 3 | [
"MIT"
] | permissive | class Scale(object):
def __init__(self, scale, denominator):
assert isinstance(scale, float)
assert isinstance(denominator, float)
self.numerator = scale
self.denominator = denominator
@property
def representativeFraction(self):
numerator = int(round(self.numerator/s... | true |
f97c24ab02d6efd06d60b5865a8f51414d76038d | Python | quhuohuo/python | /lvlist/teacherPython/test2.py | UTF-8 | 175 | 3.1875 | 3 | [] | no_license | #!/usr/bin/python
def P(n,x):
if n == 0:
return 1
elif n == 1:
return x
return ((2 * n - 1)*x*P(n - 1,x) - (n - 1)*P(n - 2,x)) / n
print P(2,3)
| true |
f44d8b0c0fe6ca9f5a59c5f1decbc049d64c27ca | Python | ximitiejiang/PythonCodingSkill | /test/test_tbd.py | UTF-8 | 1,785 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 18 11:10:14 2019
@author: ubuntu
"""
import torch.nn as nn
class Registry(object):
def __init__(self):
print('this is init')
self.module_dict={}
def __call__(self, class_type):
print('this is call')
modu... | true |
6169d44e3f3e069f589a901c06af0bbe19c06f36 | Python | martinabr/pydgilib | /tests/test_logger_data.py | UTF-8 | 5,464 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | """This module holds the automated tests for LoggerData."""
from pydgilib_extra import (
InterfaceData, LoggerData, INTERFACE_POWER, INTERFACE_SPI, INTERFACE_GPIO)
def test_init_logger_data():
"""Test instantiations."""
# Simple instantiaton
data = LoggerData()
assert tuple(data[INTERFACE_POWER])... | true |
b792965305b952795e0aa222c805441a2ba4652e | Python | zqfd9981/e-book-reader | /小说阅读器/typechange/typetobyte.py | UTF-8 | 2,467 | 3.09375 | 3 | [] | no_license | """
类型转化函数,将'int'等类型封装转化为byte
"""
import socket
import enum
from struct import pack, unpack
from typechange.message_type import MessageType
from binascii import unhexlify
VAR_TYPE_INVERSE = {
'int': 1,
'float': 2,
'str': 3,
'list': 4,
'dict': 5,
'bool': 6,
'bytearray': 7
}
def long_to_byt... | true |
fa83e9e29d5407a4de66b6008e89685bdcc310e0 | Python | shaoguangleo/FastImaging-Python | /src/fastimgproto/skymodel/helpers.py | UTF-8 | 1,352 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | """
Basic classes used to help structure data related to skymodel, skyregions, etc.
"""
import astropy.units as u
import attr.validators
from astropy.coordinates import Angle, SkyCoord
from attr import attrib, attrs
@attrs
class SkyRegion(object):
"""
Defines a circular region of the sky.
"""
centre ... | true |
8e551171e49774f11e372787baef37da5f4082b3 | Python | markWJJ/text_classifier_rl | /actor.py | UTF-8 | 3,458 | 2.734375 | 3 | [] | no_license | import tensorflow as tf
import tflearn
import numpy as np
from tensorflow.contrib.rnn import LSTMCell
class ActorNetwork(object):
"""
action network
use the state
sample the action
"""
def __init__(self, sess, dim, optimizer, learning_rate, embeddings):
self.global_step = tf.Variable(0... | true |
5ec3599b8870a676d9bf4595883e12111cda7fa9 | Python | harpninja/boids | /main.py | UTF-8 | 9,074 | 2.765625 | 3 | [
"MIT"
] | permissive | import maya.cmds as cmds
import random
import math
import imp
v = imp.load_source('v', '/lhome/kristina/Documents/code/maya/boids/vector_class.py') # maya python 2.7 weirdness
width = 100
height = 100
depth = 100 # was 150
class Particle(v.vec3):
'''
Class defining a single particle.
'''
def __init_... | true |
26394d522a287ace3a9741e27d7d487fa638a969 | Python | LokeshKD/MachineLearning | /CaseStudy/dataProcessing/integerFeature.py | UTF-8 | 389 | 2.78125 | 3 | [] | no_license |
import tensorflow as tf
# Add the integer Feature objects to the feature dictionary
def add_int_features(dataset_row, feature_dict):
# CODE HERE
int_vals = ['Store', 'Dept', 'IsHoliday', 'Size']
for feature_name in int_vals:
list_val = tf.train.Int64List(value=[dataset_row[feature_name]])
... | true |
fee457acacb1d4721bd7f7beb84e60273f6ba4d9 | Python | shubh4197/Python | /PycharmProjects/day3/program8.py | UTF-8 | 380 | 2.609375 | 3 | [] | no_license | with open('demo.txt', 'r') as fo:
data = fo.readline()
data1 = fo.readline()
data2 = fo.readline()
print(data)
print(data1)
print(data2)
fo = open('RA1511004010460 Shubham Das.jpg', 'rb')
i = 0
for line in fo:
fo1 = open('chunks/demo' + str(i) + '.jpg', 'wb')
print(line)
... | true |
35f24a0a9d55f7468b65e803659e7ae2d1cfbe85 | Python | aplocher/rpi-bbmon | /WebMonitor/file_writer.py | UTF-8 | 213 | 3.484375 | 3 | [] | no_license | class FileWriter:
def __init__(self, filename):
self._filename = filename
def write(self, text):
file = open(self._filename, "w")
file.write(text +"\n")
file.close() | true |
91e8de234eaed083d081eb26bd60dedf25b413f3 | Python | AbiramiRavichandran/DataStructures | /Tree/LeafTraversalOfTwoBST.py | UTF-8 | 1,410 | 3.828125 | 4 | [] | no_license | class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def is_leaf(self):
return self.left is None and self.right is None
def has_same_leaf_traversal(t1, t2):
q1 = []
q2 = []
q1.append(t1)
q2.append(t2)
while q1 or q2:
if not... | true |
448e30095ea4fa023a3091d5956d47fe8b81a18a | Python | LitRidl/checker-content | /cont11lab/problems/20/solution.py | UTF-8 | 772 | 3.015625 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
перевести все мерные расстояние из миль(mi) в киллометры(km). Например 1000mi -> 1609km
28147326av 100mi 205mi\nami in 0mi 5MI man 1000mi
'''
from __future__ import print_function
from sys import stdin, stdout
from string import *
def cs(w):
return str(int(round(1.6... | true |
24301f4022d78ff3e78643c1776a0820c01c8777 | Python | MsSusie/PythonProjects | /fillingInTheGaps.py | UTF-8 | 2,161 | 3.53125 | 4 | [] | no_license | # python 3
# program that finds all files with a given prefix eg. spam001.txt, spam002.txt, spam004.txt etc and
# locates any gaps in the numbering eg. missing spam003.txt when the file jumps to spam004.txt
# program should rename all the later files to close the gaps
import re, os, glob, shutil
from pathlib import Pa... | true |
c6a2f52900752d7ce222943ef9fda075a0c5f780 | Python | june2413/python | /EMPService.py | UTF-8 | 1,035 | 3.75 | 4 | [] | no_license | from EMP import EMP
from datetime import datetime
class EMPService:
# 객체 생성없이 바로 사용가능한 static method로 선언
@staticmethod
def readEmp(): # 사원번호, 이름, 성, 이메일, 전화번호, 입사일 등 입력
empno = input("사원번호를 입력하여 주십시오 : ")
fname = input("이름을 입력하여 주십시오 : ")
lname = input("성을 입력하여 주십시오 : ")
... | true |
348a94152a810a80eb68776ab5ceaf0b228f5afb | Python | olive1618/csss17_multilayer_networks | /MultiTensor_Pkg/AUC.py | UTF-8 | 1,303 | 3.34375 | 3 | [
"MIT"
] | permissive | import numpy as np
def calculate_AUC(M,Pos,Neg):
# M= # SORTED (from small to big) List of 2-tuple, each entry is M[n]=(mu_ij,A_ij)
# Pos= # positive entries (graph edges)
# Neg= # negative entries (graph non-edges)
y=0.;bad=0.;
for m,a,n in M:
if(a>=1.):
y+=1;
... | true |
fd5900793e66d605b11225e795b65ffc67c10232 | Python | yogii1981/Fullspeedpythoneducative1 | /test3.py | UTF-8 | 505 | 4.59375 | 5 | [] | no_license | # Given an inRange(x,y) function, write a method that determine whether a pair (x,y) falls in
# the range ( x < 1/3 < y)/ Essentially you will be implementing the body aof a function that takes two numbers
# x and y and returns True if x <1/3 < y ; otherwise it returns False.
x = int(input("Enter a value:"))
y = int(i... | true |
57054a5a1c7b1ec450f2ccb0daf2f0bbe6ac48b9 | Python | phny/python-lab | /random_walk.py | UTF-8 | 1,027 | 3.8125 | 4 | [] | no_license | #!/usr/bin/env python3.5
from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
'''
一个生成随机漫步数据的类
'''
def __init__(self, num_points = 5000):
'''初始化随机漫步属性 '''
self.num_points = num_points
#所有的随机漫步都始于(0, 0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(s... | true |
f6cf889773ce23c267394868bae65f3bb61e4ec2 | Python | HanQQ/KNN-Test | /knn.py | UTF-8 | 3,353 | 2.84375 | 3 | [] | no_license | #-*-coding:utf-8-*-
__author__ = 'Qiao'
from numpy import *
import operator
class knn:
#初始化:
def __init__(self,Filename,Inx,K,Filetest):
#training数据集:
self.filetrain=Filename
#待检测数据:
self.inX=Inx
self.k=K
#test数据集:
self.filetest=Filetest
#对train... | true |
bcd04a88f6af6cece9c278b4bfab0676c59f2c39 | Python | Shuravin/python_practice | /W3Resources/Strings/15.py | UTF-8 | 503 | 4.59375 | 5 | [] | no_license | # 15. Write a Python function to create the HTML string with tags around the word(s). Go to the editor
# Sample function and result :
# add_tags('i', 'Python') -> '<i>Python</i>'
# add_tags('b', 'Python Tutorial') -> '<b>Python Tutorial </b>'
s = input("Type your sentence: ")
tag = input(
"In which tag do you whan... | true |
c141f0d56d04e6c960e6de44e20ae8f7f46a8be0 | Python | NoraXie/LeetCode_Archiver | /LeetCode_Archiver/pipelines.py | UTF-8 | 1,178 | 2.78125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import time
from LeetCode_Archiver.LocalFile import LocalFile
from LeetCode_Archiver.Statistic import Statistic
class Questi... | true |
84c97d77825d990da42eee6bf3c1a49e71c9dc62 | Python | FalseG0d/gecko-dev | /third_party/rust/jsparagus/jsparagus/actions.py | UTF-8 | 10,213 | 3.0625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LLVM-exception",
"Apache-2.0"
] | permissive | from .ordered import OrderedFrozenSet
from .grammar import InitNt, Nt
class Action:
__slots__ = [
"read", # Set of trait names which are consumed by this action.
"write", # Set of trait names which are mutated by this action.
"_hash", # Cached hash.
]
def __init__(self, read... | true |
9f184d4510aa25b6751e1a9ad0c0533c00ca5d42 | Python | Rossel/Solve_250_Coding_Challenges | /chal111.py | UTF-8 | 111 | 3.484375 | 3 | [] | no_license | x = "The days of Python 2 are almost over. Python 3 is the king now."
if len(x) >= 50:
print("True!") | true |
696126e59b5036483badcc22bd49c7aa97bd2a34 | Python | JetBrains-Research/similar-python-dependencies | /src/preprocessing/preprocess.py | UTF-8 | 4,357 | 2.6875 | 3 | [
"MIT"
] | permissive | from collections import Counter, defaultdict
from operator import itemgetter
import os
from typing import Dict, List, Optional
import numpy as np
import requirements
def process_sources() -> None:
"""
Parses through all the versious of requirements files, saves the processed version
into a single file.
... | true |
b3b0b8bb76c3c958628e771b2bfec4cb3c5499a9 | Python | blodyx/AdventOfCode2020 | /3_extra.py | UTF-8 | 342 | 2.6875 | 3 | [] | no_license | lines = open("input/3.input", "r").readlines()
tests=[]
maxx=len(lines)
maxy=len(lines[0])-1
for cx in range(10,19):
for cy in range(10,19):
tree=x=y=0
while x<maxx:
if lines[x][y] == '#':
tree+=1
x+=cx
y+=cy
if y>=maxy:
y=y-maxy
tests.append([cx,... | true |
f1b8a4d0f66502a2ca94cc20b1cf9e0043ee2ca4 | Python | LoneElk/Infrared-IPS | /test/test_building_model.py | UTF-8 | 12,022 | 2.5625 | 3 | [] | no_license | __author__ = 'jim'
import unittest
import sys
import json
import logging
import globals.building_model as bm
from globals.global_constants import *
def load_map(file_name):
"""load map for specified room"""
map_data = {}
try:
with open(file_name,'r') as fs:
map_data = json.load(fs)
... | true |
203eb553422fa0c063e352723b4c5ebc45f68e5a | Python | mattmar2410/spec_analysis | /spec_analysis/spec_analysis/fix_spe.py | UTF-8 | 877 | 2.609375 | 3 | [] | no_license | import os
from copy import deepcopy
import numpy as np
def fix_spe(fname, fname_new=None):
'''
fix_spe_zero_cal(fname, fname_new=None) creates a new file name for an uncalibrated
gammavision spectrum
fname: the spectrum that needs to be calibrated
'''
if fname_new is None:
fname_new = '... | true |
f67efe29b21082a949d708bf9381ad412bf30872 | Python | marcvifi10/Curso-Python | /Python 1/1 - Introducion/10 - Salida de datos/Salida_de_datos.py | UTF-8 | 180 | 4.125 | 4 | [] | no_license | # Salidas
nombre = "Marc"
edad = 22
print("Hola",nombre,"tienes",edad,"años.")
print("Hola {} tienes {} años.".format(nombre,edad))
print(f"Hola {nombre} tienes {edad} años.") | true |
e6f9cf4f0f688084342266687a8b185983d6631b | Python | FKomendah/PYTHON_TIZI | /second_assignment/dirb_look_alike_with_exception.py | UTF-8 | 582 | 3.046875 | 3 | [] | no_license | #!/usr/bin/python
import requests as req
import sys
def statuschecker(url,path):
'''comment here'''
r=req.get(url+path)
code=r.status_code
return code
path_file=open("/usr/share/dirb/wordlists/common.txt","r")
try:
if len(sys.argv)<2:
print "Usage: %s http://target.url"%sys.argv[... | true |
70c62bbd1b1d115dcbcdb3639aa88e4cada0b88b | Python | Jannis12324/meme_generator | /QuoteEngine/DocxIngestor.py | UTF-8 | 921 | 3.09375 | 3 | [] | no_license | """Ingests docx files and returns a list of QuoteModule Objects."""
from .IngestorInterface import IngestorInterface
from typing import List
from .QuoteModel import QuoteModel
import docx
class DocxIngestor(IngestorInterface):
"""A class that handles the ingestion of docx files."""
allowed_extensions = ["do... | true |
ed5186557c1a376d46524c4dc43accf789724f21 | Python | wenshanj/Database-Development-for-Spotify | /simple_query_2.py | UTF-8 | 633 | 3.109375 | 3 | [] | no_license | import psycopg2 as pg2
from prettytable import PrettyTable
con = pg2.connect(database = 'spotify', user = 'isdb')
con.autocommit = True
cur = con.cursor()
def US5(playlist_id):
print ("US5: As a listener, I want to see the total number of songs in a given playlist")
print ("Input: playlist_id = 9")
tmpl =... | true |
492806f512380ad866832db38cdb64dec74a71a6 | Python | ReinaKousaka/core | /src/algorithm/scripts/count_overlap_btw_clusters.py | UTF-8 | 1,984 | 2.734375 | 3 | [] | no_license | from src.algorithm.Activity.count_overlap_activity import CountOverlapActivity
import argparse
import time
from src.algorithm.count_overlap.parser.parse_config import parse_from_file
from src.shared.utils import get_project_root
DEFAULT_PATH = str(get_project_root()) + "/src/algorithm/count_overlap/config/count_overla... | true |
a0f64ab6723d3a8ff4e25e00c4e7b50d578b5fc3 | Python | jfmacedo91/curso-em-video | /python/ex102.py | UTF-8 | 543 | 4.375 | 4 | [] | no_license | def fatorial(num, show=False):
"""
→ Calcula o Fatorial de um número.
:param num: O número a ser calculado.
:param show: (Opcinal) Mostrar ou não a conta.
:return: O valor fatorial do número num.
"""
tot = 1
for c in range(num, 0, -1):
tot *= c
if show:
... | true |
f12f67f33c0388e36300dc50a8b06ac4e841cca3 | Python | jmoradian/directedStudy | /dataPrep/createFeatureMatrix/Featurize.py | UTF-8 | 946 | 2.734375 | 3 | [] | no_license | import string, calendar, textblob
from dateutil import parser
FAVORITE_INDEX = 0
DATE_INDEX = 1
TEXT_INDEX = 3
LISTED_INDEX = 5
VERIFIED_INDEX = 6
FRIEND_INDEX = 7
def getTimeStamp(timeStr):
parsedDate = parser.parse(timeStr)
timestamp = calendar.timegm(parsedDate.timetuple())
return timestamp
# uses textblob lib... | true |
811d2537ca49dbeabcab9ee7c604f4235cef5d6c | Python | shen-huang/selfteaching-python-camp | /exercises/1901040047/1001S02E05_string.py | UTF-8 | 1,489 | 3.65625 | 4 | [] | no_license | t = '''
"The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although prac... | true |
24bd91dbcb6cf81db97e05d97f7416b6e6d1ab84 | Python | EachenKuang/LeetCode | /code/459#Repeated Substring Pattern.py | UTF-8 | 636 | 3.65625 | 4 | [] | no_license | # https://leetcode.com/problems/repeated-substring-pattern/description/
class Solution(object):
# First char of input string is first char of repeated substring
# Last char of input string is last char of repeated substring
# Let S1 = S + S (where S in input string)
# Remove 1 and last char of S1. Let t... | true |
b502ccc25a35b4297690f608243ee427e4405825 | Python | 924235317/leetcode | /179_largest_number.py | UTF-8 | 473 | 3.5625 | 4 | [] | no_license | from functools import cmp_to_key
def largestNumber(nums):
def comp(str1, str2):
if str1 + str2 > str2 + str1:
return 1
elif str1 + str2 == str2 + str1:
return 0
else:
return -1
nums_str = list(map(str, nums))
nums_str = sorted(nums_str, key=c... | true |
83cc1c83482a81874da6a730706c15b6f39403bc | Python | mattswoon/peanut-butter | /peanut_butter/indexer.py | UTF-8 | 1,262 | 2.796875 | 3 | [
"MIT"
] | permissive | import attr
import enum
from typing import List
import numpy as np
@attr.s
class Region:
code = attr.ib(type=str)
class Status(enum.Enum):
susceptible = enum.auto()
infected = enum.auto()
recovered = enum.auto()
NUM_STATUSES = 3
@attr.s
class Indexer:
regions = attr.ib(type=List[Region])
... | true |
88da2053bc2c93da551bd414c1fd629e9cb90863 | Python | qmnguyenw/python_py4e | /geeksforgeeks/python/easy/6_17.py | UTF-8 | 19,882 | 4.5 | 4 | [] | no_license | Tic Tac Toe GUI In Python using PyGame
This article will guide you and give you a basic idea of designing a game Tic
Tac Toe using _pygame_ library of Python. Pygame is a cross-platform set of
Python modules designed for writing video games. It includes computer graphics
and sound libraries designed to be use... | true |
849d86ee6a349a19d1ef5025e59c45f593bdb2ea | Python | kangminsu1/Computer_Vision | /Midterm/Q_3.py | UTF-8 | 1,637 | 3.703125 | 4 | [] | no_license | class N:
def __init__(self, head, new_head=None, random=None):
self.head = head
self.new_head = new_head
self.random = random
#Print를 위한 재귀 함수
def finding(node):
if node is None:
print("null")
return
# 현재의 노드 head와 random한 포인터 데이타
print(node.head, end='')
if node.random:
text = "[%d]"%(n... | true |
b2e7a6f4a2df69448b8231f572d8fbb3701bb1ff | Python | NannikEU/eu_python_basics | /exc_423.py | UTF-8 | 1,852 | 3.40625 | 3 | [] | no_license | # 423
import math
import random
def a():
result = 0
for i in range(n):
result += A[i][0]
return result
def b():
result = 0
for i in range(n):
result += A[i][i]
for i in range(n):
result += A[i][n - i - 1]
if n % 2 == 1:
result -= A[math.floor(n / 2)][... | true |
c229eda1c818c0dcc98a36a7279e3186f31a4f42 | Python | gungui98/object-detect | /shrink_images.py | UTF-8 | 435 | 2.625 | 3 | [] | no_license | import glob
import cv2
FOLDERS = ['livingrooms/','bedrooms/','kitchen/','bathrooms/']
ROOT_FOLDER = 'data/'
DESTINATION_FOLDER = 'preprocess/'
for folder in FOLDERS:
for file in glob.glob(ROOT_FOLDER+folder+'*.jpg'):
file_name = file.replace(ROOT_FOLDER+folder,'')
image = cv2.imread(file)
... | true |
d134596f4bbf3f38682b70687c3d559bb559a913 | Python | NikhilCBhat/grow-organic | /data_collection/water_plants.py | UTF-8 | 1,789 | 3.390625 | 3 | [] | no_license | import sys
sys.path.append('.')
import time
from time import sleep
from data_collection.valve import setup_valve, open_valve, close_valve
from data_collection.pump import setup_pump, run_pump_forward, run_pump_backward, stop_pump
from data_collection.moisture import is_water_safe
def water_plant(plant_id, water_durati... | true |
f04fc2dd703cf2308caba986c4966c320a5c5084 | Python | amaozhao/algorithms | /algorithms/arrays/two_sum.py | UTF-8 | 509 | 3.828125 | 4 | [
"MIT"
] | permissive | """
给定一个整型数组, 返回这样2个元素的索引: 这2个元素相加的结果为给定的值.
你可以假定这个结果只有一种情况, 但是每个元素只能使用一次.
例如:
给定 nums = [2, 7, 11, 15], target = 9,
因 nums[0] + nums[1] = 2 + 7 = 9,
返回 [0, 1].
"""
def two_sum(array, target):
dic = {}
for i, num in enumerate(array):
if num in dic:
return dic[num], i
... | true |
0f4776e4b12700024e106bd7e1a31cd1300ae489 | Python | joesdesk/themecrafter | /themecrafter/interface/html.py | UTF-8 | 3,351 | 3.15625 | 3 | [] | no_license | # Module to visualize the comments through html.
from math import floor
from bs4 import BeautifulSoup
from .htmlrender import doc2tr
from .html_styling import Doc2HtmlStyler
class HTMLInterface:
'''The interface for viewing the XML documents.'''
def __init__(self, xmlstring):
'''Takes an XML st... | true |
04fee2416e4a10cde49fc3267f7b371f0b16fa87 | Python | AlbertoCastelo/Neuro-Evolution-BNN | /neat/dataset/regression_example.py | UTF-8 | 5,653 | 2.78125 | 3 | [] | no_license | import torch
from sklearn.preprocessing import StandardScaler
from torch.utils.data import Dataset
import numpy as np
from neat.dataset.abstract import NeatTestingDataset
class RegressionExample1Dataset(NeatTestingDataset):
'''
Dataset with 1 input variables and 1 output
'''
TRAIN_SIZE = 5000
TES... | true |
50c4efde030006daeab9693571f8c1d5324c5b80 | Python | 1576dkm/Spark_Jobs | /Abs/p1.py | UTF-8 | 408 | 2.59375 | 3 | [] | no_license | from operator import add
from pyspark import SparkContext
sc = SparkContext("local[*]", "example")
rdd = sc.textFile("C:\\Users\janjanam.sudheer\Desktop\data.csv")
rdd1 = rdd.map(lambda x : x.split(',')).map(lambda x: (x[0],x[1].split(';'))).filter(lambda line: "Country" not in line).map(lambda z : (z[0],list(map(lamb... | true |
c6d6b7f340d07353c7da767b83732d87361ae593 | Python | kar655/Kaggle-cactus-identification | /build_data.py | UTF-8 | 2,879 | 3.125 | 3 | [] | no_license | import os
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
import time
labels = pd.read_csv("train.csv")
class Cactus():
IMG_SIZE = 32
cactuscount = 0
notcactuscount = 0
# 0: not-cac 1: cac
test_data_amount = [0, 0] # trying to get 1... | true |
890735457d3b5c643b871623ee8af1edcddef0f7 | Python | bledem/webvision | /cnn/vocab.py | UTF-8 | 2,578 | 2.921875 | 3 | [] | no_license | # Create a vocabulary wrapper
import nltk
import pickle
from collections import Counter
import json
import argparse
import os
class Vocabulary(object):
"""Simple vocabulary wrapper."""
def __init__(self):
self.word2idx = {}
self.idx2word = {}
self.idx = 0
def add_word(self, word)... | true |
b78980d67c88fb9400fc79bc00e1aa0d0a2b96d3 | Python | an-kumar/rntn | /stepper.py | UTF-8 | 9,974 | 2.84375 | 3 | [] | no_license | '''
Ankit Kumar
ankitk@stanford.edu
learning steps for the rntn model
uses adagrad as in the paper
'''
from rntn import *
import cPickle as pkl
from data import *
def softmax_crossentropy_cost(tree):
'''
a costfunction that computes softmax crossentropy gradients and cost
'''
cost = 0.
for node ... | true |
c0a508625d84d1b3117a33a8987a7b8a0108e28c | Python | gogofunoliver/WeChatCon | /WeChatServer/CloudVision.py | UTF-8 | 1,204 | 2.75 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# filename: CloudVision.py
# Jason Li
# text detection API
import argparse
import io
from google.cloud import vision
from google.cloud.vision import types
class GCPCV(object):
def detect_document(path):
"""Detects document features in an image."""
client = vision.ImageAnn... | true |
00edc8f96e99bc3890df137019b0c585194d6d9c | Python | boks01/True-or-False | /checking.py | UTF-8 | 965 | 4.09375 | 4 | [] | no_license | class Checking:
def __init__(self, question, answer):
self.answer = answer
self.question = question
self.question_number = 0
self.score = 0
def give_question(self):
for _ in range(len(self.question)):
current_question = self.question[self.question_number]
... | true |
873ac0f5487556c590adb9ced4a2edf7cb7353ff | Python | Aasthaengg/IBMdataset | /Python_codes/p02803/s480619618.py | UTF-8 | 1,651 | 2.671875 | 3 | [] | no_license | #!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from functools import reduce, lru_cache
import collections, heapq, itertools, bisect
import math, fractions
import sys, copy
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.... | true |
995424bb9db2fcd925533d89bee981055daa223e | Python | LoverOfPies/AutomationBuild | /src/gui/dictionary/simple_dictionary/BaseUnitUI.py | UTF-8 | 4,016 | 2.5625 | 3 | [] | no_license | from kivy.lang import Builder
from kivy.metrics import dp
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen
from kivy.uix.scrollview import ScrollView
from src.db.models.base.BaseUnit import BaseUnit
from s... | true |
fe3129bdcdd5644f8eb6ae4fc4701f750863c384 | Python | gladpark/network-importer | /tests/unit/adapters/test_base_adapter.py | UTF-8 | 1,436 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | """test for the base adapter."""
from typing import List, Optional
from pydantic import BaseSettings
from network_importer.adapters.base import BaseAdapter
def test_init_no_settings_class():
adapter = BaseAdapter(nornir="nornir_object", settings=None)
assert adapter.nornir == "nornir_object"
assert adapt... | true |
30f04eafccdaf258dff18d0448b1311371e2bce5 | Python | tro9lh/RandomYoutubeVideo | /defs.py | UTF-8 | 3,574 | 2.5625 | 3 | [] | no_license | import requests
import json
import datetime
import random
def get_random_video_ru():
day = random.randrange(3000)
sec = random.randrange(86399)
datenow = datetime.datetime.now()
publishedAfter1 = datenow - datetime.timedelta(days=(day +1), seconds = sec)
publishedAfter = publishedAfte... | true |
c5daaf71e11306b0f614c84959bd39ce2b6df241 | Python | lijiunderstand/MultitaskNet | /utils/data_utils.py | UTF-8 | 4,856 | 2.859375 | 3 | [] | no_license | import os
import numpy as np
import h5py
import torch
import torch.utils.data as data
import pickle
from PIL import Image
class CreateData(data.Dataset):
def __init__(self, dataset_dict):
self.len_dset_dict = len(dataset_dict)
self.rgb = dataset_dict['rgb']
self.depth = dataset_dict['depth... | true |
ff403a67dc337f4c59971d5be5adddbab58fae18 | Python | shellydeforte/PDB | /pdb/lib/datetime_info.py | UTF-8 | 1,184 | 2.8125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""Create ISO 8601 compliant date and time stamps."""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import pytz
import re
from datetime import datetime
class RE(object):
datetime_stamp_pattern = """
^ # An... | true |
4a8f579cace15ea48effc824850c610308b56bd8 | Python | JonathanCSantos098/programacao-orientada-a-objetos | /listas/lista-de-exercicio-02/questao11.py | UTF-8 | 159 | 3.15625 | 3 | [] | no_license | num1=int(input())
num2=int(input())
num3=int(input())
produto=(num1*2)*(num2/2)
soma=(num1*3)+num3
potencia=num3**3
print(produto)
print(soma)
print(potencia)
| true |
dde499912a98190e19a7026b2fe799d61d7c76b5 | Python | Hchong16/VulnContract | /tests/declaration_test.py | UTF-8 | 5,152 | 2.65625 | 3 | [] | no_license | import unittest
import sys
sys.path.append("../..")
from declarations.solidityFile import SolidityFile
class TestFunctionsModule(unittest.TestCase):
filename = 'suicidal.sol'
file_path = '../../examples/{}'.format(filename)
smart_contract = SolidityFile(filename, file_path)
smart_contract.... | true |
177b0021efcbe19b1edf7f5151db60c43cf0c7d0 | Python | jjliewie/kakao | /taxi.py | UTF-8 | 560 | 2.671875 | 3 | [] | no_license | import heapq
# floyd warshall algorithm
def solution(n, s, a, b, fares):
d = [ [ 20000001 for _ in range(n) ] for _ in range(n) ]
for x in range(n):
d[x][x] = 0
for x, y, c in fares:
d[x-1][y-1] = c
d[y-1][x-1] = c
for i in range(n):
for j in range(n):
... | true |
28b38a2047ed90001f54964a449f02eaebe24c98 | Python | NgoKnows/Interview-Practice | /Trees and Graphs/List of Depths.py | UTF-8 | 475 | 2.90625 | 3 | [] | no_license | from collections import dequeue
def list_depths(root, queue=None, levels=None, index=0):
if queue is None:
queue = dequeue([root])
if levels is None:
levels = dict()
levels[index] = LinkedList()
queue2 = dequeue()
while len(queue1):
node = queue.pop()
levels[index].add(node)
if... | true |
3e867851c9048c770968fa665bda04d4a5ddbdf9 | Python | syn1911/Python-spider-demo | /01improve/14多线程04.py | UTF-8 | 910 | 3.5 | 4 | [] | no_license | # map使用
from concurrent.futures import ThreadPoolExecutor
import time
# 参数times用来模拟网络请求的时间
def get_request(times):
time.sleep(times)
print("用了{} 时间进行了返回".format(times))
return times
executor = ThreadPoolExecutor(max_workers=2)
urls = [3, 2, 4] # 并不是真的url
for data in executor.map(get_request, urls):
p... | true |
1e554b0bc634837c42ca21686db3181b6225c5bc | Python | YangLiyli131/Leetcode2020 | /in_Python/1276 Number of Burgers with No Waste of Ingredients.py | UTF-8 | 456 | 2.625 | 3 | [] | no_license | class Solution(object):
def numOfBurgers(self, tomatoSlices, cheeseSlices):
"""
:type tomatoSlices: int
:type cheeseSlices: int
:rtype: List[int]
"""
A,B = tomatoSlices, cheeseSlices
res = []
a = A - 2 * B
b = 4 * B - A
if a ... | true |
ca9b7730bc2a4157f7570d3dbce5114725c50613 | Python | frostbyte16/botaku | /project_files/contentBased.py | UTF-8 | 3,560 | 3.28125 | 3 | [] | no_license | # content based filtering
import pandas as pd
from sklearn.metrics.pairwise import sigmoid_kernel, cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
import random
def recommend(name, anime_type, subtype):
df_anime = pd.read_csv(f"{anime_type}.csv")
# Drops all blank anime with dupl... | true |
a78c8ee218eacb59646c2dea593ffa74ebb7e231 | Python | odnodn/PatientFM | /src/models/BiLstmCRF/decoder.py | UTF-8 | 2,379 | 2.71875 | 3 | [
"MIT"
] | permissive | import torch
from torch import nn
from torchcrf import CRF
r""" The Decoder implements two tasks: I2B2 entity classification, and novel detection of entities.
I2B2 part uses the CRF, novel part uses linear+softmax """
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size, max_le... | true |
50790c3c6a4926d4ce0271d910df58945e45a5bd | Python | texnedo/algo-tasks | /algo-python/PaintHouse.py | UTF-8 | 804 | 2.890625 | 3 | [] | no_license | import sys
from typing import List, Dict
class Solution:
def min_cost(self, costs: List[List[int]]) -> int:
return self.min_cost_internal(costs, 0, -1, dict())
def min_cost_internal(self, costs: List[List[int]],
i: int, prev_j: int, cache: Dict[tuple, int]):
if i >= ... | true |
a633fa471a6d1f6ac4f93a9e3cf85be4870a08b8 | Python | Sentone5/Laba_4 | /Zadanye2.py | UTF-8 | 545 | 3.796875 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Дано слово из 12 букв. Переставить в обратном порядке буквы, расположенные между
# второй и десятой буквами (т.е. с третьей по девятую).
if __name__ == '__main__':
word = input("Введите слово из 12 букв ")
word = word.replace(word[2], word[8], 1)
w... | true |
7f32b5e6a1d6151c7442621d939bd63214d82bb6 | Python | noahfkaplan/InterviewPracticeSolutions | /DailySolutions/2020/01-07-2020/main.py | UTF-8 | 72 | 2.765625 | 3 | [] | no_license | import LookAndSee
n = 4
result = LookAndSee.LookAndSee(n)
print(result) | true |
863485bb52b7b7aa4fa0b76ac2aa8ced543578fa | Python | asw101/GithubAzureGuide | /djangoapp-master/polls/pandas_data.py | UTF-8 | 2,121 | 2.609375 | 3 | [
"MIT"
] | permissive | import pandas
import os
from datetime import datetime
from datetime import timedelta
from .models import Githubevent
def filter_in_admin():
issue_df = pandas.DataFrame(list(Githubevent.objects.all().values()))
count_df = issue_df.groupby('issue_id').size().sort_values(ascending=False)
count_df = count_df[... | true |
081af84de8920c3300774a5d658ce7b2520ef2b0 | Python | brandoneng000/LeetCode | /medium/998.py | UTF-8 | 883 | 3.390625 | 3 | [] | no_license | from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
... | true |
9feba069ed707117cae743f32f65590a64e44a5d | Python | TylerMorley/book-scraper | /scraper-test-unit.py | UTF-8 | 2,490 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python
import unittest
import scraper
from lxml import etree, html
from lxml.etree import tostring
import requests
class UnitTest_Iterations(unittest.TestCase):
@classmethod
def setUp(self):
self.setupTest(self)
class TestCases(UnitTest_Iterations):
def setupTest(self):
sel... | true |
80cf59158e8dd1dabbf7d47822b6cb99b9ec3bd1 | Python | sebinemeth/chesscraft-client | /figure/FigureFactory.py | UTF-8 | 773 | 3.046875 | 3 | [] | no_license | from abc import ABC
from figure.Bishop import Bishop
from figure.King import King
from figure.Knight import Knight
from figure.Peasant import Peasant
from figure.Queen import Queen
from figure.Rook import Rook
class FigureFactory(ABC):
@staticmethod
def get_figure(figure_type, player):
if figure_type... | true |
024000850ac46c847cc2838f945b9d3c42139baf | Python | liuspencersjtu/MyLeetCode | /925-Long-Pressed-Name.py | UTF-8 | 1,026 | 3.03125 | 3 | [] | no_license | class Solution:
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
if len(name)==1:
for i in typed:
if i != name:
return False
return True
p1,p2 = 0,0
... | true |
5ea700be999aee2a1187981c0497c725c06fec7f | Python | bohdi2/euler | /problem43.py | UTF-8 | 4,167 | 3.53125 | 4 | [] | no_license | #!/usr/bin/env python3
import argparse
import functools
import sys
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print('%r (%r, %r) %2.2f sec' % (method.__name__, args, kw, te-ts))
return result
... | true |
f888e32e5eae74a2110534237c0b47145bfc2c4a | Python | jlyons6100/Wallbreakers | /Week_2/jewels_and_stones.py | UTF-8 | 453 | 3.453125 | 3 | [] | no_license | # Jewels and Stones: Given strings J representing the types of stones that are jewels and s representing the stones you have.
# Determine how many stones you have that are also jewels.
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
j_set = set()
for jewel in J:
j_se... | true |
a86d6791ab30901d2297c2ad67a250392e608cd9 | Python | UrbanWojnowski/PythonFiles | /ExcelWrite.py | UTF-8 | 206 | 2.640625 | 3 | [] | no_license | import xlwt
# create an object of workbook
wk = xlwt.Workbook()
ws = wk.add_sheet("Testing")
ws.write(0,0,"Testing WOrld")
ws.write(0,1,"www.theTestingWorld.com")
wk.save("TestingWorld1.xlsx")
| true |
cf1889966eba2efc94e0aa558178f2f0002dcec3 | Python | rezasaneei/ML | /Python/massoud_tfidf/massoud_tfidf_v3.py | UTF-8 | 1,655 | 3.078125 | 3 | [] | no_license | from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
from sklearn.metrics.pairwise import euclidean_distances
import csv
import numpy as np
docs = []
with open('movie_lines.txt') as f:
docs = f.read().splitlines()
len_docs = len(docs)
#print 'nu... | true |
b444bc7436611d75e25e30bea711a1c36801b5f6 | Python | moonkangyun/MSE_python | /ex110.py | UTF-8 | 500 | 4.25 | 4 | [] | no_license | if True :
if False:
print("1")
print("2")
else:
print("3")
else :
print("4")
print("5")
# 즉, 3과 5가 나올 것이다. 첫번째 if문에서서 무조건 True기 때문에 두번째 if문으로 가는데 이때에는 거짓이라면 1과 2를 출력하지만 거짓이 아니기 때문에 3을 출력하고 if문을 빠져나온다. 그러고나서 제일 마지막에 if문에 영향을 받지않는 print("5")가 있기 때문에 5도 출력하고 마친다. | true |
21a66cb234653fce958ae89e45123bafe910f79c | Python | JohnEstefano/AWS_Data_Lake | /etl.py | UTF-8 | 7,266 | 2.59375 | 3 | [] | no_license | import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format
config = configparser.ConfigParser()
config.read_file(open('dl.cfg'))
config.sections()
o... | true |
dd8d9bf1244616b0884e9da8b9b1e05c23a01f83 | Python | johnwatterlond/playground | /hangman.py | UTF-8 | 4,291 | 4.5625 | 5 | [] | no_license | """
A hangman game.
Player is allowed 7 wrong guesses.
"""
import string
import os
import random
from words import word_list
def clear():
"""Clear terminal screen."""
os.system('clear')
class Hangman:
"""
Represents a game of hangman.
Args:
secret_word: The word used for the game of ... | true |
03a83330bc3bfd7e16bda60c29dd3dea06bb7a08 | Python | JorgeOrobio/Proyecto1_CG | /Proyecto_1/Objetos.py | UTF-8 | 3,515 | 2.78125 | 3 | [] | no_license | import pygame as pg
from libreria import*
class Bloque(pg.sprite.Sprite):
"""clase bloque"""
def __init__(self,imagen,pos):
pg.sprite.Sprite.__init__(self)
self.image = imagen
self.rect=self.image.get_rect()
self.pos = pos
self.rect.x=pos[0]+240
self.rect.y=pos[... | true |
69fb323f44bea3f1af5b7c9721c59fb59eef4bcd | Python | bengwie/PythonCodePractice | /missingnumber2.py | UTF-8 | 1,335 | 3.1875 | 3 | [] | no_license | #!/usr/bin/python
def testMe(nums):
maxRep = 0
num_dict = dict()
previousNum = None
for (index, num) in enumerate(nums):
print "num: %s" % num
if num in num_dict:
num_dict[num] += 1
else:
if maxRep != 0:
if num_dict[previousNum] < maxRep:
retu... | true |
7fede34f5e5c07e5f1a9d887e832e160c19b6367 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/2180.py | UTF-8 | 501 | 3.1875 | 3 | [] | no_license | def gl(f, splitchar=' '):
return map(f, raw_input().split(splitchar))
def g(f):
return f(raw_input())
t=g(int)
for i in xrange(t):
first=g(int) - 1
cards1=[gl(int) for _ in xrange(4)]
second=g(int) - 1
cards2=[gl(int) for _ in xrange(4)]
ans = set(cards1[first]) & set(cards2[second])
p... | true |
04e99c8a77a9a28ee221e945ed8ed30c662cad8d | Python | KashifAS/Aganitha-Full-Stack-and-AI-Quiz-2020- | /app.py | UTF-8 | 5,209 | 3.5 | 4 | [] | no_license | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
import flask
app = Flask(__name__)
def get_rules():
rules = {'Numbers': {
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'... | true |
b57228086259be3c3d07349118f0a38d612f85ea | Python | JiaXingBinggan/RL_ad | /src/DRLB/RL_brain_for_test.py | UTF-8 | 3,045 | 2.734375 | 3 | [] | no_license | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.config import config
import os
np.random.seed(1)
class Net(nn.Module):
def __init__(self, feature_numbers, action_numbers):
super(Net, self).__init__()
# 第一层网络的神经元个数,第二层神经元的个数为动作数组的个数
neuron_num... | true |