blob_id large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|
464cd9a8237c05a295596e0a152defdf80c371ca | tdf5400/SINS_navigation | /dataPack.py | UTF-8 | 889 | 3.0625 | 3 | [] | no_license | import struct
def u32ToFloat(byteData):
"""
convert u32 to float
:param byteData:
:return:
"""
byteData = byteData[::-1] # inverted order
output = struct.unpack("!f", byteData)[0]
return output
def calCRC(data): # crcData:ADDR~Datas
# assert isinstance(data, list), "crcData s... | true |
5424619b25df2ea6c7a181ae5566469fe2f8435b | JinhuaTian/Tools_Tjh | /computeRocEer.py | UTF-8 | 5,326 | 2.796875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 16:50:13 2021
@author: clemensTian
calculate ROC
input is activation matrix and its ground turth
1.calculate its cosine correlation matrix
2.compute their inner and outer correlation (average)
3.plot ROC curve and compute ROC area and EER
"""
#compute cos similari... | true |
5c47890b2d2b5b4000fa5fb50717826c59a4426c | HassanAbbas92/FacialLandmark-Live-Training | /utils/transforms.py | UTF-8 | 774 | 2.59375 | 3 | [
"MIT"
] | permissive | from __future__ import division
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
import numpy as np
class RandomRotate(object):
def __init__(self,range):
self.range = range
assert len(range) == 2
def __call__(self, img):
angle =... | true |
9e097d8f233ad663359af485a2f7acb15251f52a | salaschen/ACM | /UVA/Liu/Chapter7_BruteForce/524_PrimeRingProblem/sol.py | UTF-8 | 2,575 | 3.53125 | 4 | [] | no_license | '''
UVa 524 - Prime Ring Problem
Date: 23/Nov/2018
'''
evenCandidates = [];
oddCandidates = [] ;
def MakePrimes(up):
primes = [2,3];
cur = 5 ;
while cur <= up:
isPrime = True ;
for p in primes:
if cur % p == 0:
isPrime = False ;
break ; ... | true |
cd7cca409dae4b8a7a3c6d57b55854d3585f1946 | xiayuan/machineLearningMetric | /auc.py | UTF-8 | 2,718 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sklearn import cross_validation,metrics
import numpy as np
def read_file(pred_file, label_file):
"""
数据读取
"""
pf = open(pred_file, 'r')
lf = open(label_file, 'r')
pf_list = []
lf_list = []
for pi in pf:
pf_list.appen... | true |
7e2d1d73f52b85639726719f7a2e8227c6b1f9a5 | PhilKennedy86/DigitalCrafts-Assignments | /AlgorithymPracticeAssignmt5.py | UTF-8 | 245 | 3.96875 | 4 | [] | no_license | height = int(input("How many rows is your pyramid?: "))
bottom_length = (height*2)-1
for i in range(0,height):
row_length = (i*2)-1
spaces = int(bottom_length - row_length / 2)
print(" " * spaces + "*" * row_length + " " * spaces)
| true |
5212930b1535b86ef9b59d20728d49d9b2a62200 | GondorFu/Lintcode | /167.链表求和/Solution.py | UTF-8 | 1,244 | 3.3125 | 3 | [] | no_license | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here... | true |
e652ab9b234e642a4bab43d5b2a9a0e62aaf53fd | smqh-smqh/lecture | /人工智能实践/pandass.py | UTF-8 | 408 | 3.046875 | 3 | [] | no_license | # !/user/bin/env python
# coding:utf-8
# Author:wangyx
import pandas as pd
df= pd.read_csv("iris.txt",header=None)
x_data=df.iloc[:,0:4].values
epoch=150
flag=0
y_data=[]
for i in range(epoch):
if df.values[i][4]=="Iris-setosa":
flag=0
elif df.values[i][4]=="Iris-versicolor":
flag... | true |
53b86d1cec1c983398f3e1950cfab822bd82fbd6 | freesan44/LeetCode | /PTA_BL_1031.py | UTF-8 | 932 | 2.953125 | 3 | [] | no_license | count = int(input())
# count = int("4")
jiaquanList = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
jiaoyanMList = ["1","0","X","9","8","7","6","5","4","3","2"]
isAllPass = True
for i in range(count):
inputStr = str(input())
# inputStr = str("12010X198901011234")
inputStrList = list(inputStr)
countRes = 0
i... | true |
ba63a4593422176072a59d01f50920318163e341 | AllGoodNamesAreTaken2/AoC-2020 | /12.py | UTF-8 | 2,985 | 3.140625 | 3 | [] | no_license | from Utils import Base, read_values
values = read_values('12_value')
print(values)
pos_x = 0
pos_y = 0
way_x = 10
way_y = 1
current_direction = 'E'
dic_dir = {
'N': 0,
'E': 90,
'W': 270,
'S': 180,
}
dic_dir_rev = {
0: 'N',
90: 'E',
270: 'W',
180: 'S',
}... | true |
52b505480980006a9ea12492408beb9e4068548d | cheesemid/knightstour_jobdistribution | /job.py | UTF-8 | 1,786 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python3
import time
class Job():
def __init__(self, jobid, name, data, completedflag=False, execpy=None, callback=None, inittime=None, dispatchtime=None, expiretime=None):
'''
jobid => int id of job
name => string name of job
data => bstr pickled obj req... | true |
44c3e832172bf1afd60354572a8ed422db683830 | maxshaps/Times-Through-The-Order-Penalty | /Scripts/rename.py | UTF-8 | 915 | 2.859375 | 3 | [] | no_license | from sys import argv
from os.path import exists
import os
import string
"""
Renames a bunch of CSV files into a "<year> <blah>_<number> format.
Input: firstFileName: Name of the first file in the list of files to rename.
Must be of the format <blah>_table_<year>_<number>.
outputFileName: Name of the <bl... | true |
73f319d4951f8c698a35222e6f90d22a47c22273 | RicoWorld/Apollo3 | /file_conversion.py | UTF-8 | 3,277 | 2.859375 | 3 | [] | no_license | import pickle
import struct
import re
import os
file_index=[]
file_dic={}
def ascii_bin(file_path_in,lindex,rindex,file_path_out):
f1=open(file_path_in,'rb')
f2=open(file_path_out,'wb+')
line=f1.readline()
# for i in range(lindex,rindex-1,2):
i=0
while i < rindex-1:
if(i % ... | true |
d0fe4a1d300e5cabd3d08029c959ee51e260fa6e | cuongnguyen1402/Person-Detection | /detect.py | UTF-8 | 2,460 | 2.515625 | 3 | [] | no_license | import numpy as np
import joblib
from utils import *
from skimage.feature import hog
from imutils.object_detection import non_max_suppression
def detect(image, model='model.dat', img_w=350, img_h=0, size=(64, 128), step_size=(9, 9), downscale=2, score=1, thresh=0):
# If this is a path of image
if type(image) ... | true |
d8357e99ff5dadded131a208ba674d983a6e10bd | yangkai2/Tendorflow | /MNIST/CNN1.py | UTF-8 | 2,942 | 2.890625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu May 18 21:29:04 2017
@author: 凯宾斯基
"""
from __future__ import print_function
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist=input_data.read_data_sets('MNIST_data/',one_hot=True)
sess=tf.InteractiveSession()
#定义权重,,偏置初始化函数
... | true |
125d383c5fdcd4461532f136e41d2f4b3ec77a94 | Aliskka/First | /12_useful_modules/task_12_1.py | UTF-8 | 1,272 | 3.625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
'''
Задание 12.1
Создать функцию check_ip_addresses, которая проверяет доступность IP-адресов.
Функция ожидает как аргумент список IP-адресов.
И возвращает два списка:
* список доступных IP-адресов
* список недоступных IP-адресов
Для проверки доступности IP-адреса, используйте ping.
Адрес счи... | true |
a5e1573c353b4a7aacf23df46c1c7e7f66b5ac1e | sjwilczynski/Studies | /17-18/Winter/AI4Games/SimpleTasks/MCTS/mcts.py | UTF-8 | 1,968 | 3.1875 | 3 | [] | no_license | import sys
import math
class Vertex:
def __init__(self, score=0, n_visits=0):
self.score = score
self.n_visits = n_visits
self.children = {}
def ucb1_score(parent_node, child_node, constant):
return child_node.score/child_node.n_visits + constant*math.sqrt(math.log(parent_node.n_visits... | true |
0b5a2d760e800a61e4b2fede30fba16209dd7880 | TIS2019-FMFI/konverzia-ohlasov | /converter/file_writer.py | UTF-8 | 1,907 | 3.140625 | 3 | [] | no_license | from reference import reference
from pymarc import Record
from pymarc import Field
from pymarc import MARCWriter
class file_writer:
"""Stara sa o zapisovanie ohlasov do suboru.
"""
def __init__(self, name, encoding="utf-8", path=""):
"""Pri inicializacii sa pripravi subor na zapisovanie.
... | true |
923ce02cd47e8f34167e3bc320dc0fd31d6450d8 | Tima222/array | /code.py | UTF-8 | 305 | 3.59375 | 4 | [] | no_license | #Вычислить среднее арифметическое положительных элементов массива F(M).
a=[int(i) for i in input().split()] #Задаём массив
counter1=0
counter2=0
for i in a:
if i>0:
counter1+=i
counter2+=1
print(counter1/counter2)
| true |
32abe08689053046867c0e6729d593fbcfa2e42d | vladimir-ru/instagram_bot | /src/instabot.py | UTF-8 | 9,966 | 2.65625 | 3 | [] | no_license | # PYTHON GANG
# INSTABOT
# MAIN CODE
# AUTHOR IS VLADIMIR EGOROV
# instagram - @var_poltos
from selenium.common.exceptions import NoSuchElementException
import random
import pyautogui
import time
from selenium import webdriver
if __name__ == '__main__':
print('===================\n####PYTHON GANG####\n##instabot ... | true |
a5366f79f8b7bdee159259f480e6c82913f2449c | iZuno-K/SubgoalGeneration | /misc/_debug/debug_tf.py | UTF-8 | 2,109 | 2.703125 | 3 | [] | no_license | import tensorflow as tf
import numpy as np
from tensorflow.contrib.distributions import Uniform
def debug_pow():
dim = 4
a = np.array([np.arange(dim), np.arange(dim)]) # (batch=2, dim)
ph = tf.placeholder(tf.float32, (None, dim))
pow = tf.pow(ph, 4)
with tf.Session() as sess:
result = se... | true |
a7a5674691f941f2328518d0c0faf9cf8cb7b904 | funcionante/Essential-Hammond | /som/effects_processor.py | UTF-8 | 5,222 | 2.671875 | 3 | [] | no_license | #!/usr/bin/python
# encoding=utf-8
import wave
import json
from struct import pack
import math
from math import sin, pi
from interpreter import generate_pairs
from synthesizer import generate_sounds
rate = 44100
#returns a list that contains the multiples ([0,1]) to apply to the amplitudes with the envelope effect
d... | true |
1bc95adf2f8461021af45002165257ff2458ff50 | YangLiyli131/Leetcode2020 | /in_Python/0723 Candy Crush.py | UTF-8 | 2,123 | 3.109375 | 3 | [] | no_license | class Solution(object):
def candyCrush(self, board):
"""
:type board: List[List[int]]
:rtype: List[List[int]]
"""
m, n = len(board), len(board[0])
def check(b,i,j):
v = b[i][j]
if v == 0:
return False
if 0... | true |
b34d062c225622656d7b88c5f566ae50a38c8a60 | cosmos-sajal/ds_algo | /sliding_pattern/no_substring_repeat.py | UTF-8 | 1,170 | 3.953125 | 4 | [
"MIT"
] | permissive | # https://www.educative.io/courses/grokking-the-coding-interview/YMzBx1gE5EO
def add_in_set(alpha_set, character):
alpha_set.add(character)
return alpha_set
def delete_from_set(alpha_set, character):
alpha_set.discard(character)
return alpha_set
def get_max_length(max_len, ptr1, ptr2):
if ma... | true |
2d954e93a04fc3600075ac965b97c4cd935be17d | lakhujanivijay/GeneralProblems | /Python_Dictionary/make_dict.py | UTF-8 | 283 | 3.265625 | 3 | [] | no_license | dict={}
with open("out_1.txt") as file1:
for line in file1:
line=line.strip().split("\t")
if line[0] in dict:
dict[line[0]].append(line[1])
else:
dict[line[0]] = [line[1]]
for k,v in dict.items():
print k, ", ".join(v)
| true |
ae6d1aa2ea2301bf5117b04356683c93845c71bd | Aasthaengg/IBMdataset | /Python_codes/p03290/s960390146.py | UTF-8 | 713 | 2.53125 | 3 | [] | no_license | d, g = map(int, input().split())
PC = []
for i in range(d):
p, c = map(int, input().split())
PC.append((p, c))
PC.reverse()
ans = 10**18
for i in range(2**d):
temp = 0
cnt = 0
flag = True
for j in range(d):
if (i >> j) & 1:
temp += 100*(d-j)*PC[j][0]+PC[j][1]
cn... | true |
ff285f571c3e744f644cb03957ecb9f5997d2754 | catx0rr/bufferoverflow | /vulnserver/offset/find_offset.py | UTF-8 | 685 | 2.53125 | 3 | [] | no_license | #!/usr/bin/python3
import sys, socket
host = '172.16.10.101'
port = 9999
offset_file = 'pattern1.rb'
def read_file(file):
try:
with open(file, 'r') as file:
file = file.read()
return file.strip()
except FileNotFoundError as err:
print(err)
sys.exit()
def find_offset(host, port, offset):
while ... | true |
e1b31a259c004ca276a1cf253c07f2c230045436 | FilippoOggionni/PropagationOptimizationAssignmentsPython | /LunarAscent/LunarAscentOptimization.py | UTF-8 | 25,880 | 3.109375 | 3 | [] | no_license | """
Copyright (c) 2010-2021, Delft University of Technology
All rights reserved
This file is part of the Tudat. Redistribution and use in source and
binary forms, with or without modification, are permitted exclusively
under the terms of the Modified BSD license. You should have received
a copy of the license with thi... | true |
b9f0fa742daf4ddf8e84fc6a13f7857fd1b611d5 | biolearning-stadius/rdkit | /rdkit/VLib/NodeLib/SmartsRemover.py | UTF-8 | 3,877 | 2.6875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # $Id$
#
# Copyright (C) 2003 Rational Discovery LLC
# All Rights Reserved
#
from rdkit import Chem
from rdkit.VLib.Transform import TransformNode
class SmartsRemover(TransformNode):
""" transforms molecules by removing atoms matching smarts patterns
Assumptions:
- inputs are molecules
Sample Usag... | true |
b66b4df93a5564d647a44c8f339f483a04945204 | salimmj/Flask_login | /login.py | UTF-8 | 3,263 | 2.578125 | 3 | [] | no_license | from flask import Flask
import flask_login
#import WTForms
app = Flask(__name__)
app.secret_key = 'SECRET_KEY'
# login manager
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# sample database of users
users = {'salim@columbia.edu': {'pw': 'secret'}}
#idk what that is
class User(flask_log... | true |
52527d379d0d01f4cf0cd246c93975e255af98fd | seanmenezes/python_projects | /basic/classes/Aggregation_Example.py | UTF-8 | 1,266 | 4.25 | 4 | [] | no_license | """
Aggregation follows the Has-A model. This creates a parent-child relationship between two classes, with one class owning the object of another.
So, what makes aggregation unique?
Independent lifetimes #
In aggregation, the lifetime of the owned object does not depend on the lifetime of the owner.
The owner objec... | true |
c321a802fad8e36cc536ec7d2cfb6cc8028d5a07 | siva4646/Private-Projects | /Python_Course/LECTURES/Modules/modules.py | UTF-8 | 188 | 2.953125 | 3 | [] | no_license | import converters
print(converters.kg_to_lbs(70))
print('''
''')
print(f'50m to cm: {converters.metres_to_cm(50)}cm')
numbers = [20, 591, 45012, 399]
print(converters.find_max(numbers)) | true |
2bc5d0290757921e5a6db90649d298080371490c | Information-Fusion-Lab-Umass/flare | /src/models/image.py | UTF-8 | 2,326 | 2.59375 | 3 | [] | no_license | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def layer(x, fc, dp, bn):
return dp(F.relu(bn(fc(x))))
class Tadpole(nn.Module):
def __init__(self, num_input, num_output):
super(Tadpole, self).__init__()
self.aff1 = nn.Linear(num_input, num_output)
... | true |
c118bc8ef5a3cbcf4afcc7a024b5522b3afc463c | eyalmazuz/DeepAFM | /pyfiles/Models/ADFM.py | UTF-8 | 2,900 | 2.515625 | 3 | [] | no_license | import tensorflow as tf
import numpy as np
from tensorflow.keras import regularizers
from .Layers import PairWiseInterationLayer, AttentionLayer, PoolingLayer, ADFMLayer, DeepLayer
class ADFM(tf.keras.Model):
def __init__(self, features_dict, sparse_columns, dense_columns, embedding_size, attention_facto... | true |
06f8c5b45d71436cabdb1b264dd5dc376a31eae5 | bapuoldtown/marshmallow | /classModelsRecursion.py | UTF-8 | 294 | 2.765625 | 3 | [] | no_license | class Author(object):
def __init__(self,authorname,country):
self.authorname=authorname
self.country=country
class Books(object):
def __init__(self,bookname,author,genre):
self.bookname=bookname
self.author=author
self.genre=genre
| true |
c88a5075bc3ad93558281d78957eacd6dcd0d549 | 1930609129/all | /day3/b站1.py | UTF-8 | 1,130 | 2.546875 | 3 | [] | no_license | import requests
import os
from lxml import etree
import re
if __name__ == '__main__':
url=input("网址:")
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.80 Safari/537.36 Edg/86.0.622.43",
"referer": url
}
response... | true |
4e514d43f7df26143cb31c18f4aa1816d6fee239 | Dukemegaman/python_repo | /Python basics/5. Работа с файлами/hw_5_1.py | UTF-8 | 593 | 3.59375 | 4 | [] | no_license | """
1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
Об окончании ввода данных свидетельствует пустая строка.
"""
file = open('test.txt', 'w')
raw = input('Введите текст \n')
while raw:
file.writelines(raw)
raw = input('Введите текст \n')
if not raw:... | true |
0fed25b99417c8e2ebd799983df8c778e4e839d9 | dettore/learn-python-exercises | /_beginners python 3 source files/15. loops-and-range.py | UTF-8 | 98 | 2.953125 | 3 | [] | no_license | for i in range(1,7):
print(i)
#print("In loop")
print("\nEnd of the loop.")
| true |
ea12dc1bc3889a708bdd590f4d2d83266b1cbf29 | rimys/L3 | /slovar.py | UTF-8 | 574 | 3.4375 | 3 | [
"MIT"
] | permissive | slovar1 = {}
slovar1 = {'a' : 'azbuka', 'b' : 'bukvar'}
print(slovar1)
sl_1 = slovar1.fromkeys(['a' , 'b'], [12 , 1111])
print(type(sl_1), sl_1)
sl_1 = dict(word1 = 'hello')
print(type(sl_1), sl_1)
print(sl_1['word1'])
sl2 = {a: a**2 for a in range(10)}
print(sl2[8])
print(list(sl2.keys()))
print(list(sl2.values... | true |
397c59aa7a0064feef146197965d02b7c0f112d8 | Mkohm/Pirka | /tests/TestCourseEvents.py | UTF-8 | 1,380 | 2.8125 | 3 | [] | no_license | from unittest import TestCase
from imeapi.CourseEvents import CourseEvents, Event
class TestCourseEvents(TestCase):
def setUp(self):
self.event = Event(0, "TFY4170")
self.course_event = CourseEvents("TFY4170")
def test_get_event_day(self):
day = self.event.get_day()
self.ass... | true |
67cff8b96e6149cb4cd30082ab4d2b805a4e05bb | wangyum/Anaconda | /pkgs/numba-0.24.0-np110py27_0/lib/python2.7/site-packages/numba/tests/test_exceptions.py | UTF-8 | 6,294 | 2.640625 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | permissive |
import numpy as np
import sys
from numba.compiler import compile_isolated, Flags
from numba import jit, types
from numba import unittest_support as unittest
from .support import TestCase, tag
force_pyobj_flags = Flags()
force_pyobj_flags.set("force_pyobject")
no_pyobj_flags = Flags()
class MyError(Exception):
... | true |
55e706c60f5e9f2f52773a0af314761a89d83def | beancount/fava | /src/fava/core/group_entries.py | UTF-8 | 2,068 | 2.765625 | 3 | [
"MIT"
] | permissive | """Entries grouped by type."""
from __future__ import annotations
from collections import defaultdict
from typing import NamedTuple
from fava.beans import abc
from fava.beans.account import get_entry_accounts
class EntriesByType(NamedTuple):
"""Entries grouped by type."""
Balance: list[abc.Balance]
Clo... | true |
d833640747ec5fbf80c7af284d9af0d026d98657 | fractalram/integralstor_utils | /site-packages/integralstor_utils/certificates.py | UTF-8 | 6,817 | 2.515625 | 3 | [] | no_license | from integralstor_utils import config, command
import os
import re
import shutil
def get_certificates():
"""Get a list of certificates dicts for stored certs."""
cert_list = []
try:
certificates_dir, err = config.get_pki_dir()
if err:
raise Exception(err)
if not certif... | true |
bea858cebf044ab8c7bb0dadcb2e56089451a27a | anandrathidev/RESUMEParse | /ResumeMapper.py | UTF-8 | 2,431 | 2.578125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed May 23 10:09:16 2018
@author: he159490
"""
##################################################################
###################### Resume Mapper ############################
##################################################################
import json
def Lo... | true |
682b5442eba6bc7382d417c71a3598f16dd0c4bb | N-NEJATISHAHIDIN/ImplementationOfCompleteBalancingViaRotation | /classCBT.py | UTF-8 | 814 | 3.078125 | 3 | [] | no_license | import rootOfT
import numpy as np
from rootOfT import Node , treeQ
class CBT:
def __init__(self, root):
self.root = root
def in_order(self, start, traversal):
if start:
traversal = self.in_order(start.left, traversal)
traversal.append(start.data)
traversal =... | true |
7e30b00c505084c53c236b1133dc10fd845d2234 | a31415926/geekhub | /HT_4/2.py | UTF-8 | 1,532 | 3.796875 | 4 | [] | no_license | """Створіть функцію для валідації пари ім'я/пароль за наступними правилами:
- ім'я повинно бути не меншим за 3 символа і не більшим за 50;
- пароль повинен бути не меншим за 8 символів і повинен мати хоча б одну цифру;
- щось своє :)
Якщо якийсь із параментів не відповідає вимогам - породити виключення із в... | true |
779b756c0030db527d0edc96575a9bef6cb6ccdc | darongliu/Cross_Modal_Projection | /code/remove_blank.py | UTF-8 | 210 | 2.734375 | 3 | [
"MIT"
] | permissive | """
remove blank from image dir name
"""
import os
image_dir = "../images"
all_dir = os.listdir(image_dir)
for dir in all_dir :
os.rename(os.path.join(image_dir,dir),os.path.join(image_dir,dir.strip()))
| true |
1c4a5bd890d8dfeeaa4e1dac6b985d81974e9866 | DH-Cologne/quenfo_py | /code/training/knnclassifier/__init__.py | UTF-8 | 451 | 2.546875 | 3 | [] | no_license | """ Init-Script for knn-training."""
# ## Imports
from scipy.sparse.csr import csr_matrix
from . import gen_knn
from sklearn.neighbors import KNeighborsClassifier
import logger
# ## Function
def start_knn(tfidf_train: csr_matrix, all_classes: list) -> KNeighborsClassifier:
# Call KNN-Training function
... | true |
1d7c5a021a4a8f9677c8cf76e30eeb7ce43e5b04 | rakeshsagalagatte/STLab | /partA/check_triangle.py | UTF-8 | 563 | 3.8125 | 4 | [] | no_license | def isvalid(v):
return v>0 and v<=10
A,B,C=-1,-1,-1
while True:
try:
A,B,C=map(int,input("Enter the sides of the triangle: ").split())
except:
print("Invalid input: Wrong format.")
continue
if isvalid(A) and isvalid(B) and isvalid(C):
break
else:
print("I... | true |
e0e79f89b2f1dec25feb67df6529e983567e5f9f | breeze-Li/Alien_invasion | /game_functions.py | UTF-8 | 9,553 | 2.734375 | 3 | [] | no_license | import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
def cheek_events(ai_setting, screen, stats, play_button,
ship, aliens, bullets, sb, ):
# 监视键盘和鼠标,
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | true |
4dea98c7ac18cb248c756c72f48e8114ee107f3a | ZhengLiangliang1996/Leetcode_ML_Daily | /contest/contest279/2165_SmallestValueofRearrangedNumber.py | UTF-8 | 796 | 2.96875 | 3 | [] | no_license | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022 liangliang <liangliang@Liangliangs-MacBook-Air.local>
#
# Distributed under terms of the MIT license.
class Solution(object):
def smallestNumber(self, num):
"""
:type num: int
:rtype: int
"""
... | true |
f079f393a90507d8ec8371f65974ec4b47074251 | Wang-Yann/LeetCodeMe | /python/_1501_2000/1803_count-pairs-with-xor-in-a-range.py | UTF-8 | 4,344 | 3.59375 | 4 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Rock Wayne
# @Created : 2021-03-22 03:19:59
# @Last Modified : 2021-03-22 03:19:59
# @Mail : lostlorder@gmail.com
# @Version : 1.0
# 给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数:low 和 high ,请返回 漂亮数对 的数目。
#
# 漂亮数对 是一个形如 (i, j) 的数对,其中 0 <= i ... | true |
09f8f0e6649c2294764787ae44eca5a87c3a403c | PyCon/2013-slides | /Auth Is Hard, Let's Ride Bikes by Chris McDonough/app2.py | UTF-8 | 3,123 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPForbidden
from waitress import serve
class BlogentryViews(object):
def __init__(self, request):
self.request = request
@view_c... | true |
b063afcae31e058378ea1474a7602f5023a8a77d | dariemp/walkathon | /map2streetdata.py | UTF-8 | 3,118 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env python
import math
from xml.dom.minidom import parse
from geopy.distance import distance as geo_distance
LOCAL_COORD_ORIGIN_LATITUD = 50.8
LOCAL_COORD_ORIGIN_LONGITUD = -114.3
def earth_coord_2_local_coord(lat, lon):
x = geo_distance((lat, lon), (lat, LOCAL_COORD_ORIGIN_LONGITUD))
y = geo_dist... | true |
83ab35e7fa4cd44870dec91f6c2776afaa17df95 | protivofazza/ITEA | /Python/Lesson 5/pools_examples.py | UTF-8 | 345 | 2.953125 | 3 | [] | no_license | from concurrent.futures import ThreadPoolExecutor, as_completed
import time
executor = ThreadPoolExecutor(max_workers=100)
def sleeping(time_to_sleep):
time.sleep(time_to_sleep)
return time_to_sleep
a = []
for i in range(100):
a.append(executor.submit(sleeping, 100-i))
for result in as_completed(a):
... | true |
85c37c70c2b81926cf5e27e6c0d46c47a346de02 | cha63506/InterviewPreparations | /three.py | UTF-8 | 167 | 3.140625 | 3 | [] | no_license | ls = [-1, -2, 1, 3, 2]
maxx = ls[0]*ls[1]*ls[2]
for i in range(len(ls)-2):
prod=1
for j in range(i,i+3):
prod*=ls[j]
if maxx < prod:
maxx = prod
print maxx | true |
0b116ebad1af31880fe30234ce51f9602900b05b | piksa13/ChallengingTasks4beginners | /euler_problems/10001prime.py | UTF-8 | 351 | 3.96875 | 4 | [] | no_license | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
from prime import isPrime
primes = []
index = 10001
i = 2
while True:
if isPrime(i):
primes.append(i)
if len(primes) == index:
print(primes[index - ... | true |
78f0441079ec7ab3a19adb9cdd16903dac848977 | JoseALermaIII/python-tutorials | /pythontutorials/Udacity/CS101/Lesson 23 - Problem Set/Q4-Deep Count.py | UTF-8 | 1,135 | 4.75 | 5 | [
"MIT"
] | permissive | # Deep Count
# The built-in len operator outputs the number of top-level elements in a List,
# but not the total number of elements. For this question, your goal is to count
# the total number of elements in a list, including all of the inner lists.
# Define a procedure, deep_count, that takes as input a list, and ou... | true |
b51780fc9878d70af941f425e5cf541556aea004 | Ravi5ingh/disaster-response | /app/run.py | UTF-8 | 2,578 | 2.796875 | 3 | [] | no_license | import json as js
import plotly as pl
import flask as fl
import utility.util as ut
import global_variables as gl
app = fl.Flask(__name__)
# Initialize file names
disaster_db_filename = __file__[0:__file__.rindex('\\')] + '\\..\\data\\DisasterResponse.db'
disaster_table_name = 'Disaster'
model_filename = __file__[0:__... | true |
3d3cd6e3ec1bed960771beb57931f9f335325b18 | ahmadmostafa10495/Security | /Hill Cipher.py | UTF-8 | 1,473 | 3.171875 | 3 | [] | no_license | import math
def matrixmult (A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
print ("Cannot multiply the two matrices. Incorrect dimensions.")
return
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 fo... | true |
c13b87abb337def832a52f8d4e3a0dfda23b3ba9 | kratoslyk/ost_final | /comment.py | UTF-8 | 2,052 | 2.578125 | 3 | [] | no_license | import category
import urllib
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import os
class CommentHandler(webapp.RequestHandler):
def get(... | true |
4224c56f5868eeff2d40d2e6a997e4add8a46383 | ethresearch/Shuffle_SSLE | /python_code/fiat_shamir.py | UTF-8 | 406 | 2.640625 | 3 | [] | no_license | import hashlib
from eth_abi import encode_abi
from py_ecc.secp256k1.secp256k1 import bytes_to_int
def hash_integers(values):
k = bytes(32)
for i in range(0,len(values)):
k1 = int(values[i]).to_bytes(32, byteorder='big')
v = encode_abi(['bytes32','bytes32'],[k,k1])
k = hashlib.sha256(v)... | true |
8d01b1d08396e5fc921cc79d10f7d50c956b9773 | wuyiquan/QA | /V0.0/word_segmentation.py | UTF-8 | 6,054 | 2.5625 | 3 | [] | no_license | # /usr/env/bin python
# -*- coding: utf-8 -*-
#本代码用于对于用户上传的数据进行数据清洗及分词,字符串的分词的结果存储到一个单独的文件夹中
#sys.argv[1]代表丁香园数据的位置,sys.argv[2]代表丁香园数据中的病的种类数目(不包括0类),sys.argv[3]代表分好词的丁香园的数据位置,分词的结果也是按照病的种类编号存储在对应文件夹中
#sys.argv[4]代表存储无法分词的文件的地址的路径, sys.argv[5]为分词时分词文件的路径, sys.argv[6]为分完词后存储分词的文件为word2vec做准备的文件的路径
#sys.argv[7]代表用... | true |
c3adfe1f6832ac10e013c976d583b70c5ef575a3 | kersha38/WebLibres2 | /extras/parseTree.py | UTF-8 | 285 | 2.6875 | 3 | [] | no_license | import xml.etree.ElementTree as ET
def cataloga(archivo):
tree = ET.parse(archivo)
root = tree.getroot()
for country in root.findall('country'):
rank = country.find('rank').text
name = country.get('name')
print(name, rank)
#cataloga('prueba.html') | true |
91603ae44b8ad4968268752ad96e1e994f07cf3a | parkerdgabel/Cs110Projects2017 | /Project_12/recommender.py | UTF-8 | 5,848 | 3.59375 | 4 | [] | no_license | # Parker Gabel, CSc 110, Autumn 2017, Section 1B
# Programming Assignment #12, 11/27/17
# This program makes recommendations based on previous user ratings.
AVERAGES = "averages"
RECOMMEND = 'recommend'
QUIT = "quit"
def main():
"""Main function of the program.
Args:
None
Returns:
A+ gra... | true |
f04faa494b1acd27ec9a7ed6731352bc386bf1e6 | shuangerli/RFM | /src/script/extract_genomic_regions.py | UTF-8 | 3,022 | 3.015625 | 3 | [] | no_license | ## This script extracted the 5'UTR, CDS, and 3'UTR annotation from the transcript annotation in genepred format. Then output the files in genepred format.
## non-coding transcripts will be automatically removed.
## original programmer: Jianan Lin (jianan.lin@jax.org)
## Last edit: Jan 28th, 2019
## Contact by email f... | true |
5b8d7024d3503fef41272d07548c22f0aeca95b8 | aziznal/bank-spyders | /extract_results.py | UTF-8 | 569 | 2.546875 | 3 | [] | no_license | from shutil import copy, rmtree
import os
from os.path import isfile, isdir
from global_init import get_paths
paths = get_paths('Linux')
def check_folder_exists():
if not isdir('results'):
os.mkdir('results')
def remove_previous_contents():
rmtree('results')
def run_script():
remove_previo... | true |
43f8b3d1462c66077f004978881a8bbd311d1ef0 | kamodulin/expansion-microscopy | /processing/process.py | UTF-8 | 675 | 2.703125 | 3 | [
"MIT"
] | permissive | import cv2
import numpy as np
import os
from skimage.morphology import remove_small_objects
def read_folder_volume(path):
tiffs = [os.path.join(path, f) for f in os.listdir(path) if f[0] != '.']
fnames = sorted(tiffs)
vol = []
for i, fname in enumerate(fnames):
img = cv2.imread(fname, cv... | true |
52b837b29c481973d8bf0f44fa18618a81aa5ecd | nbcb666/DataDrivenFrameWork | /test_wmh/tuple_test.py | UTF-8 | 295 | 4.0625 | 4 | [] | no_license | #-*- coding:utf-8 -*-
#创建空元组
temp1 = ();
#如果元祖中只包含一个值,需用逗号隔开消除歧义
temp1=(1,)
#元祖的基本操作
#访问元祖,可以使用下标索引访问元素的值
temp1=('hello','world')
print temp1[1]
#world
temp1=(1,2,3,5,7,6)
print temp1[1:5] | true |
9abb891140c42d9a8ee0fc03c9456133c973d8b7 | cdelange/caseygram | /directmessages/tests.py | UTF-8 | 604 | 2.703125 | 3 | [] | no_license | from django.test import TestCase
from .models import Message
from django.contrib.auth.models import User
from django.utils import timezone
class MessageTestCase(TestCase):
def create_message(self, sender=User.objects.get(id=1), receiver=User.objects.get(id=2), content='test message'):
return Message.obje... | true |
976dce59210da8f433bf546cff36f3b682eac543 | mars2cbh/crackq | /crackq/hash_modes.py | UTF-8 | 542 | 2.875 | 3 | [
"MIT"
] | permissive | import json
class HModes(object):
@classmethod
def modes_dict(cls):
"""
Dictionary containing supported hashcat hash algorithms and
corresponding hash mode value, type and speed
Returns
-------
hash_modes: dict
dictionary containing hash modes, their... | true |
63d092db92f5ce2bb318d77bf89fa5cde44adf69 | sathayas/AnalyticsClassSpring2019 | /netCentExamples/BetweenCentral.py | UTF-8 | 2,317 | 2.96875 | 3 | [] | no_license | import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
# loading network data
G_karate = nx.read_gml('karate.gml', label='id') # Karate network
G_netsci = nx.read_gml('netscience.gml') # network science co-authorship
# betweenness centrality
Cbet_karate = nx.betweenness_centrality(G_karate)
Cbet... | true |
b13a688c8bc7cc888fcabe067b66e1c996cfa5e9 | TuxEatPi/tuxdroid | /tuxdroid/eyes.py | UTF-8 | 10,522 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | """Module defining TuxDroid Eyes"""
# pylint: disable=R0801
from concurrent.futures import ThreadPoolExecutor
import logging
import time
import types
from tuxdroid.gpio import GPIO
from tuxdroid.errors import TuxDroidEyesError
# Bounce time for rising edge detection: 100ms
BOUNCE_TIME = 0.1
# TODO Improve button bou... | true |
0edcb925103164c01fb8e280e580f3b9a1c20c2a | ZixiLi0520/nspyre | /nspyre/widgets/feat.py | UTF-8 | 5,578 | 2.59375 | 3 | [
"MIT"
] | permissive | from PyQt5 import QtWidgets, QtCore
import pyqtgraph as pg
from lantz import Q_
from collections import OrderedDict, Iterable
from nspyre.widgets.spinbox import SpinBox
def get_feat_widget(feat):
if feat['values'] is not None:
w = ComboBoxFeatWidget(feat['values'])
elif isinstance(feat['value'], (int... | true |
68e66a25a786fccd38fd0b562ab9bf58d98cf542 | santosg572/Prog-Python | /PYTHON/Python_GUI/eric6-19.11/eric/eric6/Preferences/ConfigurationPages/EditorSyntaxPage.py | UTF-8 | 2,242 | 2.515625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Copyright (c) 2011 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the Editor Syntax Checker configuration page.
"""
from .ConfigurationPageBase import ConfigurationPageBase
from .Ui_EditorSyntaxPage import Ui_EditorSyntaxPage
import Preferences
class Editor... | true |
be48dbdbf107fc130f8161b4781acf03af01d855 | notchia/heat-controlled-multistability | /modules/paraview_phase_diagram.py | UTF-8 | 12,690 | 2.65625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Render Paraview 3D phase diagram: render surface(s).
To do: add isotherm plotting, change opacity, clip a corner
@author: Lucia Korpas
"""
import os
import paraview.simple as pv
pv._DisableFirstRenderCameraReset()
def render_surface(fname,yscale=2):
''' Render a single surface, defi... | true |
b844d04898eeaf2564436791f3ba7e2e0effa7e4 | sshyran/gif2html5-app | /tests/test_context.py | UTF-8 | 1,040 | 2.546875 | 3 | [
"MIT"
] | permissive | from gif2html5.s3_manager import S3Manager
from gif2html5.config_parser import get_config
from gif2html5.date_manager import get_current_date
import os
import unittest
import tempfile
class TestContext(unittest.TestCase):
def tearDown(self):
self.delete_all_files_in_s3()
folder = tempfile.gette... | true |
c0ef5bba39f72afff93e47cba0f30b88ebe04e02 | Awerito/data-structures | /prefix-code.py | UTF-8 | 543 | 3.53125 | 4 | [] | no_license | """Given the list of simbols and its desire lenghts return is prefix code"""
import random as rnd
s = [['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']]
for i in range(len(s)):
s[i].... | true |
26c9f293d8163b91d193408264d041f5747fa06c | DaviesH79/wtfoxsay | /foxsay.py | UTF-8 | 1,425 | 3.984375 | 4 | [] | no_license | '''CS 180E, May 2018. Midterm Exam by Holy Davies'''
# What does the fox say? You're going to find out!
'''This program takes in input (animal sounds) and matches that input
to known animal sounds. If the words cannot
be matched, then we know it's what the fox said.'''
def main():
# Find out how many test cases f... | true |
337cc80c749ecf95b1ddc718859b537f2043f1a4 | zavalacl/python | /proj03old.py | UTF-8 | 3,945 | 3.890625 | 4 | [] | no_license | print("At the prompts, please enter the following:\n")
print(" Customer's classification code (a character)")
print(" Number of days the vehicle was rented (an integer)")
print(" Odometer reading at the start of the rental period (an integer)")
print(" Odometer reading at the end of the rental period (an in... | true |
7915e3e0c46d2a2c2558abf532da3549e59f00fc | dennmat/FC | /parser.py | UTF-8 | 6,552 | 2.5625 | 3 | [] | no_license | import re
import struct
from pyparsing import *
from opcodes import *
REGISTERS_MAP = dict(REGISTERS)
LABELS = {}
class Section(object):
def __init__(self, name):
self.name = name
self.offset = 0
self.stack = []
class Instruction(object):
def __init__(self, opcode, label=None):
self.opcode = opcode
sel... | true |
b29149e463d8853a0a04efa26eb880c4ae6f41a0 | motingz/leetcode | /course_schedule/canFinish.py | UTF-8 | 750 | 3.265625 | 3 | [] | no_license | def canFinish(numCourses, prerequisites):
adjList = collections.defaultdict(list)
visited = [False] * numCourses
recStack = [False] * numCourses
for pre in prerequisites:
adjList[pre[0]].append(pre[1])
for node in range(numCourses):
if not visited[node]:
if isCycle(node... | true |
4e43ef61373b983e75360690c9e4c48bda395e3c | verma-robin/pycose | /pycose/signcommon.py | UTF-8 | 2,481 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | import abc
from typing import Optional, Union
from pycose import cosebase
from pycose.algorithms import CoseAlgorithms
from pycose.exceptions import CoseIllegalKeyType, CoseInvalidAlgorithm, CoseIllegalCurve
from pycose.keys.cosekey import EllipticCurveType
from pycose.keys.ec import EC2
from pycose.keys.okp import OK... | true |
258e21e11cb88ebfa7af719bff5aeaabddc9123c | dynamicguy/wordsplit | /wordsplit.py | UTF-8 | 234 | 2.5625 | 3 | [] | no_license | import os
from flask import Flask
from ngrams import *
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def wordsplit(path):
return 'Your splitted sentence is: %s' % ' '.join(segment(path)) | true |
9ffe0ccf7d54cd4b2a5403f7fe7b4892695cc9f1 | matisyo/montecarlotreesearch | /memorymontecarlo/memcts.py | UTF-8 | 1,785 | 2.5625 | 3 | [] | no_license | import toytree
from toyplot import html
from montecarlo.nodo import Nodo
from montecarlo.uct import tree_policy, backup_negamax, default_policy, best_child
class Memcts():
def __init__(self,game):
self.root = Nodo(game,None)
self.root.action = [-1,-1]
def move(self, m):
existia = Fals... | true |
eb4a62114e50375eae17a7b4385ed89601da6537 | marek-slipski/NGIMS-temps | /src/loadfiles.py | UTF-8 | 4,250 | 2.765625 | 3 | [] | no_license | import numpy as np
import pandas as pd
import argparse
from scipy.io import loadmat
################################################################################
# Functions to work with Shane Stone's s2 files
# s2 files have calculate densities differently than standard NGIMS L2 product.
# s2 files include tempera... | true |
46aa9ff21e3356620bba92f508071da47798ad53 | DavidJanz/successor_uncertainties_tabular | /plotting/mpl_latex.py | UTF-8 | 2,268 | 2.734375 | 3 | [] | no_license | import os
import matplotlib as mpl
import numpy as np
the_textwidth = 397.4
golden_ratio = (np.sqrt(5.0) - 1.0) / 2.0
def figsize(width, ratio=golden_ratio):
fig_width_pt = the_textwidth # Get this from LaTeX using \the\textwidth
inches_per_pt = 1.0 / 72.27 # Convert pt to inch
fig_width = fig_width_p... | true |
e546745643988b75ac2592044586170cf8d6e011 | JMishou/secureStepper | /alarm.py | UTF-8 | 1,354 | 2.515625 | 3 | [] | no_license | import RPi.GPIO as GPIO #import the gpio library
import time
import signal
class alarm:
def __init__(self,gpio_in,gpio_out):
self.input = gpio_in
self.output = gpio_out
self.init = 0
self.enabled = 0
self.duration = 10
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.input, GPIO.IN, pull_up_down=GPIO.PUD_UP)
... | true |
0fb578e2ebe5bae5132661843ca427ca7614cf2f | PaviVasudev/DistracNot | /Other Files/test/speech_recog.py | UTF-8 | 440 | 2.765625 | 3 | [
"MIT"
] | permissive | import speech_recognition as SpeechRecog
from word import word_filter
import pyaudio
init_rec = SpeechRecog.Recognizer()
while True:
words = []
for i in range(3):
with SpeechRecog.Microphone() as source:
audio_data = init_rec.record(source, duration=10)
try:
text = init_rec.recognize_google(audio_data)
... | true |
9d24e0786ea876ca00cfbdb78e98931a4df05744 | Falrym/Python_Projects_CS_120 | /project_5.py | UTF-8 | 18,275 | 3.765625 | 4 | [] | no_license | import time, random, os
room_items_dictionary = {"1": "key", "2": "water bucket", "3": "steel sword", "4": "note", "5": "chest"}
door_check_dictionary = {"1": "nothing", "2": "door check", "3": "door check2", "4": "door check3"}
all_life_dictionary = {"goblin": 10, "king goblin": 50, "player": 20}
weapon_dictionary = ... | true |
3837e6dc8810a7796bde2c1593d1fc2f2afc157f | californiapolicylab/pandas-log | /pandas_log/extras.py | UTF-8 | 6,126 | 3.03125 | 3 | [
"MIT"
] | permissive | import pandas as pd
import pandas_flavor as pf
@pf.register_dataframe_method
def dq_check(df, percentiles=None, thorough=True):
"""
Expanded "data quality" check that uses pd.DataFrame.describe as a base. Reports pertinent metrics
automatically depending on datatypes present.
:param df: pd.DataFrame
... | true |
9f15bdd522dd4cbe96daaa0d8d26f48e37e51e10 | DenBlacky808/Algo | /Lesson_1/Task_1.py | UTF-8 | 319 | 3.375 | 3 | [] | no_license | """
https://drive.google.com/file/d/1aN5F58ElVzOpvGbyOQE5uCr58Hitiy6k/view?usp=sharing
"""
number = int(input('Введите трехзначное число '))
hundr = number // 100
tens = (number - hundr * 100) // 10
single = number - hundr * 100 - tens * 10
print(hundr + tens + single, hundr * tens * single)
| true |
12f7790782ffb677c218becbc1045d648cc7fc4f | lucas-devFull/fistApiDjango | /api_gui/web_scrap/api/views.py | UTF-8 | 730 | 2.53125 | 3 | [] | no_license | from .models import busca
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
import json
class BuscadorViewSet(ModelViewSet):
def create(self, request, *args, **kwargs):
dados = request.data
if "search" in dados:
web_scrap = busca(search=dados[... | true |
cfd43403e4cfa5098b2e25414aaff15240906b69 | TheAlgorithms/Python | /data_structures/binary_tree/segment_tree.py | UTF-8 | 2,346 | 3.40625 | 3 | [
"MIT"
] | permissive | import math
class SegmentTree:
def __init__(self, a):
self.N = len(a)
self.st = [0] * (
4 * self.N
) # approximate the overall size of segment tree with array N
if self.N:
self.build(1, 0, self.N - 1)
def left(self, idx):
return idx * 2
de... | true |
83553aba0952eac59b4565b7ce84dffc3fd42688 | Pytness/gtav-betting-bot | /simulator/game.py | UTF-8 | 884 | 3.0625 | 3 | [] | no_license | #!/usr/bin/env python3
import numpy as np
from collections import namedtuple
import utils
from bet import Bet
from strategies import Strategies
from constants import *
class NotEnoughMoney(Exception):
pass
class GameState:
def __init__(self, balance: int, strategy):
self.__balance = balance
self.__strategy... | true |
6f9cd090aa1297fdeff9272090e6dcb77999d02f | opasni/ElektroShag | /nejc/gui/maxval.py | UTF-8 | 1,459 | 2.625 | 3 | [] | no_license | import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import numpy as np
import re
def get_max_vals(data, vzorec, N=14):
reg = re.compile(vzorec)
plt_keys = list(filter(reg.match, data.keys()))
# d = sorted([[key, np.amax(np.fabs(data[key][10:]-np.ave... | true |
7c410885e18057ca94100b5477c143ac9aa77813 | strallis/f1weather | /weather_call.py | UTF-8 | 1,402 | 2.765625 | 3 | [] | no_license | import requests
import json
import os
from race_call import get_race_info
API_KEY = os.environ.get('WEATHER_API_KEY')
def get_weather_for_next_race():
"""
Returns a dictionary with the current weather information for the next race
"""
race_info = get_race_info()
COORDINATES = race_info["race_loc... | true |
53bbfa47df052647ada5c6abf7e77c20f05a4823 | royeectu/python-exercise | /sets/02_iterating_sets.py | UTF-8 | 164 | 4.3125 | 4 | [] | no_license | # Write a program to iteration over sets
# Create a set:
my_set = {1, 2, 3, 4, 3, 2, 1, 'Royee'}
# Let's iterate over the elements:
for i in my_set:
print(i)
| true |
2750a250619b9a56b7e3bf410c9fb683b36c9c17 | dar4kamal/Proplem_solving | /CF381-D2-A.py | UTF-8 | 460 | 2.9375 | 3 | [] | no_license | numberOfCards = int(input())
SerejaScore = 0
DimaScore = 0
cards = [int(i) for i in input().split()]
for i in range(numberOfCards):
if i%2 == 0:
SerejaChoice = max(cards[0],cards[len(cards)-1])
cards.pop(cards.index(SerejaChoice))
SerejaScore += SerejaChoice
else:
DimaChoice =... | true |
68d1553c32ef40c40e24d513341488da8e87da7c | shedolkar12/DS-Algo | /binary_search/matrix_search.py | UTF-8 | 1,019 | 3.03125 | 3 | [] | no_license | #idea is use two binary search. one for searching subarray and one for that eemeny from that subarray
def check(A,B):
low = 0
high = len(A)-1
while low<=high:
mid = (low+high)/2
if A[mid]==B:
return 1
elif A[mid]>B:
high = mid-1
elif A[mid]<B:
... | true |