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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2f5697915a5d4bc4bc2d721c3edfa9df6ecb75bc | Python | endlessm/ostree-upload-server | /ostree_upload_server/task_queue.py | UTF-8 | 665 | 3.03125 | 3 | [] | no_license | import logging
from gevent import queue
class TaskQueue:
def __init__(self):
self._queue = queue.JoinableQueue()
self._all_tasks = {}
def add_task(self, task):
task_id = task.get_id()
logging.info('Adding task {}'.format(task_id))
self._all_tasks[task_id] = task
... | true |
06c47a321808e27accc4c513296d845d8f93f792 | Python | Aasthaengg/IBMdataset | /Python_codes/p02256/s278725097.py | UTF-8 | 148 | 3.71875 | 4 | [] | no_license | #ALDS 1-B: Greatest Common Divisor
x = input().split()
a = int(x[0])
b = int(x[1])
while(a % b != 0):
c = b
b = a % b
a = c
print(b)
| true |
bf76e07dd05d1424fdefadb4048ca428749d6cd2 | Python | Srikumar-R/Sri | /q71.py | UTF-8 | 133 | 3.28125 | 3 | [] | no_license | a=input()
b=[]
c=''
for i in a:
b.append(i)
b.reverse()
for i in b:
c=c+i
if (a==c):
print("yes")
else:
print("no")
| true |
f92828526e8801e62bead16429e34839ad20b9e0 | Python | pawat88/learn | /PythonCrashCourse/ch3/bicycles.py | UTF-8 | 242 | 3.421875 | 3 | [] | no_license | bicycles = ['trek', 'cannodale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
message = "My first bicycle is " + bicycles[0].title() + " and I plan to buy " + bicycles[3].title()
print(message)
| true |
15a521328bdb2297f3a735772dc06137db111c84 | Python | niklassiemer/xca | /xca/ml/tf_data_proc.py | UTF-8 | 10,123 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | from __future__ import absolute_import, division, print_function, unicode_literals
import os
from pathlib import Path
import tensorflow as tf
import numpy as np
import xarray as xr
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[val... | true |
fdc45c5b7eb82f4c4aa99b6370c54aa5112a371b | Python | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/970_Powerful_Integers.py | UTF-8 | 1,296 | 3.890625 | 4 | [] | no_license | """
Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0.
Return a list of all powerful integers that have value less than or equal to bound.
You may return the answer in any order. In your answer, each value should occur at most once.
Exampl... | true |
eb1c2740a02f25af8e625904a4ea94af7c883646 | Python | realpython/materials | /python-iterators-iterables/reusable_range.py | UTF-8 | 429 | 3.296875 | 3 | [
"MIT"
] | permissive | class ReusableRange:
def __init__(self, start=0, stop=None, step=1):
if stop is None:
stop, start = start, 0
self._range = range(start, stop, step)
self._iter = iter(self._range)
def __iter__(self):
return self
def __next__(self):
try:
return... | true |
67611f41940c178d0845536c4994405a2827ae42 | Python | cailmdaley/AU_Mic | /band6/plots/current/stirring_separation_1D.py | UTF-8 | 952 | 2.625 | 3 | [] | no_license | import numpy as np
import astropy.units as u
import astropy.constants as c
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
from matplotlib.colors import ListedColormap
from numba import jit
rs = np.linspace(35, 45, 1000)
dist_from_ring = np.abs(40 - rs)
M_ps.max()
M_star = 0.5 * u.Msun.to('Mearth')
... | true |
a61ca7f67df7dab91e09a72110c8208d8f10e811 | Python | pengfeixiang/Statistical-Learning-Methods | /05.DecisionTree/RegressionCART.py | UTF-8 | 4,988 | 3.140625 | 3 | [] | no_license | import numpy as np
from pprint import pprint
from rich.console import Console
from rich.table import Table
import sys
import os
from pathlib import Path
sys.path.append(str(Path(os.path.abspath(__file__)).parent.parent))
from utils import *
class RegressionCART:
class Node:
def __init__(self, col, Y):
... | true |
722702908f03de926ad77fca192fc5f458bd9ede | Python | shootsoft/practice | /lintcode/NineChapters/07/combination-sum.py | UTF-8 | 762 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | __author__ = 'yinjun'
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
# write your code here
self.results = []
candidates.sort()
self.combination(candidat... | true |
b24a35cd85e8f3ec2c2a249b00592bb6e5a96183 | Python | penelopeia/snake_game | /snake.py | UTF-8 | 5,938 | 3.21875 | 3 | [] | no_license | import random
from time import sleep
import pygame
from pygame.locals import *
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
class Snake(pygame.sprite.Sprite):
x = 0
y = 0
speed = 3
length = []
length_pos = []
def __init__(self, image):
pygame.sprite.Sprite.__init__(self)
self.sna... | true |
c12f24041f7cb2b1aeb916a31b95c0ec0db699fe | Python | markovnik007/Python_lessons_basic | /lesson04/home_work/hw04_normal.py | UTF-8 | 4,756 | 2.921875 | 3 | [] | no_license | __author__ = "Вторушин Марк Викторович"
# Задание-1:
# Вывести символы в нижнем регистре, которые находятся вокруг
# 1 или более символов в верхнем регистре.
# Т.е. из строки "mtMmEZUOmcq" нужно получить ['mt', 'm', 'mcq']
# Решить задачу двумя способами: с помощью re и без.
import re
import numpy as np
line = 'mtMmE... | true |
c886f9d9f3e4182ad630721e7dfae25ac18b9158 | Python | mdhvkothari/Python-Program | /simple/alph.py | UTF-8 | 322 | 3.296875 | 3 | [] | no_license | c=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
a= input("Enter spell:")
b= int(input("Enter how many alphabate to find:"))
x= len(a)
for i in range (0,b):
count=0
c= input("Enter alphabate to find:")
for s in range (0,x):
if (a[s] == c):
count=count+1
if count==0:
print ("no alphabate")
else :
print (count)
... | true |
a88c685544dbca51a90e80d04b3b31ba359271c8 | Python | Akasan/HackerRankResult | /ProblemSolving/compare_the_triplets.py | UTF-8 | 750 | 3.0625 | 3 | [
"MIT"
] | permissive | #!/bin/python3
import math
import os
import random
import re
import sys
def compareTriplets(a, b):
tmp1 = [a[0] > b[0], a[1] > b[1], a[2] > b[2]]
tmp2 = [a[0] == b[0], a[1] == b[1], a[2] == b[2]]
a_cnt = tmp1.count(True)
b_cnt = 3 - a_cnt
for i, item in enumerate(tmp2):
if item == Tru... | true |
7f598b12fb3885c9f7821a562a19dd4ff6c9043f | Python | Himanshu-singhal-creator/Movies-Ticket-Reservation-System-Application | /Movies_Ticket_Reservation_System_Application.py | UTF-8 | 2,099 | 2.65625 | 3 | [] | no_license | #code
n = int(input())
dic1 = {}
def process(s):
def check(l):
if l[0]==-1:
l=l[1:]
if l[len(l)-1]==-1:
l=l[:len(l)-1]
for i in l:
if i!=0:
return False
return True
s=s.strip().lower().split()
screen=... | true |
31ef69bc7d293442281d39298510a4832cee1354 | Python | Moandh81/exo_python | /script1.py | UTF-8 | 201 | 3.359375 | 3 | [] | no_license | # -*- coding:Utf-8 -*-
# exercice sur les boucles
# Ecrivez un programme qui affiche les 20 premiers nombre de la table de multiplication par 7
nbre = 7
i=1
while i<=20:
print(i*7)
i=i+1
| true |
a937495078c0867be87c1208eaf4742752306d67 | Python | akt22/pagerank | /calcPageRank/job2/reducer.py | UTF-8 | 1,487 | 2.609375 | 3 | [] | no_license | #!/usr/local/bin/python
# coding: utf-8
import sys
import pdb
damping = 0.85
# どのページがどのリンクに結びついているかの辞書
# key:リンク元,value:リンク先のリスト
linkDic = {}
# last_key:リンク元,score:リンク元のスコア
(last_key, score) = (None, 0.0)
# どのページがどのリンクに結びついているかのファイルを読み込む(Job1)の出力結果
f = open('toLink2.txt', 'r')
for l in f.readlines():
fromPage, _, ... | true |
3df7e32f0666214a399fdf67f295f4df695d6b2c | Python | shelvi31/Python | /Python Practice/ReplaceXwithY.py | UTF-8 | 132 | 3.25 | 3 | [] | no_license | def replace(list, X, Y):
while X in list:
i = list.index(X)
list.remove(X)
list.insert(i,Y)
return list
| true |
804c9783776f1b15bf22d86603b9c28caff15432 | Python | Benson1198/CPP | /Random python Codes/Codechef October Challenge/Positive AND.py | UTF-8 | 165 | 3.734375 | 4 | [
"MIT"
] | permissive | arr = [2,3,1,5,6,4,8,9,7]
ans = True
for i in range(n-1):
if(arr[i] & arr[i+1] == 0):
print(str(arr[i]) + " " + str(arr[i+1]))
ans = False
break
print(ans) | true |
054812788b711ce92d2bbdb1ef69a7144849ab9a | Python | ocefpaf/python-oceans | /oceans/datasets.py | UTF-8 | 10,511 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | import functools
import warnings
import numpy as np
from netCDF4 import Dataset
from oceans.ocfis import get_profile, wrap_lon180
def _woa_variable(variable):
_VAR = {
"temperature": "t",
"salinity": "s",
"silicate": "i",
"phosphate": "p",
"nitrate": "n",
"oxygen_... | true |
6c8ea84a6e4457aec2048bbb2a6153e883d63f8e | Python | Mikleku/imgComplexity | /velvet.py | UTF-8 | 2,932 | 2.796875 | 3 | [] | no_license | from math import sqrt
from PIL import Image, ImageDraw
CL = [(1 + sqrt(3)) / (4 * sqrt(2)),
(3 + sqrt(3)) / (4 * sqrt(2)),
(3 - sqrt(3)) / (4 * sqrt(2)),
(1 - sqrt(3)) / (4 * sqrt(2))]
def hpf_coeffs(CL):
N = len(CL) # Количество коэффициентов
CH = [(-1)**k * CL[N - k - 1] # Ко... | true |
5e4077b81add71a4d0d0409b6d65017a730eb624 | Python | DEShawResearch/msys | /tools/neutralize.py | UTF-8 | 10,655 | 2.9375 | 3 | [
"LicenseRef-scancode-unicode",
"BSD-3-Clause",
"BSL-1.0"
] | permissive | """
Replace water molecules with ions
"""
import msys, math
import random
def compute_center(residue):
tm = 0.0
tx = 0.0
ty = 0.0
tz = 0.0
for a in residue.atoms:
m = a.mass
tm += m
tx += m * a.x
ty += m * a.y
tz += m * a.z
if tm:
tx /= tm
... | true |
11610749b5f9ca245e46932f207a42adf81fedac | Python | doyu/hy-data-analysis-with-python-summer-2021 | /part03-e05_correlation/src/correlation.py | UTF-8 | 438 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python3
import scipy.stats
import numpy as np
def load():
import pandas as pd
return pd.read_csv("src/iris.csv").drop('species', axis=1).values
def lengths():
d = load()
cr = scipy.stats.pearsonr(d[:,0], d[:,2])[0]
return cr
def correlations():
d = load()
return np.corrcoe... | true |
b73bf785456c50018e130374f52d70431da7fc8b | Python | gusmendez99/my-confident | /web/models/chat.py | UTF-8 | 3,299 | 2.609375 | 3 | [] | no_license | from app import DB
from datetime import datetime
class Chat(DB.Model):
__tablename__ = "chats"
id = DB.Column(DB.Integer, primary_key=True)
dt = DB.Column(DB.DateTime, nullable=False)
user1_id = DB.Column(DB.Integer, DB.ForeignKey("users.id"), nullable=False)
user1_name = DB.Column(
DB.St... | true |
fa66a3aa266c779612c55378af1fa31bf2ee8c06 | Python | aminRX/datamining | /exercise3/map.py | UTF-8 | 3,612 | 3.296875 | 3 | [] | no_license | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from statistics import mode
def pie_chart_diagnostic(df):
mean_beligno = mean_diagnostic(df, 2)
mean_maligno = mean_diagnostic(df, 4)
labels = 'Malignos', 'Belignos'
sizes = [mean_maligno, mean_beligno]
fig1, ax1 = plt.subplots(... | true |
d1406b38821e678b2169ba1ecba98b6e191d1347 | Python | jessiepyx/ComputationalGraphics | /ImageCompletion/demo.py | UTF-8 | 2,421 | 2.625 | 3 | [] | no_license | import sys
sys.path.extend(['.', '..'])
import os
import argparse
import torch
import json
import torchvision.transforms as transforms
from torchvision.utils import make_grid
from model import CompletionNetwork
from PIL import Image
from utils import poisson_blend, gen_input_mask
def show_img(tensor, nrow=8, paddin... | true |
b805538134ec24323ebadb8a8b22958f684fcd83 | Python | sunnie629/COMP560-A2 | /modelbased.py | UTF-8 | 6,299 | 3.53125 | 4 | [] | no_license | # COMP560 A2 - MODEL BASED LEARNING // Sunnie Kwak, Jacob Gersfeld, Kinsey Ness
# Goal: know the policy--> calculate transition and reward
# keep track of how many times s' follows state s when you take action a
# update transition probability after you're in the new end state
# keep track of rewards after each step
# ... | true |
099ed07746f68e7a407a7a56296dd5a16fad6abb | Python | chetnakhanna16/DS_Algo_Practice | /validBracketString.py | UTF-8 | 509 | 3.796875 | 4 | [] | no_license | def validBracketString(str):
countopen = 0
if len(str) == 0:
return True
if str[0] == ")":
return False
for i in range (0, len(str)):
if str[i] == "(":
countopen = countopen + 1
elif str[i] == ")":
if countopen > 0:
countopen = countopen - 1
else:
return False
if countopen == 0:... | true |
416fb7d6f6fd967107b62b4f9020073a34893d8d | Python | hcbh96/SC_Coursework_1 | /test_shooting.py | UTF-8 | 3,559 | 3.0625 | 3 | [
"MIT"
] | permissive | from scipy.optimize import fsolve
from scipy.optimize import newton
from scipy.integrate import solve_ivp
from scipy.integrate import odeint
import math
from shooting import shooting
import numpy as np
import pytest
def test_on_lotka_volterra():
"""This function is intended to test the generalised shooting method... | true |
89755561e666cf189aa701374ab2bff36badd1dd | Python | TanzimRusho/Codeforces_Solutions | /Problems_C/contest_1560C.py | UTF-8 | 363 | 3.296875 | 3 | [] | no_license | import math
t = int(input())
for i in range(t):
number = int(input())
seven = int(math.ceil(math.sqrt(number)))
mid = seven * seven - (seven-1)
if number == mid:
print(seven, seven)
elif number < mid:
print((seven - (mid-number)), seven)
else:
... | true |
9b99e7ee4ab5f201682000dd60bc0907995881a5 | Python | perext5528/Python_2019 | /SW Competition/18-4.py | UTF-8 | 539 | 3.546875 | 4 | [] | no_license | def PrintArray(arr):
print("Result:\n")
for i in range(0, n):
for j in range(0, n):
print("%d " % arr[i][j], end=" ")
print("")
#n = int(input("Input NxN Magic Square(N : 4의 배수) : "))
n=8
array = [([0] * n) for i in range(n)]
number1 = number2 = 1
q=1
for i in range(0,n):
for... | true |
3537f33ada6034a2a969fd490ad8e2e63ff012c5 | Python | josecervan/Python-Developer-EOI | /module2/challenges/4_decorators/main.py | UTF-8 | 739 | 3.609375 | 4 | [] | no_license | # Importa funciones y decorator
import decs
# Importa paquetes
from random import sample
from numpy import random
# Ejecuta 'N_PRUEBAS' pruebas
N_PRUEBAS = 10
for _ in range(N_PRUEBAS):
# Lista de números enteros positivos aleatorios
positives = random.choice(range(100 + 1), size=10)
# Lista de números e... | true |
4c4a8308b69a357dfa06c8e1910f0addc24a80e6 | Python | Zahidsqldba07/CodeSignal-65 | /almostIncreasingSequence.py | UTF-8 | 415 | 3.265625 | 3 | [] | no_license | def almostIncreasingSequence(sequence):
removed, max, previousMax, = 0, 0, 0
for s in sequence:
if not max or s > max:
previousMax, max = max, s
elif not previousMax or s > previousMax:
if removed:
return False
removed, max = 1, s
else... | true |
2e677fc02f09b4864716c637eab56f7c446956bd | Python | Lubhaank/MagicSquareSolver | /Magic Square Solver (Search based AI with optimized heuristics)/magic.py | UTF-8 | 17,656 | 3.390625 | 3 | [] | no_license | '''
--------------------------------------------------------------------------------
Specs: given a file like below, find a magic square with non-neg numbers
First line is dimension (n) of square
Next d lines contain the grid. -1 is placeholder for empty, modifiable value
Next line contains n row sums (first number is ... | true |
6924409bc8d37d4f9aa1c6e3f9f6d8daf0d541c3 | Python | KindSpidey/DNN | /Deep_Neural_Network/Model/plot.py | UTF-8 | 668 | 2.84375 | 3 | [] | no_license | # библиотека для рисования математических графиков
import matplotlib.pyplot as plt
# Метод использовался для отрисовки полей Record()'ов
def plot(records, id):
param_list = []
counter = 0
for pi in id:
user_list = records[pi]
for c in range(len(user_list)):
if c > le... | true |
1e10234d08bb595f88bed0ce600fa3d26e3be568 | Python | victormunduruca/soccer-annotations | /main.py | UTF-8 | 4,102 | 3.046875 | 3 | [] | no_license | import cv2
import numpy as np
import math
positions=[]
extra=[]
count=0
#Mode variable used to select one the three modes (offside (0), freekick (1) and circle (2))
mode = 0
def convert_coordinate(x, y, homography):
p = np.array((x,y,1)).reshape((3,1))
temp_p = homography.dot(p)
sum = np.sum(temp_p ,1)
... | true |
4e155974324caae2bb845f2b6cd259ba493e2813 | Python | soyNesh/dungeon | /dungeon.py | UTF-8 | 5,143 | 3.03125 | 3 | [] | no_license | import re
import graph
class Maze:
def __init__(self, maze=[]):
self.maze = maze
self.maze_graph = None
def __str__(self):
for m in self.maze:
for line in m:
print(line)
return ''
def matrix_2_graph(self):
tmp_start_id = ''
tmp... | true |
087b863726985e4b34665d7d045b04062e3b2494 | Python | dongriDK/Python | /machine learning/realworldtest.py | UTF-8 | 6,761 | 2.828125 | 3 | [] | no_license | import tensorflow as tf
"""
filename_queue = tf.train.string_input_producer(
['winequality-red.csv'], shuffle=False, name='filename_queue')
reader = tf.TextLineReader()
key, value = reader.read(filename_queue)
# 각 각 필드의 데이터 타입 정의 (float32)
record_defaults = [[0.], [0.], [0.], [0.], [0.], [0.], [0.], ... | true |
9b3f6e8f82818357b0424e4bc912874c13e3ffd1 | Python | huajianmao/pyleet | /utils/list/ListNode.py | UTF-8 | 707 | 3.796875 | 4 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import json
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
@classmethod
def stringToListNode(cls, string):
# Generate list from the input
numbers = json.loads(string)
# Now convert that list into linked lis... | true |
7611547f8265e9ca13814136c90e0ec76c4375bd | Python | Xitog/tal | /patterns.py | UTF-8 | 10,843 | 2.703125 | 3 | [] | no_license | from copy import deepcopy
class Pattern:
def __init__(self, text):
self.text = text
self.ast = parse(text)
self.extended = build_possibilities(self.ast, [[]])
self.possibilities = len(self.extended)
self.min_length = None
self.max_length = 0
for pc in s... | true |
3b1f7b877700b58302ef4e8281cee893a79843ce | Python | sankar-mukherjee/CoFee | /scikit_algo/plot_learning_curve.py | UTF-8 | 1,225 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive |
import numpy as np
from sklearn.learning_curve import learning_curve
def plot_lurning_curve(ax, clsfr, clsfr_name, X_train, y_train, sizes):
ax.set_title("Learning Curve ("+clsfr_name+")")
ax.set_xlabel("# Training sample")
ax.set_ylabel("Accuracy")
ax.set_ylim([0, 1])
ax.set_yticks(np.arange(0,1... | true |
c2bd04eea77252a33135054278d6ba70db004934 | Python | Keschler/LightTikTakToe | /main.py | UTF-8 | 3,258 | 3.625 | 4 | [] | no_license | tik_tak_toe_table = ["_" for i in range(9)]
current_player = ""
def start(started) -> None:
while True:
print_table()
if not started:
started = True
while True:
who_starts_input = input("Who should start? X or Y")
if who_starts_input == "X":
... | true |
8c1400bd99fabfd5d87936913e85c16762ad4a6e | Python | aaqibgouher/python | /test.py | UTF-8 | 1,449 | 2.96875 | 3 | [] | no_license | import pandas as pd
import numpy as np
def get_response_list_top_10(df):
df_new = pd.DataFrame()
df_new["Country/Region"] = df["Country/Region"]
df_new["Confirmed"] = df.iloc[:,-1]
df_all_new = df_new.sort_values("Confirmed",ascending=False).head(10)
print(df_all_new)
print(df_all_new.to_dict())
p... | true |
7d98b5e4ae8fe2cd516293b77df8b54d3ab83ec7 | Python | gityangyue/tlxy | /Tkinter/screensaver.py | UTF-8 | 5,350 | 3.890625 | 4 | [] | no_license | '''
项目名称 :屏保
项目分析:
1 屏保可以自己启动,也可以手动启动
2 一旦敲击键盘或者移动鼠标,或者其他的引发事件,则停止
3 如果屏保是一幅画的话,则没有画框
4 图像的动作是随机的,具有随机性,可能包括颜色,大小,多少,运动方向,变形等
程序设计
1 Screensaver:
a 需要一个canvas,大小与屏幕大小一致, 没有边框
2 Ball
a 颜色,大小,多少,运动方向,变形等随机
b 球能动,可以被调用
'''
import random
import tkinter
class RandomBall... | true |
59469f507747303a6e1a2bfcb6c87854407a5efc | Python | FabioFusimoto/tcc-scripts | /src/webcamUtilities/video.py | UTF-8 | 1,955 | 2.625 | 3 | [] | no_license | import cv2.cv2 as cv2
import numpy as np
from threading import Thread
import time
import urllib.request as urllib
class ThreadedWebCam:
def __init__(self, baseUrl='http://192.168.0.9:8080', videoWidth=320, videoHeight=240, photoWidth=4128, photoHeight=2322):
self.URL = baseUrl
self.shotEndpoint = '... | true |
cfda394e7d9ee0fe44d8ee6e3f3268210a55685d | Python | FranCorsini/work_tracker | /model/model.py | UTF-8 | 1,158 | 2.609375 | 3 | [] | no_license | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
name = Column(String, primary_key=True)
type = Column(String)
# one-to-many
... | true |
ca4d9165e36b9e214e50c3ec208ba72af64c9592 | Python | Ja-vi/location_aware | /bin/location_aware | UTF-8 | 1,965 | 2.546875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# encoding: utf-8
#------------------------------------------------------------------------------
# The MIT License (MIT)
# Copyright (c) 2014 Robert Dam (Concept, algorithms and ruby code)
# Copyright (c) 2016 Javier Gonzalez (Python code and library)
# Permission is hereby granted, free of cha... | true |
ad3b6e1c62679214c91d7da51622c7e657e507bc | Python | vantablanta/learning-python | /file3.py | UTF-8 | 2,586 | 4.5 | 4 | [] | no_license | # try and except used when waiting for a promise say in APIs
try :
if name :
print ("The try statment was succesful")
except:
print( "the try statemnt failed")
#functions
def myfunction():
print("Hello World")
myfunction()
def greeting(name):
print("Hello" +" "+name + "!")
greeting("Miche... | true |
8e97396563681ee6ba38de73793cbe84a7751805 | Python | Weida-Lin/Python001-class01 | /week01/Exercise1.py | UTF-8 | 2,381 | 2.90625 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
movie_name = []
movie_genre = []
movie_date = []
urls = []
#电影列表,提取电影名称与电影详情页面的超链接
user_agent1 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'
header1 = {
'user-agent':u... | true |
95e45ce864045662997375e939ba080740baff19 | Python | nyaruka/klab | /klab/members/models.py | UTF-8 | 6,563 | 2.546875 | 3 | [] | no_license | import logging
from smartmin.models import SmartModel
from django.db import models
from django.contrib.auth.models import User
from tempfile import mktemp
import os
from django.core.files import File
logger = logging.getLogger(__name__)
class Application(SmartModel):
"""
The application model
"""
PR... | true |
775733d6f24089d93ff7a29df8c6e41d00513b3f | Python | GayathriVenkatesh/BMTC | /code_indicators/revenue_kpi.py | UTF-8 | 1,664 | 2.78125 | 3 | [] | no_license | import pandas as pd
import datetime
import csv
def getDuration(dur):
hours = int(dur[:2])
mins = int(dur[3:5])
secs = int(dur[6:])
return hours*3600 + mins*60 + secs
def isHoliday(date):
if(date == '2018-12-25'):
return True
date_obj = datetime.datetime.strptime(date, "%Y-%m-%d").date()
week_no = date_obj.we... | true |
4fdfe7e37310e1da0ebb80161dd89becc779c781 | Python | Eileen0917/GliaCloud | /combination.py | UTF-8 | 359 | 3.46875 | 3 | [] | no_license | n = input(">>> Input n: ")
r = input(">>> Input r: ")
def mul(x,y):
return x*y
ans=reduce(mul,range(n-r+1,n+1))/reduce(mul,range(1,r+1))
print "Answer: %d" % (ans)
"""
n_factorial=n
r_factorial=1
ans=0
temp=1
while(temp<=r):
n_factorial=n_factorial*(n-1)
n-=1
r_factorial*=temp
temp+=1
ans=n_factorial/r_fact... | true |
018e121179319f96e7d4a2d7fa127091d8f1a0d4 | Python | KAMAL246-GITHUB/My-Python-Projects | /Python_Training/Session1.py | UTF-8 | 1,618 | 4.09375 | 4 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[41]:
### See your python/ Anaconda version
import sys
print(sys. version)
from platform import python_version
print(python_version())
### Start With "Hello World"
print ('Hello World')
print (4)
a = 3.5
print (type(a))
print (a)
### Constants, Variables, Assignment & ... | true |
9459f1bb3c06f828312809e89e43d85cf48edc94 | Python | vvanglro/asgi-blog-series | /asgi/server/splitbuffer.py | UTF-8 | 484 | 3.296875 | 3 | [] | no_license | class SplitBuffer:
def __init__(self):
self.data = b""
def feed_data(self, data: bytes):
self.data += data
def pop(self, separator: bytes):
first, *rest = self.data.split(separator, maxsplit=1)
# no split was possible
if not rest:
return None
els... | true |
9b70b73f02e3853e084b9e2b28aca7c4766c0a74 | Python | akrisanov/python_notebook | /packages/concurrent_futures.py | UTF-8 | 425 | 3.140625 | 3 | [
"MIT"
] | permissive | from concurrent.futures import Future
import threading
future0 = Future()
future1 = Future()
def count(future):
# doing some useful work
future.set_result(1)
t0 = threading.Thread(target=count, args=(future0,))
t1 = threading.Thread(target=count, args=(future1,))
t0.start()
t1.start()
# blocks until all t... | true |
89f7683000a671543888d3e373e10abbb2ae5a15 | Python | KiranDwaram/TrueMed-Application | /pythonscript/med.py | UTF-8 | 1,403 | 2.8125 | 3 | [] | no_license | #!/usr/bin/python
import requests
import MySQLdb
data = None
finalarry = []
db = None
medname = {}
alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
db = MySQLdb.connect("localhost","root","password","medicine_test")
cursor = db.cursor()
for letter in a... | true |
a0041a04f56a3f877a2f62022f5433cb6855d7bb | Python | sanyabeast/useful-scripts | /chatworks/webcam_gamma_backlight_control.py | UTF-8 | 2,560 | 2.703125 | 3 | [] | no_license | import time
import subprocess
import cv2
import numpy as np
import os
AUTOAJUST_INTERVAL = 15 * 60 - 1
IDLE_AUTOAJUST_TIMEOUT = 3 * 60 - 1
MAIN_TICK_DURATION = 29
MIN_BRIGHTNESS = 0.15
GAMMA_CURVE = 1/3
def is_on_battery():
return 'on-line' not in subprocess.check_output(['acpi', '-a']).decode().strip()
def ler... | true |
f997e30a534ca575a87660f709399e681ab879d9 | Python | y0shwebapp/AtCoder | /Python3/ABC101-150/ABC139/B.py | UTF-8 | 120 | 2.953125 | 3 | [] | no_license | A,B = map(int,input().split())
ans = 0
if B / A == 1:
ans = 1
else:
ans = 1 + -(-(B - A) // (A - 1))
print(ans) | true |
8c65fd7dc140ed7107d0f41e8129ad11ae7bb502 | Python | Kernos308/Python-start | /cw 6/cw6_zad4.py | UTF-8 | 116 | 2.6875 | 3 | [] | no_license | import numpy as np
def potega(n, k):
a = np.logspace(1,k,num = k,base = n)
return(a)
print(potega(2,4)) | true |
c64a402feed4f635e30058acfbba0ac705dcb0e6 | Python | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetCode/863 All Nodes Distance K in Binary Tree.py | UTF-8 | 3,718 | 3.921875 | 4 | [] | no_license | #!/usr/bin/python3
"""
We are given a binary tree (with root node root), a target node, and an integer
value K.
Return a list of the values of all nodes that have a distance K from the target
node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
... | true |
80252d9addcfa50b14ea7999bbb26b30b6afbdd5 | Python | mai20-meet/meetyl1201819 | /lab6.py | UTF-8 | 1,149 | 3.40625 | 3 | [] | no_license | import turtle
from turtle import Turtle
from random import randint
class Square(Turtle):
def __init__(self, size, color):
Turtle.__init__(self)
self.shapesize= size
turtle.shape("square")
turtle.colormode(255)
# turtle.color(color)
'''
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
turtle... | true |
42bdcf02d8196a2f8b1bc054033af1165e292241 | Python | Achamoth/CITS4403_Project_Stock-Exchange-Model | /Market.py | UTF-8 | 12,569 | 3.078125 | 3 | [] | no_license | import Graph
import SocialSphere
import random
class Investor(object):
numShares = 0
inMarket = False
node = Graph.Vertex('')
marketHistory = []
lastChange = 10000
numTimesLeft = 0
def __init__(self, numShares, node):
self.numShares = numShares
self.node = node
def en... | true |
0354f70aae94ed1b71a93c45551774a586c7b850 | Python | HaohanWang/geneExpressionRepresentation | /cnn/mlp.py | UTF-8 | 14,882 | 2.75 | 3 | [] | no_license | import os
import sys
import timeit
import numpy
import theano
import theano.tensor as T
from logistic_sgd import LogisticRegression, load_data, LinearRegression
from cnn import LeNetConvPoolLayer
from optimizers import Optimizer
def tanh(x):
return T.tanh(x)
def rectifier(x):
return T.maximum(0., x)
def lin... | true |
16622b6ec5f62c8818093255916ff867849c96f4 | Python | AZ015/design_patterns | /Behavioral/chain_of_responsibility/handler.py | UTF-8 | 458 | 2.921875 | 3 | [] | no_license | from abc import ABC, abstractmethod
from Behavioral.chain_of_responsibility import HttpRequest
class Handler(ABC):
def __init__(self, next_):
self._next = next_
def handle(self, request: HttpRequest) -> bool:
if self.do_handle(request):
return False
if self._next is not N... | true |
d09a0b9faa55c07d6f2de2edc355b8680881603b | Python | psambyal/python-examples | /test/objoriented/multiple_inheritence.py | UTF-8 | 556 | 3.3125 | 3 | [] | no_license | '''
Created on 07-Jun-2018
@author: pritika sambyal
'''
class Alpha:
def pprint(self):
print('Print from Alpha')
class Beta:
def pprint(self):
print('Print from beta')
class Charlie(Beta,Alpha):
def pprint(self):
Alpha.pprint(self) #way to print pprint of specific class
... | true |
f1d59db3e29d3ef515fc7fd048be9fa5c6c356dc | Python | jkb-dfki/workshop-ai | /templateMatching.py | UTF-8 | 951 | 2.53125 | 3 | [] | no_license | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('./slides/image.png',0)
template = cv2.imread('./slides/template.png',0)
template_width, template_height = template.shape[::-1]
response = cv2.matchTemplate(img, template,cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMa... | true |
650f448758a60d3e391c7d049915155cb735d7eb | Python | TabrisXiao/dOD | /sample/dataWrapper.py | UTF-8 | 3,770 | 3.09375 | 3 | [] | no_license |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
class data_wrapper(object):
"""
a base class for wrapper the samples into a generator feeding to nn for trainning
FUNC:
pop: (vritual) generate one sample
adjust: (vritual) adjust the data shape for trainning
generate: ... | true |
f1c55af47fe31c480e4799d27cdbbc6d79bcd47c | Python | eisengrim/karsten | /code/swansea/python_tools/ParticleFile.py | UTF-8 | 5,552 | 3.078125 | 3 | [] | no_license | #!/usr/bin/python
import ConfigParser
import re
from vecutils import s2vector, v2string
class ParticleFile:
"""Import Particle definitions from file"""
def __init__(self, pfilepath=None):
if pfilepath:
self.read(pfilepath)
def read(self, pfilepath):
"""Read details from INI st... | true |
2bde96a553185ff9f6df5c242bb68450b5b54477 | Python | malaffoon/euler | /python/problems/problem233.py | UTF-8 | 3,262 | 3.875 | 4 | [] | no_license | """Problem 233 - Project Euler
Lattice points on a circle
Let f(N) be the number of points with integer coordinates that are on a circle
passing through (0,0), (N,0), (0,N), and (N,N).
It can be shown that f(10000) = 36.
What is the sum of all positive integers N ≤ 10^11 such that f(N) = 420 ?
-------------------... | true |
dde803ddbd7a4e3ca1e78ccd2d8b21b8d118c249 | Python | baboon-king/2c | /src/classifier/model_lib/cosine_similarity.py | UTF-8 | 2,519 | 3.390625 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
"""
Created by howie.hu at 2021-04-08.
Description:余弦相似度
Changelog: all notable changes to this file will be documented
"""
from functools import reduce
from math import sqrt
import numpy as np
np.seterr(divide="ignore", invalid="ignore")
class CosineSimilarity:
"""
余弦相似性计... | true |
fe29562d60c924773531b2f30a0160ba687db058 | Python | gjain307/Autonomous-driving | /source/vehicletracker/tracker.py | UTF-8 | 5,500 | 2.84375 | 3 | [
"MIT"
] | permissive | import numpy as np
import cv2
from skimage.feature import hog
from skimage.transform import resize
from scipy.ndimage.measurements import label
from vehicletracker.features import FeatureExtractor
from collections import deque
class VehicleTracker(object):
"""
Tracks surrounding vehicles in a series of consecu... | true |
abfa0ca04f3f145ee4fd7542d884dee9b76d9ee2 | Python | hoangtuyenblogger/Thu-thap-va-tien-xu-li-du-lieu | /DOAN/Search.py | UTF-8 | 623 | 3.015625 | 3 | [] | no_license | import sqlite3
def Search():
Search_words = str(input("Nhập từ khoá tìm kiếm: "))
Search_words = "%{}%".format(Search_words)
conn = sqlite3.connect("data/DBTimviec.db")
query = """SELECT TITLE,LINK, DESCRIPTION from JOBS_DATA
where CONTENT like ? OR TITLE LIKE ? OR JOB_NAME LIKE ? OR DESCRIPTI... | true |
3fc33c2153ea2b32b4c7f2dfb5ac79d43eab9064 | Python | hyoungsp/Graphs | /Union_find.py | UTF-8 | 1,592 | 4.3125 | 4 | [] | no_license | '''
Python Code for Union-Find: using DFS Recursion
'''
from collections import defaultdict
parent = defaultdict(int)
## initialize the parent of each vertex is itself
for i in range(1, 11):
parent[i] = i
## DFS (recursively find out which vertex is a parent vertex)
def get_parent(vertex):
if parent[vertex]... | true |
b6712d284b7c077c4f6b471acf9bb5cd38d7f41a | Python | adykumar/Grind | /py_DecimalArray.py | UTF-8 | 672 | 3.0625 | 3 | [] | no_license | #-------------------------------------------------------------------------------
# Name: module11
# Purpose:
#
# Author: Swadhyaya
#
# Created: 24/12/2016
# Copyright: (c) Swadhyaya 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
def ... | true |
e09c5e89ea4dfdeb25365be56e2ca01025b31060 | Python | eduguerdex/BRT | /BRT_Bringup/src/BRT_Description/src/test_diffkine.py | UTF-8 | 2,599 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python
#
from __future__ import print_function
import rospy
from sensor_msgs.msg import JointState
from markers import *
from functions import *
# Initialize the node
rospy.init_node("testKineControlPosition")
print('starting motion ... ')
# Publisher: publish to the joint_states topic
pub = rospy.Pub... | true |
e1eaf1084174b78faf5810244fc72e6e008639ca | Python | ikoryakovskiy/curriculum_learning | /assessment.py | UTF-8 | 3,742 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
from collections import deque
import pdb
class Evaluator(object):
def __init__(self, max_action):
DXL_XM430_210_MAX_TORQUE = 3.49054054054
DXL_XM430_210_MAX_CURRENT = 2.59575289575
DXL_XM430_210_TORQUE_CO... | true |
113c2779a05f99294af7c9af8f062849fa155280 | Python | kevinschill/InstagramBot-Beta | /gui_content/settings/comment_settings.py | UTF-8 | 1,635 | 2.859375 | 3 | [
"MIT"
] | permissive | from tkinter import *
from tkinter import ttk
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
from tkinter.font import Font
class CommentSettings():
def __init__(self,gui_frame):
self.settings_tab = gui_frame
comments_today_text = tk.Label(self.settings_tab, text="max. Comment... | true |
9f440e3000005821e8da5b7c6e8374b09444fe54 | Python | possib1e/cve-2020-10977 | /exploit.py | UTF-8 | 2,213 | 2.75 | 3 | [] | no_license | #!/usr/bin/python3
import os
from gitlab import *
import urllib3
import tempfile
import argparse
# hide insecure request warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def temp_name():
return next(tempfile._get_candidate_names())
def exploit(args):
# Establish connection wi... | true |
6f8034e6dadf9a9cd60c95b04b2d6cc59f9725ac | Python | KalebeGouvea/exercicios-python | /lista05/exerc.py | UTF-8 | 196 | 3.859375 | 4 | [] | no_license | #Questão C. Entre 1067 e 3627 (inclusive), quantos números são pares e
#também divisíveis por 7?
n = 0
for x in range(1067, 3628):
if x % 2 == 0 and x % 7 == 0:
n += 1
print(n) | true |
7d4d9c9fe559982c89992ff0e3eaadc6aa260291 | Python | peter8472/GSM_SMS | /pdu.py | UTF-8 | 4,002 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | """read pdu sms format and return timestamp at least... probably more stuff"""
import sys
import pdb
import time
import re
import binascii
import StringIO
import gsm7
test_message = []
# sorry.. these were private. append your own text messages instead
"""
bitoff hshift lshift
1 0 N/A
2 <<1 >>7
3 <<2 >>6
4 <<3 >>5
5 <... | true |
b478186d707a1ddc3d46a8fc12c85fa8235facfb | Python | a-alimbai/web_new | /lab7/task1/1/d_e_67.py | UTF-8 | 274 | 3.3125 | 3 | [] | no_license | n = int(input())
list = input().split()
for i in range(n):
list[i] = int(list[i])
cnt = 0
for i in range(1, len(list)):
if ((list[i] > 0 and list[i - 1] > 0) or (list[i] < 0 and list[i - 1] < 0)):
cnt += 1
if (cnt > 0):
print("YES")
else:
print("NO") | true |
ee35ae6e18433e6108d8827282b2d5b9d4aa9d43 | Python | pg12575/TerabeeEvoPythonProcessing | /ViewRaw.py | UTF-8 | 3,373 | 2.75 | 3 | [] | no_license | import numpy as np
import matplotlib.pylab as plt
from matplotlib.pyplot import figure, draw, pause
import matplotlib
import cv2
from PIL import Image
matplotlib.use("TkAgg")
filename = "output/frameACM0.txt"
N = 32
data = np.loadtxt(filename)
data2 = np.loadtxt("output/frameACM1.txt")
numRows, _ =... | true |
8770318261bcdb047f7ee283341f2d5a7d68fc52 | Python | tesera/pygypsy | /tests/test_increment.py | UTF-8 | 1,832 | 2.546875 | 3 | [
"MIT"
] | permissive | # TODO: 0 as an input
# TODO: negative as an input
from pygypsy import basal_area_increment as incr
def test_increment_basal_area_aw():
args = []
expected = 0.010980296350305301
params = [
('SI_bh', 7.3878921344490012),
('bhage', 32.32),
('N_bh', 817.46),
('SC', .25),
... | true |
ad670d24d5496172759dd41d23921099d19eefe6 | Python | Aarav16/c-111 | /main.py | UTF-8 | 2,517 | 2.984375 | 3 | [] | no_license | import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import pandas as pd
import random
import csv
df=pd.read_csv("medium_data.csv")
data=df["reading_time"].to_list()
mean1=statistics.mean(data)
print("Mean of sample1:",mean1)
def random_set_of_mean(counter):
dataset=[]
for ... | true |
eb55b1cfb96dd960c27315c71b67193dd20d8929 | Python | JustinLove/hades-boons | /proc/sjson/test/test_sjson.py | UTF-8 | 9,582 | 3.109375 | 3 | [
"CC-BY-4.0"
] | permissive | # coding=utf8
# @author: Matthäus G. Chajdas
# @license: 3-clause BSD
import sjson
import pytest
import io
from collections import OrderedDict
import collections.abc
def testEncodeList():
r = sjson.dumps([1,2,3])
assert ("[1, 2, 3]" == r)
def testEncodeTuple():
r = sjson.dumps ((1, 2, 3,))
assert ("... | true |
0cd3730673ed2a03321fc63accbbbe7b537d05f8 | Python | puthurr/textanalytics | /tests/test_queuetrigger.py | UTF-8 | 471 | 2.78125 | 3 | [
"MIT"
] | permissive | # tests/test_queuetrigger.py
import unittest
import azure.functions as func
from functions.QueueTrigger import my_function
class TestFunction(unittest.TestCase):
def test_my_function(self):
# Construct a mock Queue message.
req = func.QueueMessage(
body=b'test')
# Call the fun... | true |
4d903991ce746c661224ca8108ed701668b90d71 | Python | amanrique1/Curso-Python | /dijkstra.py | UTF-8 | 1,829 | 3.203125 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
def darArcos(costos):
adyacentes=[]
for i in range(len(costos)):
if(costos[i]<=14):
adyacentes.append((i,costos[i]))
return adyacentes
plt.style.use('ggplot')
inicial=input("Digite el nodo inicial: ")
final=input("Digite el nodo final: ")
puntos=np.random.... | true |
391d9e5daa0f9a9beea0194e9c4773074a456d5f | Python | spdrnl/nmt_bilstm_cnn | /test_highway.py | UTF-8 | 2,785 | 2.96875 | 3 | [] | no_license | import unittest
import torch
from highway import Highway
import numpy as np
import torch.nn as nn
class TestHighway(unittest.TestCase):
def test_output_size(self):
x = torch.zeros(3, 5)
h = Highway(torch.nn.Identity(), 5)
y = h(x)
self.assertEqual(x.size(), y.size())
def test_... | true |
cc83e5c00e3160a7900a3b4eabe559c946c57c0f | Python | makeTaller/Crash_Course_Excercises | /tuples_buffet.py | UTF-8 | 148 | 3.203125 | 3 | [] | no_license | foods = ["Turkey husk", "Hogg Mauwg", "Pig feet", "dik Fish"]
#food = [item for item in foods]
for food in foods:
print("We have: " +str(food))
| true |
65c9de5363736ac992dc4acee659569b08a92cb8 | Python | Pittodo/pittodo_e1 | /classDatabaseConnector.py | UTF-8 | 423 | 3.046875 | 3 | [] | no_license | import pickle
class DatabaseConnector:
def __init__(self, file_path):
self.path = file_path
def save(self, obj):
print('(SAVE)', self.path, obj)
fj = open(self.path, 'wb')
pickle.dump(obj, fj)
fj.close()
def load(self):
fj = open(self.path, 'rb')
... | true |
62e8b32c5a5b1c56a6d51c4dff308e2c97e63453 | Python | Duanython/NLP-Parser | /dyfparser/train/train.py | UTF-8 | 2,039 | 2.859375 | 3 | [] | no_license | import torch
from tqdm import tqdm
import math
from dyfparser.utils.toolkit import AverageMeter
from dyfparser.utils.minibatches import minibatches
def train(parser, train_data, dev_data, output_path, batch_size=1024, n_epochs=10, lr=0.0005):
best_dev_UAS = 0
loss_func = torch.nn.CrossEntropyLoss()
optim... | true |
a7b69eeb177ce0556997663576aad234c8cf5420 | Python | gerrywen/pypise | /pypise/running/test_runner.py | UTF-8 | 1,193 | 2.640625 | 3 | [
"MIT"
] | permissive | # coding=utf-8
import time
import os
from .HTML_test_runner import HTMLTestRunner
import unittest
class TestRunner(object):
''' Run test '''
def __init__(self, cases="./",title="pypise Test Report",description="Test case execution"):
self.cases = cases
self.title = title
self.des = de... | true |
958a92e45d02660a013b53a22c9977422378d18b | Python | jvujcic/ProjectEuler | /063.py | UTF-8 | 274 | 3.234375 | 3 | [] | no_license | from math import log10, floor, pow
digits = lambda n: ((n==0) and 1) or floor(log10(abs(n)))+1
solution = 0
limit = 100
for n in range(1, 10):
for k in range(1, limit):
d = digits(n**k)
if d < k: break
if d == k: solution += 1
print(solution) | true |
50f10a503a63610929c4d0cd7cf15e80d9d15af3 | Python | tannonk/FS2019-TextMining | /preprocessing_scripts/uniq_counter.py | UTF-8 | 410 | 2.796875 | 3 | [] | no_license | # usr/bin/env python3
# -*- coding: utf8 -*-
import sys
import csv
file = sys.argv[1]
with open(file, 'r', encoding='utf8') as f:
reader = csv.reader(f, delimiter='\t')
uniq = set()
c = 0
for row in reader:
try:
x = hash(row[1])
if x not in uniq:
uni... | true |
7d519e1bf4cabe39cfcc1749c0976b7a6e31eaf1 | Python | jsmack/learn | /old/language/python/udemy/ds/098/98.py | UTF-8 | 151 | 2.609375 | 3 | [] | no_license | import os
print(os.path.exists('test.txt'))
print(os.path.isfile('test.txt'))
print(os.path.isdir('test.txt'))
os.symlink('test.txt', 'symlink.txt') | true |
fc60ec45583638e2cb560768d3cc37c8746f9f8b | Python | raissaccorreia/python_usefull | /list_methods.py | UTF-8 | 627 | 3.984375 | 4 | [] | no_license | a = [66.25, 333, 333, 1, 1234.5]
#insere x na posição y insert(y, x)
a.insert(2, -1)
#adicione um item no fim da lista
a.append(333)
#retorna a posição de x
a.index(333)
#remove o elemento de valor x
a.remove(333)
#reverte toda a lista
a.reverse()
#ordena
a.sort()
#retorna o numero de vezes que x aparec... | true |
7a2eaeac09fdfc331bc68b8d4f57b692c38d83ef | Python | lindo-zy/pthon-study | /chapter13.py | UTF-8 | 4,140 | 3.703125 | 4 | [] | no_license | # 正则表达式 re模块
import re
# re.match(pattern,string,flags=0)
'''
尝试从字符串的起始位置匹配一个模式,
如果不是起始位置匹配成功的话,
match()就返回none
可用group(num)或者groups()匹配对象函数获取表达式
'''
print(re.match('www', 'www.baidu.com').span()) # (0.3)
print(re.match('com', 'www.baidu.com')) # None
line = 'Cats are smarter than dogs'
matchObj = re.match(r'(.*)... | true |
55012f87112e2c568d60b795a5b965226f7df61a | Python | gjw199513/books_to_scrape | /books_to_scrape/pipelines.py | UTF-8 | 1,306 | 2.84375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
# 将评价等级转为数字
class RatingConverterPipeline(object):
rating_map = {
'One': 1,
'Two': 2,
'Three': 3,
... | true |
6a366288f75edf3546031657ad74cbe2602e82cb | Python | sjmhua1024/NLP | /CAIL2019/SCM/baseline/doc2vec/main.py | UTF-8 | 2,844 | 2.703125 | 3 | [] | no_license | import json
import jieba
import numpy as np
from gensim.models import Doc2Vec, doc2vec
import codecs
# 函数: 训练doc2vec模型
# 返回值:训练好的doc2vec模型
def train_doc2vec(train_data):
# 参数待调整
model = Doc2Vec(
train_data,
dm=0,
dbow_words=1,
size=300,
window=8,
min_count=... | true |
d2330a2e909519d6b1e1deb632ee72a0531b292d | Python | kevinuhrmacher/learning-python | /helloworld.py | UTF-8 | 229 | 3.859375 | 4 | [] | no_license | #learning python commands
print "Hello World!"
print "My name is Kevin"
print "Let's count some things"
print "Boys", 25+30/6
print "Girls", 100-25*3%4
print "Let's count the class:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
| true |