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 |
|---|---|---|---|---|---|---|---|---|---|---|
f6300f4cbc6119b8b426e3ac003b092afb3ac777 | SPARgroup/Python-Problems | /HackerRank/MatrixRotation.py | UTF-8 | 1,172 | 2.828125 | 3 | [] | no_license | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the matrixRotation function below.
def matrixRotation(m, n, matrix, r):
layers = []
for i in range(min((m, n)) // 2):
#Layers loop
xlim = (i, n-i)
ylim = (i, m-i)
#Unwrap layer
#Step1:
... | true |
70e162a8c3f7827d2dbe6f7156d78c94f73981a9 | brianbirir/python-sandobox | /oop/classes/max_size_list.py | UTF-8 | 529 | 4.125 | 4 | [] | no_license |
class MaxSizeList:
def __init__(self, max):
self.max_size = max
self.inner_list = []
def push(self, obj):
self.inner_list.append(obj)
if len(self.inner_list) > self.max_size:
self.inner_list.pop(0)
def get_list(self):
return sel... | true |
2ce9ba7035668f3ac9296ef6cc22d11a49cb529d | drstrange11/code | /player_35.py | UTF-8 | 126 | 3.265625 | 3 | [] | no_license | #AJ_35
import string
a=input()
a.split()
a=a.replace(" ","")
b=[i for i in a if a.count(i)==1]
c=' '.join(b)
print(c)
| true |
093529ee88c8b6160c50b10f11163a6e1329cbad | fsancho1985/Infinity_school | /Aula_Presencial_19-06/Folha.py | UTF-8 | 575 | 3.5625 | 4 | [] | no_license | class Folha:
def __init__(self, funcionarios):
self.__funcionarios = funcionarios
# getters
@property
def funcionarios(self):
for f in self.__funcionarios:
print("Funcionário: ", f.nome, "Salário: ", str(f.salario))
# Setters
@funcionarios.setter
... | true |
4b0a584805ddd38828ea3fec225d4b766c775e18 | BoardGamesQuest/Board-Games | /Sushi-Go/CardEval.py | UTF-8 | 7,605 | 3.046875 | 3 | [] | no_license | from AbstractPlayer import Abstract
import copy
def replicate(inp): #copy doesn't really work for maintaining the same instance of objects, but this will (JANK)
if type(inp) != list:
new = [inp] + [0]
new.pop()
new = new[0]
else:
new = inp + [0]
new.pop()
return new
... | true |
7eda2a7226203d9933fd3444725215553b2906b2 | bartdegoede/datastructures | /trees/tests.py | UTF-8 | 344 | 3.03125 | 3 | [] | no_license | from trees import binary_tree, binary_search_tree
from trees.traversal import inorder, preorder, postorder
if __name__ == '__main__':
print('In order:')
inorder(binary_search_tree)
print('=' * 80)
print('Preorder:')
preorder(binary_search_tree)
print('=' * 80)
print('Postorder:')
postor... | true |
26fc401681a617659d13752cf6a3dfd36ca6a55e | pauldubois98/PercolationFractalsStudy | /data_visualization/complement_semi_straight_crossingsData3D.py | UTF-8 | 470 | 2.59375 | 3 | [] | no_license | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('data/complement_crossings_semi_straight_3D_50000.csv')
data = data.sort_values(["p", "d", "n"])
data["cp"] = data["nc"] / data["rep"]
data["max"] = data["rep"] * ((data["n"]**(data["d"]))**2)
data["density"] = data["sq"] / data... | true |
3507bb5c67ce72e4d3b82df503a12210ce5e63fe | jxx1998/translator-attribution | /data/BZL_Macbeth_Preprocess.py | UTF-8 | 1,191 | 2.59375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | import re
bzl_file = open('BZL-Macbeth-Preprocessed3.txt', 'r')
lines = bzl_file.readlines()
bzl_file.close()
processed = []
# for line in lines:
# line = re.sub(r'\d+', '', line)
# if line:
# processed1.append(line)
#
# characters = "女巫甲 |女巫乙 |女巫丙 |顿 |玛 |队长 |列 |麦 |麦夫人 |多 |罗 |门 |安 |凯 |弗 |西 |士兵 |小西 |瑟... | true |
55d777a472bfbb537be0e24e9222dff2d77bb330 | saturnin13/poetry-generation | /src/RNN.py | UTF-8 | 3,691 | 2.78125 | 3 | [] | no_license | # Code inspired by https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py
from __future__ import print_function
import os
import random
import sys
import numpy as np
from keras.callbacks import LambdaCallback
from keras.layers import Dense
from keras.layers import LSTM
from keras.models imp... | true |
e1db920169f8d78776a85a12468fb36f1b063473 | ssyu0808/HFUTICS | /hfutics.py | UTF-8 | 3,367 | 2.671875 | 3 | [] | no_license | import hashlib
from jxglstu import hfut
def datumToIcs(datum: dict):
result = datum['result']
lessonList = result['lessonList'] # 课程信息
scheduleList = result['scheduleList'] # 每一节课
scheduleGroupList = result['scheduleGroupList'] # 选课信息
lessonName = {lesson['id']: lesson['courseName'] for lesson ... | true |
8cca9d7d7af84286e90b7dead8d6f8dc9e2f5b9f | razerboot/DataStrcutures-and-Algorithms | /python/codemonk_ez.py | UTF-8 | 704 | 2.8125 | 3 | [] | no_license | from operator import itemgetter
import heapq as pq
from collections import defaultdict
t = input()
for x in xrange(t):
v, e = map(int, raw_input().split())
graph = defaultdict(dict)
for f in xrange(e):
x, y, w = map(int, raw_input().split())
graph[x][y] = w
q = []
print graph
fo... | true |
41ef7101989ea172e135686b86ad5c2263ab00db | JayWelborn/HackerRank-problems | /python/python-language/sets/symmetric_difference.py | UTF-8 | 309 | 3 | 3 | [] | no_license | a = int(input())
# make first set
M = set(map(int, input().split()))
b = int(input())
# make second set
N = set(map(int, input().split()))
# get difference
diff_1 = list(M.difference(N))
diff_2 = list(N.difference(M))
difference = diff_1 + diff_2
# print difference
[print(x) for x in sorted(difference)] | true |
9c84a253efc13b7b47f083eaf65f701cca4471b1 | GCSec-Gloscol/Liam-Jack | /Task 4.py | UTF-8 | 123 | 3.796875 | 4 | [] | no_license | name = input("enter name: ")
address = input("enter address: ")
print("Your name is ", name ," and you live at ", address)
| true |
9064d5564b862b1eac5993ad1aa06862278e8d23 | Tjejer/game | /player.py | UTF-8 | 799 | 3.71875 | 4 | [
"MIT"
] | permissive | """Class for player."""
class Player():
"""Player classing."""
def __init__(self, player_id, name):
"""Player created."""
self.player_id = int(player_id)
self.name = name
self.current_score = 0
def change_name(self, new_name):
"""Change the players name."""
... | true |
a959e9e97875380c46a99c71fd98359aae069d16 | dev-yohan/football_bets | /leagues/models.py | UTF-8 | 2,042 | 2.671875 | 3 | [] | no_license | from django.db import models
from cloudinary.models import CloudinaryField
from django.template.defaultfilters import slugify
# Create your models here.
#Model for football leagues
class League(models.Model):
name = models.CharField(max_length=200)
short_description = models.TextField(max_length=1000)
lo... | true |
dd31e4ba1783527a028e4dbab4db04b92068f967 | itdxer/naive-bayes | /examples/imdb_reviews/__main__.py | UTF-8 | 4,071 | 2.75 | 3 | [
"MIT"
] | permissive | import os
import time
import ntpath
from optparse import OptionParser
import numpy as np
from skll.metrics import kappa
from nltk.corpus import stopwords
from pandas.io.parsers import read_csv
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report, accuracy_score
from n... | true |
d00c09a6c9f020c2546746a148f190edd1a388c7 | shuvorahman/Hackerrank | /day_8.py | UTF-8 | 484 | 3.8125 | 4 | [] | no_license | # day 8 : Dictonaries and Map
# Enter your code here. Read input from STDIN. Print output to STDOUT
entry = int(raw_input().strip())
phone_book = dict()
for i in range(entry):
data = raw_input().strip().split(' ')
if data:
phone_book[data[0]] = data[1]
while True:
try:
data = raw_input().s... | true |
f7c9bf07c0da21b0ebbc025acc292fbfce4c5c3c | curtank/spamwork | /filewalker.py | UTF-8 | 535 | 2.640625 | 3 | [] | no_license | import os
def walkinrootdir(rootdir):
errcount=0
for parent,dirnames,filenames in os.walk(rootdir):
for filename in filenames:
try:
f=open(parent+'/'+filename,'r',encoding='gb18030')
yield f,filename,parent
except:
print('err'+paren... | true |
ec16e026c57d62710a19bfba13751af5c1fb1c4e | yuweiwan/ML-dimension-reduction | /test.py | UTF-8 | 1,089 | 3.046875 | 3 | [] | no_license | import numpy as np
def txt_to_matrix(filename):
file = open(filename)
lines = file.readlines()
datamat = np.zeros((800, 13))
row = 0
for line in lines:
line = line.split(" ")
line = [float(x) for x in line]
datamat[row, :] = line[:]
row += 1
return ... | true |
1349b6293061a20a9c43f12a6d086d760b6ae1be | prismofeverything/school | /computationalneuroscience/python/assignment1.py | UTF-8 | 5,064 | 2.796875 | 3 | [] | no_license | import numpy as np
from itertools import chain
from neuron import *
import plot
def assign_hoc_globals(hoc):
for key in hoc.keys():
h(key + ' = ' + str(hoc[key]))
# a basic class for the hodgkin-huxley neuron model.
class SimpleHH:
def __init__(self):
self.duration = 5
self.settings =... | true |
d856e2a0ddcb7b59d9517360c64ec1015e7df476 | thanus/myriad-ql | /MaikelGerard/QLS/stages/type_checker.py | UTF-8 | 3,439 | 2.640625 | 3 | [] | no_license | class TypeChecker(object):
def __init__(self, qls_ast, qls_env, ql_ast, ql_env, error_handler):
self.ast = qls_ast
self.env = qls_env
self.ql_ast = ql_ast
self.ql_env = ql_env
self.handler = error_handler
def start_traversal(self):
self.env.clear_env()
se... | true |
48bed03147c045d529a4d6b988979328ccc344d0 | gdmgent-1718-wot/Hardware | /rpi-flotilla/modules/rainbow/rainbow.py | UTF-8 | 1,084 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | """
==============================================
Rainbow - Flotilla
==============================================
Example with the 'Rainbow'-module
----------------------------------------------
Course: Web Of Things (WOT)
Option: New Media Development
Department: Graphic and Digital Media
College: Arteve... | true |
bee5549e3569024f3763c5504b89399a4d69ec77 | tuliocl/Minicurso-python---POO | /util.py | UTF-8 | 370 | 3.265625 | 3 | [] | no_license | class util:
def Cast(option):
try:
aux_int = int(option)
return aux_int
except:
return -1
def Cast_float(number):
try:
aux = float(number)
return aux
except:
print("ERRO AO CONVERTER")
print(... | true |
58d134f96525ec58f85ef727083709d86875de31 | Apocilyptica/Python_notes_school | /Variables/strings/negative_index.py | UTF-8 | 80 | 3.140625 | 3 | [] | no_license | sentence = 'The quick brown fox jumped over the lazy dog.'
print(sentence[-4:]) | true |
8801c22fee39af44c42ad5127a4d1fd88ec43189 | defiasto/OPR | /L9/1.py | UTF-8 | 90 | 3.25 | 3 | [] | no_license | i = 0
x = str(123456)
a = []
while i < len(x):
a.append(int(x[i]))
i += 1
print(a[::-1]) | true |
66074ec598ccd9f211820cf69719fc6f0d45e8d1 | warriorarmentaix/lfd | /point_clouds/features.py | UTF-8 | 1,094 | 2.5625 | 3 | [] | no_license | """
Point cloud features
"""
from __future__ import division
from jds_utils import math_utils
import numpy as np
def cloud_shape_context(cloud, hist_dim):
return np.array([point_shape_context(pt, cloud, hist_dim) for pt in cloud])
def point_shape_context(pt, cloud, hist_dim):
cloud = np.atleast_2d(cloud) - ... | true |
636cad1f98869a5fb48529f4d732da4453ab7519 | TheoryDance/mypyworkspace | /base_demo/plt_demo.py | UTF-8 | 385 | 3.203125 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
plt.plot((2,4,6,8),'k--')
ax3 = fig.add_subplot(2,2,3)
from numpy.random import randn
plt.plot(randn(50).cumsum(), 'k--')
ax1.hist(randn(100),bins=20,color='k',alpha=0.3)
a... | true |
b40f3834eafa0f2ba2d989d94fbcd2b722f8f33a | JanDimarucut/cp1404practicals | /prac_02/capitalist_conrad.py | UTF-8 | 1,866 | 3.59375 | 4 | [] | no_license | #import random
#MAX_INCREASE = 0.175 # changed increase from 10% to 17.5%
#MAX_DECREASE = 0.05 # 5%
#MIN_PRICE = 1 # changed price from 0.01 to 1
#MAX_PRICE = 1000.0 # changed the price from 1000 to 100
#INITIAL_PRICE = 10.0
#OUTPUT_FILE = "output_stock"
# Added the output file
#out_file = open(OUTPUT_FILE, 'w')
... | true |
71b7f025de014e4560104a9e69b0303cb4551f90 | ParthSolanki1/LeetCode | /476-numberComplement.py | UTF-8 | 244 | 3.5625 | 4 | [] | no_license | def getBinaryComp(num):
binary = ""
finalVal = 0
i = 0
while num != 0:
val = num % 2
if(val == 0):
finalVal += 2**i
num = num // 2
i += 1
return finalVal
print(getBinaryComp(5)) | true |
87f2d29527d25b38224b9d98da11f0d613ddb7bf | zarkaltair/Data-Scientist | /Scikit-learn/mlcourse.ai/Task_5_bagging_randomforest/mlcourse_ai_task_5_article.py | UTF-8 | 21,159 | 2.953125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
from matplotlib import pyplot as plt
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = 10, 6
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')
telecom_data = pd.read_csv('telecom_churn.csv')
fig = sns.kdeplot(telecom... | true |
417772faaeb843fa0cf437393ad560f3cfaab554 | NAV-2020/nichipurenko | /Lesson_19_Nichipurenko_A.V/Lesson_19_Nichipurenko_A.V.py | UTF-8 | 289 | 2.9375 | 3 | [] | no_license | """
import struct
ls = [1,3,9,12]
obj = struct.pack('>4i', ls[0], ls[1], ls[2], ls[3])
size = struct.calcsize('>3f')
print('obj:', obj)
print('size', size)
"""
import pickle
#pickle.dump(object, )
my_list = [1,2,3,4,5]
f = open('my_file.bin', 'wd')
pickle.dump(my_list, f)
f.close() | true |
6d4065751bd3fc243d1a0d44d6d9292b0e7e85b3 | sds1vrk/Algo_Study | /Inflearn_algo/section5_StackQueueHash/pro_9_HashDic.py | UTF-8 | 799 | 3.65625 | 4 | [] | no_license | # 아나그램
# 딕셔너리 해쉬
# str1, str2 입력
# str1[A]=1
# str1[A]=str1[A]+1
# 이렇게 해버리면 키값이 없는 경우가 발생 가능
# 따라서 str1[A]=str1.get('A',0)+1 을 이용하여 없으면 str1[A] return, 없으면 0을 리턴
import sys
sys.stdin=open("input.txt","r")
n=list(input())
n.sort()
m=list(input())
m.sort()
n_dict=dict()
for x in n:
# get을 이용해서 만약 키 값이 있으면 그걸 사용하... | true |
3a04d2c99e6c7864ba16885f3071bcae4223dadd | SurendraKumarAratikatla/MyLenovolapCodes1 | /Python/Python All in 1 Codes/advanced/Data Structures/User defined Data Types/Linear DS/Linked Lists/Practice/liked_list_practice2.py | UTF-8 | 2,186 | 4.25 | 4 | [] | no_license | class Node:
def __init__(self,data = None, next = None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_begining(self,data):
node = Node(data, self.head)
self.head = node
def insert_at_ending(self,data):
... | true |
ced067e82977c5ba90ee0623ae0218cfda72d1b4 | nitzan89/python | /secretnumber.py | UTF-8 | 165 | 3.90625 | 4 | [] | no_license | secret = 6
guess = input("Guess a number:")
if guess == secret:
print "Congrats! You guessed it!"
if guess != secret:
print "Sorry, wrong number!" | true |
82507bd41df0c933a369063bb45ed42a744918f6 | rogerdahl/copy-mp3-to-soundfly | /copy_mp3_to_soundfly.py | UTF-8 | 3,105 | 2.828125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
"""Copy MP3s to a SoundFly AUX in such a way that the SoundFly plays the MP3s in album order.
"""
import os
import re
import shutil
import sys
import id3reader
MUSIC_SRC_PATH = os.path.abspath('./music')
SOUNDFLY_ROOT_DIR_PATH = os.path.abspath('./soundfly')
def main():
if not os.path.i... | true |
0756fc51ce4a4580649f9bc06ddb75c191e59851 | n03076944/ELSpring2016 | /code/myBlinkingLed.py | UTF-8 | 880 | 2.59375 | 3 | [] | no_license | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.OUT)
def Blink():
while True:
GPIO.output(17,True)
time.sleep(1)
GPIO.output(17,False)
time.sleep(1)
GPIO.output(17,True)
time.sleep(1)
GPIO.output(17,False)
time.sleep(1)
GPIO.output(17,True)
time.s... | true |
50098214d89ce1e1249b5bc1a0f8a03e4145f427 | ivanzzh/asr_preprocessing | /timit/input_data.py | UTF-8 | 11,171 | 2.515625 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Make input features (TIMIT corpus)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join, basename
import numpy as np
import pickle
from tqdm import tqdm
from utils.util import mkdir... | true |
56f8b62130e19bc480791d7d927b075aac5423b1 | eda3/python_slack_message_ranking | /slack_message_ranking.py | UTF-8 | 3,915 | 2.96875 | 3 | [] | no_license | # import argparse
import json
import os
import sys
import unicodedata
from typing import List, Tuple
def main() -> None:
# 引数チェック
args: List[str] = sys.argv
# 引数パーサを作成
# s: str = "Slackの全メッセージをエクスポートしたデータをランキング順 or 最終書き込み日順に表示する"
# parser = argparse.ArgumentParser(description=s)
if not check... | true |
40da82a2152da8529417c9a458e6a97e90ef87a5 | madhuri2k/fantastic-spoon | /scripts/test_logger.py | UTF-8 | 481 | 3.09375 | 3 | [
"MIT"
] | permissive | #import logging module
import logging
#Create a logger object
logger=logging.getLogger()
#Configure logger
logging.basicConfig ( filename="test.log", format='%(filename)s: %(message)s', filemode='w')
#Setting threshold level
logger.setLevel(logging.DEBUG)
#Use the logging methods
logger.debug("This is a debug message")... | true |
496e29b767c84ba41219566a1bab20803d8d01f7 | MrGandalv/MUGGE | /src/gridforMLP_10k.py | UTF-8 | 5,390 | 2.71875 | 3 | [] | no_license | from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import GridSearchCV
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
import csv
... | true |
4ef5dcae4acda76f8e94f35979de399a209098a6 | Lifestohack/pupil-video-backend | /others/network_latency.py | UTF-8 | 1,106 | 2.640625 | 3 | [] | no_license | from time import time, sleep
from pupil import PupilManager
import log, logging
def get_network_latency():
host = "10.3.141.136"
port = "50020"
pupil = PupilManager(host, port)
times = []
logging.info("Calculating the network lateny...")
for _ in range(100):
sleep(0.003) # simulate sp... | true |
e1ce29b2ef76fb7e58e5e38a93ecf9368a4fa51d | Hamidreza3252/Extended-Kalman-Filter | /old versions/particles-filter.py | UTF-8 | 5,616 | 3.90625 | 4 | [
"MIT"
] | permissive | # 1
# Once again, your robot starts at 30, 50, heading north (pi/2), then turns clockwise
# by pi/2, moves 15 meters, senses, then turns clockwise by pi/2 again, moves 10 m, then senses again.
# 2
# Now add noise to your robot as follows: forward_noise = 5.0, turn_noise = 0.1, sense_noise = 5.0.
# Your program shou... | true |
d116e8a803d254a4675a29818c965130f85aa729 | abhipsb/python-pactman-demo | /consumer/src/test_consumer.py | UTF-8 | 1,185 | 2.796875 | 3 | [] | no_license | """pact test for consumer"""
import pytest
import atexit
import unittest
import requests
from pactman import Consumer, Provider, Like
from consumer import UserConsumer
pact = Consumer('Consumer').has_pact_with(Provider('Provider'))
#print('start service')
#pact.start_service()
#atexit.register(pact.stop_service)
con... | true |
75159f0841153157592bdf74e0c572111ecbf2b7 | sainiudit/datasci-open-data-search | /helper_modules/NER_people_location.py | UTF-8 | 2,345 | 3.0625 | 3 | [] | no_license | import cPickle, numpy as np, pandas as pd , re
from collections import Counter
from polyglot.text import Text
'''
The purpose of this py file is to identify people and locations mentioned in the
SF open data portal
This has two functions, one for people and one for locations.
Afterwards the data is saved into a csv... | true |
af1f5abb78b82c4eb982ed4e980f499db2c1335a | ajw2329/multi_species_as_events | /rename_events_in_ioe.py | UTF-8 | 3,148 | 2.875 | 3 | [] | no_license | '''
Rename event ids in splice_lib_events.ioe files
Intended for situations where new consensus event
ids are created for orthologous events in
multiple species.
Takes as input an ioe file and final_original_name.tsv
(from multi_species_events_standalone.py) and writes
new ioe file with the consensus event id from... | true |
706afb0b3da2449ea616464cb6aea9b0599bd13e | awin2019/python-challenge | /PyPoll/main_PyPoll.py | UTF-8 | 2,760 | 3.515625 | 4 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import csv
election_data = os.path.join("..", "Resources", "election_data.csv")
# In[2]:
#set up my variables for counting all the votes
#setting up lists seems to make the most sense b/c there will be multiple candidates to track
candidates = []
total_vot... | true |
e3d6dee531b5f81a8d790c196a646bc172503e89 | sdpython/ensae_projects | /_unittests/ut_data/test_stations_chicago.py | UTF-8 | 1,749 | 2.75 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
@brief test log(time=50s)
"""
import sys
import os
import unittest
import random
from datetime import time
import pandas
from pyquickhelper.pycode import get_temp_folder, ExtTestCase
from ensae_projects.datainc.data_bikes import (
get_chicago_stations, folium_html_stations_map, add... | true |
dfef66a8af0980bb54d1459569ad3f26b138aa99 | sentairanger/Dual-Robot-Guizero-Control | /dual_movement_gui.py | UTF-8 | 4,603 | 3.1875 | 3 | [
"Apache-2.0"
] | permissive | # import libraries
from guizero import App, PushButton, Slider, Text, Window
from gpiozero import OutputDevice, PWMOutputDevice, AngularServo
from gpiozero.pins.pigpio import PiGPIOFactory
#Define the app and window for the servo sliders
app = App("Dual Robot Control", layout='grid')
servo_window = Window(app, "Servo ... | true |
423662d95b9af4d436955fcd0966f494a96121c0 | dankerri/python-time-tracking | /time_tracking.py | UTF-8 | 8,385 | 2.875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import time
from PIL import Image
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.figsize'] = (18.0, 8.0) #figure窗口的大小
OR_LOG = './or_log.txt'
LOG = './out... | true |
bb97d87d2f1cec0192f49ff12089cd263c8fcb32 | kiafar/py-airline | /data/fuelprice.py | UTF-8 | 2,516 | 3.734375 | 4 | [
"BSD-2-Clause"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
fuel module extracts and represents fuel data.
@since:12/04/2016
@author:Tirdad Kiafar
"""
from data.fileIO import IO
UNIT = 'EURO/LITTER'
UNIT_SHORT = 'eu/lit'
###############################################################################
class FuelObj:
def __in... | true |
f91e310da05e605a75cb0d228d259057fe69176b | rpedraza01/pdxcodeguildprojects | /blackjack_advice_lab_19.py | UTF-8 | 817 | 4.15625 | 4 | [] | no_license | #blackjack_advice_lab_19.py
print("Welcome to the Blackjack Advisor. Let's get you some wins!")
card_dict = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "J": 10, "Q": 10, "K": 10}
card_hand = []
first_card = input("What is your first card? > ")
card_hand += first_card
second_card ... | true |
3e79c7dcf82d84d2636999ae1fb1548a5b85b47e | ZhangPeibin/Time | /show_time_api/models.py | UTF-8 | 2,595 | 2.9375 | 3 | [] | no_license | # coding=utf-8
from werkzeug.security import generate_password_hash
from werkzeug.security import check_password_hash
from flask_login import UserMixin
import json
import uuid
PROFILE_FILE = "profiles.json"
class User(UserMixin):
"""
username = [password_hash,id]
"""
def __init__(self, username):... | true |
c960b79ed1ccb12108e2138cca6acc5915ef97a2 | michellekoks/quora-duplicate-detection | /scripts/2.Google_embedding_preparation.py | UTF-8 | 2,476 | 2.640625 | 3 | [] | no_license | import pandas as pd
import numpy as np
from gensim.models import KeyedVectors
from nltk.corpus import stopwords
from tqdm import tqdm
print('Loading the tokenized data...')
default = '.'
token_train = pd.read_pickle(default + "/data/token_train.pkl")
token_test = pd.read_pickle(default + "/data/token_test.pkl... | true |
bdb142ec4458f1aba9d9a7b29037658aab7156ec | daniel-reich/ubiquitous-fiesta | /2wJrWniq8yz79Yvgv_23.py | UTF-8 | 89 | 3.015625 | 3 | [] | no_license |
def is_narcissistic(n):
n = str(n)
return sum(int(i)**len(n) for i in n) == int(n)
| true |
781af370bddc9ea03f11ba074c22a693f840967a | ArjavJain123/my-first-github-project | /Python Projects And Works/pyhtonloops/python loops.py | UTF-8 | 1,008 | 4.34375 | 4 | [] | no_license | """
# python loops
print("python has two major loops:\n1.)while loop\n2.)for loop")
print("\n\n\n\while loop is the loop, in which the command in the loop repeats till the condition becomes true")
"""
i = 1
while i < 6:
i += 1
if i == 3:
continue
print(i)
while i == 6:
i += 1
... | true |
36a31eab5c76952eb58713d9aafa112ef0121934 | zmfkzj/deeplearning-for-scratch | /custom/loss.py | UTF-8 | 654 | 3.015625 | 3 | [
"MIT"
] | permissive | import numpy as np
class Loss:
def mean_squared_error(self, y, t):
return 0.5 * np.sum((y-t)**2)
def cross_entropy_error(self, y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 훈련 데이터가 원-핫 벡터라면 정답 레이블의 인덱스로 반환
if t.... | true |
8db5e12d12841cadaec5c9919ad3a35b95e526e5 | Rahul664/Pyhton_functional_code_snippets | /Python_Assignment_2/57.py | UTF-8 | 2,680 | 3.375 | 3 | [] | no_license | import math
import sys
try:
num = a/2
print ("num is ", num)
except Exception:
print("Exception - base class for all exception")
#Arithmetic errror
try:
div = 2/0
except ArithmeticError:
print( "Arithmetic error exception")
#StopIteration
try:
#z=[1,2]
f1=open("rsh1.txt")
for i in range(1,4):
pri... | true |
2fe0b8c127c677427f2ecfb1d369ff85670a7b87 | harishrenukunta/LearnPython | /Search_for.py | UTF-8 | 248 | 3.625 | 4 | [] | no_license |
lst = [56, 21, 234, 567, 23, 12]
def search(lst, no):
for n in lst:
if n == no:
return True
return False
no = 234
if search(lst, no):
print('Found no:{}'.format(no))
else:
print('no:{} not found'.format(no))
| true |
407dedecee6e2aaeb4f0d416c12c908daca3f9bd | wanwanaa/Leetcode | /树/104.二叉树的最大深度.py | UTF-8 | 333 | 3.671875 | 4 | [] | no_license | # 104.二叉树的最大深度(递归)
# 返回左子树和右子树的最大深度+1
# 结束条件:节点为空,返回0
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
depth_left = self.maxDepth(root.left)
depth_right = self.maxDepth(root.right)
return max(depth_left, depth_right) + 1
| true |
ba7cc7780317aa1f1782a7fce940b5c495749232 | ITA-Dnipro/Dp-207_Python_e-mandruy_django_app | /services/transport_app/api_utils/jwt_helpers.py | UTF-8 | 528 | 2.671875 | 3 | [] | no_license | import jwt
from datetime import datetime, timedelta
import os
from dotenv import load_dotenv
load_dotenv()
def create_jwt_token(payload):
'''
Return JWT token encoded with .env file sekret
'''
TRANSPORT_APP_JWT_SECRET = os.environ.get('TRANSPORT_APP_JWT_SECRET')
#
incoming_date = dict(payload... | true |
009ca700d8c087a4e77a5086d930c35623c2a739 | anemesio/Python3-Exercicios | /Mundo01/ex016.py | UTF-8 | 332 | 3.984375 | 4 | [
"Apache-2.0"
] | permissive | from math import trunc
num = float(input('Digite um valor: '))
print('O valor digitado foi {} e sua porção inteira é {}.'.format(num,trunc(num)))
'''
Outra resolução
#import math
#num = float(input('Digite um valor: '))
#print('O valor digitado foi {} e sua porção inteira é {}.'.format(num,math.trunc(num)))
'... | true |
079deb04de99a3fe7aa7658e56669d93322476be | magnusstubman/mal00 | /messages/shellcommandmessage.py | UTF-8 | 258 | 2.578125 | 3 | [
"MIT"
] | permissive | import messages
class ShellCommandMessage(object):
name = 'shellcommand'
command = None
def __init__(self, command):
self.command = command
def getBuf(self):
return messages.Message(self.name, bytes(self.command, 'ascii')).toBuf()
| true |
5eeb0fb095937a65ce98ba7982997c64271cafe6 | deephdc/deephdc.github.io | /plugins/pelican-yaml-metadata/yamlmetadata.py | UTF-8 | 3,989 | 2.734375 | 3 | [
"MIT"
] | permissive | import logging
import six
try:
from markdown import Markdown
except ImportError:
Markdown = False
try:
import yaml
try:
from yaml import CBaseLoader as YamlLoader
except ImportError:
from yaml import BaseLoader as YamlLoader
except ImportError:
yaml = False
from pelican import... | true |
e52e4c3de651537e761600b44f4dbe0112699ce4 | Baidaly/datacamp-samples | /9 - statistical thinking in python - part 2/bootstrap confidence intervals/function to do pairs bootstrap.py | UTF-8 | 956 | 3.65625 | 4 | [
"MIT"
] | permissive | '''
As discussed in the video, pairs bootstrap involves resampling pairs of data. Each collection of pairs fit with a line, in this case using np.polyfit(). We do this again and again, getting bootstrap replicates of the parameter values. To have a useful tool for doing pairs bootstrap, you will write a function to per... | true |
50c55ac4eca1b600a8a846abe086e62bdde6ca4e | titoelfoly/shorter-server | /models/db.py | UTF-8 | 2,630 | 2.625 | 3 | [] | no_license | from typing import Collection
from flask import Flask , request, json, Response
from pymongo import MongoClient
from bson.objectid import ObjectId
import datetime
class MongoAPI:
def __init__(self,data):
self.client = MongoClient("mongodb+srv://titoelfoly:tito4631041@portofolio.dspnr.mongodb.net/myFirstDa... | true |
042be21960e648f1ee369b80d8e9be4d87837130 | python-cookbook/PythonStudy | /p02_personal_summary/p13_lee_yung_seong/p02_week/p02_thursday/C3_14.py | UTF-8 | 1,558 | 3.71875 | 4 | [] | no_license | #현재 달의 날짜 범위 찾기
#문제 : 현재 달의 날짜를 순환해야 하는 코득 ㅏ있고 그 날짜 범위를 계산하는 효율적인 방법이 필요.
#해결 : 날짜를 순환하기 위해 모든 날짜를 리스트로 만들 필요 없음. 대신 범위의 시작일자와 마지막 날짜만 계산하고 datetime.timedelta 객체를 사용해서 날짜를 증가시키면 된다.
#datetime 객체를 받아서 그 달의 첫번째 날짜와 다음 달의 시작 날짜를 반환하는 함수 코드는 다음과 같다.
from datetime import datetime, date, timedelta
import calendar
def get_mon... | true |
e6b609213a104a974bac8d2a95713488a5cb7c22 | hongyong3/TIL | /Algorithm/Swea/D1_12141.py | UTF-8 | 313 | 2.8125 | 3 | [] | no_license | import sys
sys.stdin = open("D1_12141_input.txt", "r")
T = int(input())
for test_case in range(T):
N = int(input())
l, r = 0, 100000000
while l + 1 < r:
m = (l + r) // 2
if m * m <= N:
l = m
else:
r = m
if l * l + l < N:
l += 1
print(l) | true |
09340cffdb1d33132c60e7f0a76626fc1e1cb24b | edanfersi94/appAPMsWc | /app/scrum/funcObjetivo.py | UTF-8 | 3,365 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
UNIVERSIDAD SIMON BOLIVAR
Departamento de Computacion y Tecnologia de la Informacion.
CI-3715 - Ingenieria de Software I (CI-3715)
Abril - Julio 2015
AUTORES:
Equipo SoftDev
DESCRIPCION: Script que contiene los casos de prueba del modulo
... | true |
cd1ddf662b245efe3c17b0aa388bcb61f81c8277 | mskl/fit-bi-zns-homeworks | /ulohy/04/Fuzzy/Term/term_aggregate.py | UTF-8 | 1,627 | 3.78125 | 4 | [] | no_license | class TermAggregate:
""" Used to store combinations of Terms """
def __init__(self, term1, term2, kind):
""" Note that func2 might be None in case of inverse """
self.func1 = term1
self.func2 = term2
self.kind = kind
def __and__(self, other):
""" movie['Good'] & equ... | true |
b638601c7e8b1e6776967fed1d7098365ecbc713 | TomaszKolodziejczak/code_snippets | /binary_search.py | UTF-8 | 455 | 3.921875 | 4 | [] | no_license | def binary_search(nums, target):
left = 0
right = len(nums)
index = 0
while left < right:
index = (left + right) // 2
if nums[index] == target:
return index
if nums[index] < target:
left = index + 1
if nums[index] > target:
right = ... | true |
0f06193784d4c13178af2f9081fb0c5708b1f593 | cdede/ketpegs | /ktpgs/entropy.py | UTF-8 | 1,192 | 3 | 3 | [] | no_license | from operator import attrgetter
def neighbor_entropy(size=3, map=[]):
size = size
grid = {}
for x in range(size ):
for y in range(size):
grid[(x,y)]=map[y*size+x]
average = sum(map)/size
entropy = 0
for x in range(size ):
tmp = 0
tmp1 = 0
for y in ra... | true |
a7559be9c2f035cd6318d21b5bfc2ebbc8b51254 | chenyang918/python3project | /项目1-学生管理系统/类/student-V1.5class/main.py | UTF-8 | 811 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from student_info import Student
def main():
l2=[]
l=Student()
while True:
l.cao_jiemian()
x = input('请选择 ')
if x == 'q':
break
elif x == '1':
l2 +=l.input_student()
print(l2)
elif x == '2':
l.out... | true |
f48074572df3ab4217599defb60c96c9998ed239 | Zarand3r/political | /prototype.py | UTF-8 | 4,966 | 2.546875 | 3 | [] | no_license | import json
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn import preprocessing
from surprise import accuracy
from surprise import Dataset
from su... | true |
c379d2e92830400db2d6a424f8092efb047b1d7a | LPLhock/CTA | /1-策略开发/2-策略储备/3-strategies/9-keltner_bandit_strategy.py | UTF-8 | 2,984 | 2.6875 | 3 | [] | no_license | from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
from vnpy.trader.constant import Interval
class KeltnerBanditStrategy(CtaTemplate):
""""""
author = "用Python的交易员"
kk_window = 20
kk_dev = ... | true |
c746872c0989743b549f020cc0c33e08d713ba86 | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/09/01/10.py | UTF-8 | 978 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python
#
# Copyright (c) 2009 by Teanlorg Chan.
from StringIO import StringIO
import re
def process(f, out = None):
if isinstance(f,str):
if not out:
out = open(f+'.out.txt','wb')
f = open(f,'rb')
else:
if not out:
out = StringIO()
l,d,n = map(int,f.readline().strip().split())
words = []
... | true |
07a79334603adbdb0f91f44594afa50a3fbd45dd | ppasupat/plastic-case | /main.py | UTF-8 | 2,263 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown",
"Unlicense"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main entry for running experiments.
The results will be saved to ./out/
(relative to this file)
"""
from __future__ import (absolute_import, division, print_function)
import argparse
import json
import os
import sys
from yournamehere.configs import (
load_config,
... | true |
f8a3480999a905ec678378842136b7f6f3199391 | SeokLii/Algorithm | /Other/스킬 체크 테스트 Level.1(PR).py | UTF-8 | 544 | 3.359375 | 3 | [] | no_license | # 문제 1
def solution(a, b, n):
answer = 0
while n >= a:
answer += n // a * b
n = n // a * b + n % a
return answer
# 문제 2
def solution(s):
answer = []
queue = []
for i in range(len(s)):
if s[i] not in queue:
answer.append(-1)
queue += s[i]
... | true |
c2aa7d891298d810afcdb47303f848c80ac68996 | mpinilla/NASA-gamma | /nasagamma/spectrum.py | UTF-8 | 4,115 | 3.15625 | 3 | [
"MIT"
] | permissive |
"""
Created on Wed Sep 30 10:14:25 2020
@author: mauricio
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Spectrum():
def __init__(self, counts=None, channels=None, energies=None,
e_units=None):
'''
Initialize the spectrum.
Parameters
... | true |
5170f95bd1726872e4c31466d33e1fe512433f53 | LifangD/FAT-RE | /utils/ensemble.py | UTF-8 | 2,148 | 2.71875 | 3 | [] | no_license | """
Ensemble the predictions from different model outputs.
"""
import argparse
import json
import pickle
import numpy as np
from collections import Counter
from utils import scorer, constant
def parse_args():
parser = argparse.ArgumentParser ()
parser.add_argument ('--data_dir', default='data... | true |
71642635cb0c938beed6088c4110d8bdcf0a38ee | kkatayama/pip_search_color | /pip_search/__main__.py | UTF-8 | 953 | 2.859375 | 3 | [
"MIT"
] | permissive | # __main__.py
'''
usage: pypi_search.py [-h] query
positional arguments:
query terms to search pypi.org package repository
optional arguments:
-h, --help show this help message and exit
'''
import sys
import argparse
from rich import pretty
from pip_search.pip_search import search
def check_positive(page... | true |
3565bacf768732aa0aaa5bd3bfd69dc04099faf8 | rpural/python | /makeChange.py | UTF-8 | 835 | 3.65625 | 4 | [] | no_license | '''
given a number of nickles and pennies,
and a target amount, determine if
change can be successfully made.
'''
def make_change(nickles, pennies, goal):
n = goal // 5
# print(f"- nickles={nickles}, n={n}, pennies={pennies}, goal={goal}")
if n > nickles:
n = nickles
goal -= n * 5
# print(f"- revise... | true |
11508e9c453bdfe5dd621c5a97a4a39d2dfa93cd | Anavaldeonjunquera/progorientadaobjetos | /servidor_python/application/model/books.py | UTF-8 | 905 | 3.09375 | 3 | [] | no_license | __author__ = 'Ana Maria Valdeon'
class Books:
def __init__(self, lista=None):
self.lista_books = [] if not lista else lista
def add_book(self, book):
self.lista_books.append(book)
return True
def remove_book(self,id):
for x in range(0,len(self.lista_books)):
i... | true |
12098b09b1f315d2cebc01635e7788de769a2630 | inarutosai7/Web_crawler_practice | /json_image.py | UTF-8 | 1,399 | 2.703125 | 3 | [] | no_license | import requests
import json
import os
from urllib import request
if not os.path.exists('./dcardPhoto'):
os.mkdir('./dcardPhoto')
url = 'https://www.dcard.tw/service/api/v2/forums/photography/posts?limit=30&before=236646456'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gec... | true |
0d5cf3cfbfe906d8efa0362c3bcd2a1caad521cf | raihala/advent-of-code | /2021/3/main.py | UTF-8 | 677 | 3.640625 | 4 | [] | no_license | """
Day 3 Part 2
"""
with open('input') as f:
data = [line.strip() for line in f]
oxygen = data
for i in range(12):
zeroes = [x for x in oxygen if x[i] == '0']
ones = [x for x in oxygen if x[i] == '1']
if len(ones) >= len(zeroes):
oxygen = ones
else:
oxygen = zeroes
if len(oxyg... | true |
c4a1a2fe6ad5b391b695092cff5bb31a1913b95d | BenYuan1998/Unbiased-Sentiment-Matrix-Factorization-USMF- | /EFM_Relative_Ground_Truth_Relevance_Levels/Explainable-Recommendation-master/data_preprocess/statistics.py | UTF-8 | 1,442 | 2.890625 | 3 | [] | no_license | # Usage: python statistics.py data-dir
import sys
import os
import json
def get_statistics(file):
user_dict = {}
product_dict = {}
reviews_count = 0;
with open(file) as data_file:
for line in data_file:
reviews_count += 1
json_data = json.loads(line)
user_id... | true |
24bb1e1b9c00aa930f4607e0f98fd3d51cdf6ef0 | Gackle/leetcode_practice | /677.py | UTF-8 | 1,762 | 4.25 | 4 | [] | no_license | # coding: utf-8
''' 677. 键值映射
实现一个 MapSum 类里的两个方法,insert 和 sum。
对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。
'''
class MapSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.index_li... | true |
9a584af3b75b358ec338856ecc197b66e946153e | vaporose/citygen | /main.py | UTF-8 | 840 | 3.046875 | 3 | [] | no_license | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from city import City, city_types
from kivy.properties import ListProperty
class SubmitButton(Button):
def update(self, output_object: Label, name=None, size_arg=None):
ne... | true |
5fb51ece83e9f25807dacb5c63ab7697fa70ae62 | donovosoft/paas-utils | /build.py | UTF-8 | 1,646 | 2.515625 | 3 | [] | no_license | #!/usr/bin/python
import docker
import sys
import argparse
import json
from pprint import pprint
from git import Repo
from subprocess import call
class Deployer(object):
def __init__(self):
self.app_name = None
self.app_version = None
def read_info(self, app_name):
with open(app_name+'/package.json'... | true |
be9c57e5ff9678312efce3fe5fc3440b6d45243e | sidpar89/Mechanics_Apps | /Zugversuch/Zugversuch.py | UTF-8 | 10,943 | 2.65625 | 3 | [] | no_license | from bokeh.plotting import figure
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Slider, LabelSet
from bokeh.io import curdoc#, push_session
from numpy import loadtxt
from time import sleep
## set up data sources for movable objects ##
# data sources for drawing
top_of_sample_sour... | true |
c1b964d0cd7d4828b9a9482fb592ea3fc0aecc2c | jimmbraddock/WFM | /graph.py | UTF-8 | 7,685 | 3.359375 | 3 | [] | no_license | #-*- coding: utf-8 -*-
class Graph(object):
"""
Описывает сущность Граф. Определяет представление задач на карте.
"""
def __init__(self, vertexes=None, edges=None):
if not vertexes: vertexes = []
if not edges: edges = []
self._vertex = vertexes
self._edge = edges
if self._edge:
self.... | true |
8759efe599e9e52bcda3bf1b7be6d132fd7ba1e4 | jayzane/leetcodePy | /sort/merge_sort.py | UTF-8 | 802 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | """
归并排序
2020-12-06: 22:04.35;07:54.77;02:46.99;01:50.48;
2020-12-10: 05:11.03;01:31.73;02:45.53;01:59.04;
"""
from sort import validatetool
# TODO:归并的时候借用两次二分,right[0]在left中的位置,left[-1]在right中的位置
def sort(data):
def ms(d):
l = len(d)
if l <= 1:
return d
m = l // 2
le... | true |
8bb1a4632d9b7ee4e63ce9bb4d866dda5e23a5a7 | Waterdrop42/camille | /data/data_base.py | UTF-8 | 696 | 2.84375 | 3 | [] | no_license | """
data的抽象类
"""
from abc import ABC, abstractmethod
class DataHandler(ABC):
"""
DataHandler是一个抽象基类,给所有继承DataHandler子类提供接口(包括历史回测和实盘交易)
提供这样一个抽象基类的目的在于使得每一个继承此基类的子类都输出同样格式的"tick"数据,并将
这些数据传入事件队列
"""
def _set_up_prices_dict(self):
prices_dict = dict(
[(p, {'bid': None, 'a... | true |
0ba403da95f4f22679ae479c951c934b82e93a22 | suomiy/libvirt-vm-optimizer | /libvirt_vm_optimizer/util/utils.py | UTF-8 | 710 | 2.90625 | 3 | [
"MIT"
] | permissive | import sys
from enum import Enum
class Profile(Enum):
DEFAULT, CPU, SERVER = range(3)
@staticmethod
def from_str(profile):
l_profile = profile.lower() if profile else None
if l_profile == 'cpu':
return Profile.CPU
elif l_profile == 'server':
return Profile.... | true |
bc8fb228dc4f7d84ad718bca2af2de81c1c4e17d | yibwu/leetcode | /src/remove_outermost_parentheses_1021.py | UTF-8 | 664 | 3.5 | 4 | [] | no_license | class Solution:
def removeOuterParentheses(self, S):
stack = []
result = []
for ch in S:
if ch == '(':
stack.append(ch)
if len(stack) > 1:
result.append(ch)
else:
if len(stack) > 1:
... | true |
ee36026143290625976bc3e703b3e7c17dd1bed2 | nguyendangnhat97/Machine-Learning | /K-means Clustering/working on MNIST/K-means application.py | UTF-8 | 1,478 | 2.65625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 08:56:43 2021
@author: Admin
"""
import numpy as np
from mnist import MNIST
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from display_network import *# #hien thi nhieu buc anh cac chu so mot luc
mndata = MNIST(r'E:\Study Document\Machine learni... | true |
bd280102785dee488defdb2f5c98e2abed105bbf | Butterparade/School-stuff | /Math Functions/Function Structure.py | UTF-8 | 7,680 | 3.59375 | 4 | [
"Apache-2.0"
] | permissive | """
Math function Structural core
"""
import math
def mathFace():
"""
Front end of the math program, prompts user for input and problem type.
"""
print ('Enter the type of problem you wish to solve for.')
print ('Options include:')
print ('Triangle')
print ('Angle')
print ('Vector')
... | true |
f2f3f8144fa85bda46666ef8812ce0ba75a3b330 | taddes/python-crypto | /Transposition Cipher/transposition_file_cipher.py | UTF-8 | 1,853 | 3.609375 | 4 | [] | no_license | """Program to Encrypt/Decrypt Text Files"""
import time, os, sys, transposition_encrypt, transposition_decrypt
def main():
input_filename = 'war-and-peace.txt'
# input_filename = 'frankenstein.encrypted.txt'
# output_filename = 'war-and-peace.encrypted.txt'
output_filename = 'war-and-peace.encrypted.t... | true |
ff74a50f2d9b5ab45116100eac9d90d140e3955b | harkevich/testgithub | /Lesson/Lesson22Множество.py | UTF-8 | 3,126 | 3.875 | 4 | [] | no_license | #set - множество
s = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
s2 = set('hello')
s3 = {i for i in range(1, 11)}
s4 = {1, 3, 4, 5, 22, 0, 2} # Выстраиваются в порядке возрастания
print(s)
print(s2)
print(s3)
print(s4)
s5 = {} # Создаться не множество а словарь
print(type(s5))
s6 = set() # ... | true |
d3f04047013a6faa4dc61a4348c7993282ac17ec | BohemianMatrices/characteristic-polynomial-database | /website_md.py | UTF-8 | 15,562 | 3.125 | 3 | [] | no_license | import os
import glob
def get_properties(property_file = 'Properties.csv'):
properties_dict = dict()
index_to_property_map = list()
# Min/Max matrix dimension
n_min = 10000
n_max = 0
with open(property_file, 'r') as f:
# Process header
header_line = next(f)
h... | true |
df0d9c6d2b426740e3570d78d09ae32b741e27a0 | renzhe00/Python-programming-exercises | /code/69.py | UTF-8 | 405 | 3.890625 | 4 | [] | no_license | def bin_search(l, element):
bottom, top, index = 0, len(l)-1, -1
while top>=bottom and index==-1:
mid = int((top+bottom)/2)
if l[mid]==element:
index = mid
elif l[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
l = [1,2,4,6,8,1... | true |