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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4aacdbf1c096e5d7e78ca59716ea9f98ba59fb4b | Python | mvbTuratti/vm | /app/pesos.py | UTF-8 | 1,244 | 2.875 | 3 | [] | no_license | import csv
import os
import datetime
from multiprocessing import Lock
lock = Lock()
def log_peso(valor, file):
with lock:
data = [datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ"),valor]
def older_than_last(time):
rows = []
with open(file, 'r') as csvfile:
... | true |
539d5b0939bfb215de269915f269b517b26d9632 | Python | rajeevdodda/Codeforces | /CF-B/201-300/CF266-D2-B.py | UTF-8 | 310 | 3.0625 | 3 | [] | no_license | # https://codeforces.com/problemset/problem/266/B
n, t = map(int, input().split())
queue = list(input())
for i in range(t):
j = 0
while j < n - 1:
if queue[j] == "B" and queue[j+1] == "G":
queue[j], queue[j+1] = "G", "B"
j += 1
j +=1
print(''.join(queue))
| true |
dcd0a45c0c6d8d14b69daf8483309ecadceb5e68 | Python | callmexss/data_structure_and_algorithms | /tree/trie.py | UTF-8 | 1,494 | 3.84375 | 4 | [] | no_license | class TrieNode:
def __init__(self):
self.path = 0
self.end = 0
self.maps = [None] * 26
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
if not word:
return
node = self.root
for c in word:
index... | true |
7fbfc4c0d799c80ab451a86c520ac7fbe10b4ab9 | Python | Vijendrapratap/Machine-Learning | /Week4/NumPY/27. WAP to remove specific elements in a numpy array.py | UTF-8 | 459 | 4.5 | 4 | [] | no_license | """
Write a Python program to remove specific elements in a numpy array.
Expected Output:
Original array:
[ 10 20 30 40 50 60 70 80 90 100]
Delete first, fourth and fifth elements:
[ 20 30 60 70 80 90 100]
"""
import numpy as np
myaaray = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
index = [0, 1, 8]
print("... | true |
d6e8e92a08c928dde1d0c6f2dba79d330a66fa6f | Python | tbrack/ustjay-ethay-actsfayig | /main.py | UTF-8 | 1,052 | 2.828125 | 3 | [] | no_license | import os
import requests
from flask import Flask, render_template_string
from bs4 import BeautifulSoup
app = Flask(__name__)
pig_latinizer = "https://hidden-journey-62459.herokuapp.com"
def get_fact():
response = requests.get("http://unkno.com")
soup = BeautifulSoup(response.content, "html.parser")
... | true |
8a1a7ddec086073c2c6423362cc8c2f585e04636 | Python | cliffpham/algos_data_structures | /algos/daily_coding_problem/problem_211.py | UTF-8 | 766 | 3.859375 | 4 | [] | no_license | # This problem was asked by Microsoft.
# Given a string and a pattern, find the starting indices of all occurrences of the pattern in the string.
# For example, given the string "abracadabra" and the pattern "abr", you should return [0, 7].
import unittest
class Test(unittest.TestCase):
def test1(self):
... | true |
943e6dfedc0cd5910b9b9aa16b65600a8c6faed2 | Python | 1-WebPages-1/Calcu1 | /calculadora.py | UTF-8 | 3,553 | 3.640625 | 4 | [] | no_license | from tkinter import *
ventana = Tk()
ventana.title("Calculadora")
i = 0
#entrada
e_texto = Entry(ventana, font= ("Calibri 20"))
e_texto.grid(row = 0, column = 0, columnspan = 4, padx = 5, pady = 5)
#Funciones
def click_boton(valor):
global i
e_texto.insert(i, valor)
i += 1
def borrar():
e_texto.del... | true |
a08dbd7a23f31b3588e2a9cab0d6788c90ccd406 | Python | dayaftereh/py-csv | /scsv.py | UTF-8 | 2,103 | 3.046875 | 3 | [
"MIT"
] | permissive | import csv
import os
from datetime import datetime
import locale
# set default to german
locale.setlocale(locale.LC_ALL, 'de_DE')
class CSVWriter:
def __init__(self, fname, delimiter=' '):
self._f = None
self._counter = 0
self._writer = None
self._fname = fname
self... | true |
b55bf2516bceca8ed74c69245fb6f0c8fa16019f | Python | dhruv-rajput/data-structures-and-algo | /stack/max-area-matrix.py | UTF-8 | 1,905 | 3.15625 | 3 | [] | no_license | def nsl(arr,n):
ans=[]
stack=[]
i=0
while i<n:
if len(stack)==0:
ans.append(-1)
elif len(stack)>0 and stack[0][0]<arr[i]:
ans.append(stack[0][1])
elif len(stack)>0 and stack[0][0]>=arr[i]:
while len(stack)>0 and ... | true |
c9e2c3bf00c8f614ff828177bef771041f462057 | Python | lvyufeng/DuConv_mindspore | /src/callbacks.py | UTF-8 | 2,425 | 2.84375 | 3 | [] | no_license | import math
import time
from mindspore.train.callback import Callback
from numpy.lib.function_base import average
class TimeMonitor(Callback):
"""
Monitor the time in training.
Args:
data_size (int): How many steps are the intervals between print information each time.
if the program g... | true |
831a32e5cdecdb4b64074eccd9f2fb716459d781 | Python | JustinGOSSES/pyrolite | /docs/source/examples/geochem/lambdas_orthogonal_polynomials.py | UTF-8 | 3,198 | 3.0625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | """
lambdas: Visualising Orthogonal Polynomials
============================================
"""
import numpy as np
import matplotlib.pyplot as plt
from pyrolite.plot.spider import REE_v_radii
from pyrolite.geochem.ind import REE, get_ionic_radii
from pyrolite.util.math import lambdas, lambda_poly_func, OP_constants
n... | true |
3e8ff3db6650ca67e02d0f82df214a83928c820b | Python | albertauyeung/iems5703 | /lectures/files/scraping.py | UTF-8 | 726 | 3.296875 | 3 | [] | no_license | from bs4 import BeautifulSoup as BS
import requests
# Base URL of content pages
base_url = "http://highscalability.com/blog/?currentPage={:d}"
# A variable for collecting links to individual articles
links = []
# Loop through the first 10 content pages
for i in range(1, 11):
# Generate the actual UR... | true |
c35de9d40f938b898bfbb62f051224121013b503 | Python | abrozynski/python-fun | /projectEuler/problem54.py | UTF-8 | 640 | 3.234375 | 3 | [] | no_license | import poker
def problem54():
player_1_wins = 0
player_2_wins = 0
ties = 0
infile = open('poker.txt')
outinfo=[]
for line in infile:
agame = poker.PokerGame()
hand1 = poker.PokerHand(line[0:14])
hand2 = poker.PokerHand(line[15:len(line)-2])
result = agame.compare_hands(hand1, hand2)
... | true |
7b3a3501158ba4a35aaffdf6f72a865f9ea9f78b | Python | kaosbeat/choirbox | /python/metronome.py | UTF-8 | 3,093 | 2.671875 | 3 | [
"MIT"
] | permissive | import gpiozero
from gpiozero import Button, LED
from time import sleep, time
import socket
import sys
from signal import pause
# import thread module
import threading
import sys
sys.path +=['.']
from metronomeStates import BPMStateMachine
'''
In this script we want to light the LED at pin <> according to the signal ... | true |
a5d3f087704f8da72aec00c6fbacae77075e5aa5 | Python | drathke924/userscripts | /Advent_Of_Code_2022/day8.py | UTF-8 | 2,226 | 3.375 | 3 | [] | no_license | from math import prod
def generate_map(data_in):
map_out = {}
for y in range(0, len(data_in)):
for x in range(0, len(data_in[y])):
current_num = data_in[y][x]
map_out[(x, y)] = current_num
return map_out, len(data_in[y]), len(data_in)
def is_seen(x, y, full_map, map_size_x,... | true |
42fdfb15a01d65f1fb576eed4365b417b6305f6f | Python | David8Zorrilla/TP-2018-1 | /4-errores_y_math/Ejemplos/Errores/main.py | UTF-8 | 249 | 4.09375 | 4 | [] | no_license | value = input('Inserta un numero: ')
try:
int_value = int(value)
is_int = True
except Exception as e:
print('Exception:', e)
is_int = False
else:
print(5 + int_value)
finally:
print('Es' if is_int else 'No es', 'un Numero')
| true |
36bff43399a0f056f1cf62af83a432d9eca2a17f | Python | SehajS/Pong-Game | /main.py | UTF-8 | 3,855 | 3.59375 | 4 | [] | no_license | import turtle
import winsound
# creating a window
win = turtle.Screen()
win.title("Pong Game") # window title
win.bgcolor("#0c264f") # b ackground color
win.setup(width=800, height=600) # window dimensions
win.tracer(delay=0) # no animation delay
left_score = 0
right_score = 0
# Left Paddle
left_paddle = turtle.T... | true |
0164661444898db1f59a1b5f268bcca9aab6de07 | Python | happyxuwork/tensorflow-learning | /src/demo/section6-cnn/evaluateImage/convertCIFRA10ToImage.py | UTF-8 | 1,594 | 2.8125 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
'''
@author: xuqiang
'''
from scipy.misc import imsave
import numpy as np
import pickle as cPickle
import os
# 解压缩,返回解压后的字典
def unpickle(file):
fo = open(file, 'rb')
dict = cPickle.load(fo,encoding='bytes')
fo.close()
return dict
# 生成训练集图片,如果需要png格式,只需要改图片后缀名即可。
in_path = "F:/C... | true |
3ad884eb6cb4ef490ef64615eaa31ac02adcb849 | Python | GlennGuan/learn_cookbook | /chapter10/10_7.py | UTF-8 | 379 | 2.625 | 3 | [] | no_license | # 让目录或zip文件成为可运行的脚本 p417
myapplication/
spam.py
bar.py
grok.py
__main__.py
bash % python3 myapplication
解释器会把__main__.py文件作为主程序执行。
# 把代码打包进一个zip文件中时同样有效
bash % ls
spam.py bar.py grok.py __main__.py
bash % zip -r myapp.zip *.py
bash % python3 myapp.zip
...output from __main__.py...
| true |
01d355ab8858246df78af58b427abb4dc261096a | Python | GhostUser/IRIS-classification-flask-api | /app.py | UTF-8 | 986 | 2.796875 | 3 | [] | no_license | from flask import Flask, request, jsonify, render_template
import numpy as np
import pickle
app=Flask(__name__)
model=pickle.load(open("model.pkl", "rb"))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
initial_features = [float(x) fo... | true |
d0c818398f5b70591416a07b1e44308954e27ca7 | Python | shaheen19/dsp | /editors/nutmeg.py | UTF-8 | 307 | 2.875 | 3 | [] | no_license | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
print("This file was created using the nano editor by Aaron W")
# Generate some random Gaussian noise
x = np.random.randn(10)
y = np.random.randn(10)
fig, ax = plt.subplots(1)
ax.scatter(x, y)
plt.show()
| true |
12bfe23eed77d5399318fe762e7ebb965e7120ba | Python | CesarCent17/Virtual_Library | /views/ciencia_ficcion.py | UTF-8 | 3,327 | 3.015625 | 3 | [] | no_license | from tkinter import *
from centrar import *
import webbrowser as wb
from tkinter import messagebox
class Ficcion:
def __init__(self):
self.obj_centrar = Centro()
self.getVentana()
self.ventana_ficcion.iconbitmap("C:/Users/PC/Pictures/Virtual Library/graphic_resources/Virtual Library.ico")
... | true |
d4c024bce65cbcec1ec4ebe1240a64047b977317 | Python | XMY400013/Tik_Tak_Toe_Telegram_bot | /main.py | UTF-8 | 3,042 | 2.6875 | 3 | [] | no_license | import telebot
from telebot import types
from dotenv import load_dotenv
import os
from Class import Table
dotenv_path = os.path.join(os.path.dirname(__file__), 'env')
load_dotenv(dotenv_path)
tb = telebot.TeleBot(os.getenv('TOKEN'))
# Класс таблица
table = Table()
# отклик ан команду
@tb.message_handler(commands=... | true |
692861c7254199d3b80aed58bdcf740650aab227 | Python | mathematiguy/movie_reviews | /rotten_tomatoes/rotten_tomatoes/spiders/rt_reviews.py | UTF-8 | 1,815 | 2.671875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy
class RtReviewsSpider(scrapy.Spider):
name = 'rt_reviews'
allowed_domains = ['rottentomatoes.com']
start_urls = ['https://www.rottentomatoes.com/m/star_wars_the_last_jedi/reviews/?page=1&type=user']
def parse(self, response):
# get the names for each reviewer
names = res... | true |
18e942c7bcbd454a3a760242823fa9156ca8b5d2 | Python | dexion/springbok | /AnomalyDetection/DistributedDetection.py | UTF-8 | 13,224 | 2.515625 | 3 | [] | no_license | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from ROBDD.robdd import Robdd
from ROBDD.synthesis import synthesize, compare, negate_bdd
from ROBDD.operators import Bdd
from AnomalyError import AnomalyError
from AnomalyError import ErrorType
from collections import deque
import time
from NetworkGraph import NetworkGra... | true |
fceef754a1efd52e3136335fe4372593c6aa521f | Python | nsmith0310/Programming-Challenges | /Python 3/Project_Euler/problem 90.py | UTF-8 | 727 | 3.171875 | 3 | [] | no_license | ###1217
from itertools import combinations as c, product as p
t= list(c(["0","1","2","3","4","5","6","7","8","9"],6))
u = list(c(t,2))
v=[]
f=[]
for x in u:
c = list(p(x[0],x[1]))
g=[]
for y in c:
s=y[0]+y[1]
g.append(s)
f.append(g)
count=0
... | true |
b004d0ff1f95f5b05247dbba11d4a67a6d2f3f34 | Python | BenjHyon/heigthmapGenerator | /MountainGenaratorPOC.py | UTF-8 | 7,802 | 3.03125 | 3 | [] | no_license | import random, time
from PIL import Image, ImageFilter
import math
import os
import matplotlib.pyplot as plt
import sys
import numpy as np
#Make a realistic HeightMap of a mountain from the shape of a mountain from it's png value
#Known Issue: Little shape with 1 pixel wide area is not well defined
#to do:
count = 0... | true |
783ac452e8fe55f9913c59d91e37e44f28c5c0c1 | Python | jackysz/CodinGame-3 | /1. Easy/Python 3/Horse_Racing_Duals.py | UTF-8 | 129 | 2.8125 | 3 | [] | no_license | n=int(input())
a= sorted([int(input()) for i in range(n)])
d = 10000000
for i in range(n-1):
d = min(d,a[i+1]-a[i])
print (d) | true |
dad1e78a8ae4bd32656f1722c3a59e3e4a1d3323 | Python | javierlara/health-insurance | /api/routes/resources/health_center.py | UTF-8 | 2,582 | 2.59375 | 3 | [] | no_license | from flask_restful import Resource
from flask import abort, make_response, request
import flask as f
import api.models as models
from datetime import datetime
from api.db import db_session as session
class HealthCenter(Resource):
@staticmethod
def get_health_center(health_center_id):
return session.qu... | true |
1685524c521f680692d978930fc92d54b8f60285 | Python | sfeng77/myleetcode | /evaluateReversePolishNotation.py | UTF-8 | 1,028 | 4.28125 | 4 | [] | no_license | # Evaluate the value of an arithmetic expression in Reverse Polish Notation.
#
# Valid operators are +, -, *, /. Each operand may be an integer or another expression.
#
# Some examples:
# ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
# ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution(object):
... | true |
9a35d756406f675a44249b0b013cf249861ae41b | Python | falyse/advent-of-code | /2015/20/main-2.py | UTF-8 | 1,857 | 3.453125 | 3 | [] | no_license | import math
houses = {}
goal = 34000000/11
def meets_goal(i):
score = 0
for e in range(math.ceil(i/50), i+1):
if not i % e:
score += e
# print('i', i, ', e', e, ' -> ', score)
if score >= goal:
print('House', i, 'met goal with', score)
... | true |
03a8edb3075f56aec1676e41f7494cb2c8f86dd7 | Python | sshchicago/SSH-C-User-Management-Tools | /sshcldap.py | UTF-8 | 8,819 | 2.578125 | 3 | [] | no_license | #!/usr/bin/env python2.6
"""
sshcldap.py: A class of useful tools for working with LDAP servers.
Tested with 389 Directory Server against the SSH:Chicago user database;
probably works with other directories, but you'll have to try to find
out. :-)
"""
__author__ = "Christopher Swingler"
__copyright__ = "Copyright 201... | true |
252d1d245db30f917ca605af89d743df8b6653a8 | Python | Bharath2/Informed-RRT-star | /PathPlanning/rrt.py | UTF-8 | 4,139 | 3.03125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as Axes3D
from .rrtutils import *
class RRT:
def __init__(self, start, goal, Map,
max_extend_length = 5.0,
path_resolution = 0.5,
goal_sample_rate = 0.05,
max_i... | true |
1687e5dbb72875a871c080acf17e12c48b71e02a | Python | aaronbae/competitive | /kickstart/mural.py | UTF-8 | 617 | 3.5 | 4 | [] | no_license | import math
def solve(mural):
painted_window = math.ceil(len(mural) / 2)
max_beauty = sum(mural[:painted_window])
curr_beauty = max_beauty
for i in range(0, len(mural)-painted_window):
curr_beauty -= mural[i]
curr_beauty += mural[i+painted_window]
if curr_beauty > max_beauty:
... | true |
e45ee52942e991575b649de8e9010016685fdfdd | Python | westcoj/PythonZork | /Weapon.py | UTF-8 | 2,894 | 3.796875 | 4 | [] | no_license | """
* The following module contains the weapon classes for the game that the
* player uses to attack monsters
*
* @author Cody West
* @version Zork Clone
* @date 11/08/2017
"""
import random
class Weapon(object):
'''
Super class contiaing generic weapon methods for specific inheritors to use... | true |
4c69c1b9be3ae7d23d4601a5e7501c6905fca722 | Python | NataliaDiaz/BrainGym | /detect-feature-kernel.py | UTF-8 | 2,387 | 3.921875 | 4 | [] | no_license |
"""
# Feature detection in a image with:
- a convolution kernel,
- a threshold and
- image
as input. The convolution kernel is a square K x K real matrix denoted by k(i,j),
the threshold is a real number, and the image is given as an RxC real matrix with
elements between 0 and 1, with the pixel in row r and column c g... | true |
64768a811ec5d3062f8d35e632e63f5c18b2da74 | Python | Swati1-ud/Data_Practice | /5_Tree/Post-order_Traversal_Of_Binary_Tree.py | UTF-8 | 540 | 3.203125 | 3 | [] | no_license | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postOrder(self, root):
"""
input: TreeNode root
return: Integer[]
"""
# write your solution here
... | true |
e94885e3146a956f9e5b62b186aee295cba17957 | Python | DivyaJyotiDas/Trillio_Files_Operations | /main/tests/snapshot/test_smart_backup.py | UTF-8 | 1,399 | 2.703125 | 3 | [] | no_license | import os, sys, pytest, mock
from mock import mock_open, MagicMock
from main.main_lib.snapshot.smart_backup import md5, chunks_md5, size_of_file, num_process_creation
@pytest.fixture(scope='module')
def ret_file_path():
file = os.path.abspath('dummy_test_file')
return file
@mock.patch('builtins.open', new_c... | true |
02f21a048596644cdfc3b43538e202e33cb00f5e | Python | 10elements/leetcode | /reverseWords.py | UTF-8 | 227 | 3.53125 | 4 | [] | no_license | def reverseWords(s):
t = [word for word in s.strip().split() if word != ' ']
t.reverse()
return ' '.join(t)
def main():
s = " a b "
print(reverseWords(s))
b()
def b():
print('b')
if __name__ == '__main__':
main() | true |
4becf20eac58eb816ac1a3913166d015c218745c | Python | jin-james/code_lbj | /parse_word/readDocx3th.py | UTF-8 | 6,400 | 2.546875 | 3 | [] | no_license | import docx
from win32com import client
import re
from bs4 import BeautifulSoup
import os
'''
试卷按顺序的题型放入style中
'''
style = {
'0': 'single',
'1': 'multiple',
'2': 'judgment',
'3': 'fillin',
'4': 'subjective',
'5': 'english'
}
def read4word(file):
'''
:param file: 为传入的.docx文件对象,以二进制格式打开
:return:
'''
doc = ... | true |
b93202eedaa6cc4132009afc3ff0aaf0d4c4d21a | Python | i7677181/mars_rover | /test_solution.py | UTF-8 | 1,247 | 3.09375 | 3 | [] | no_license | import unittest
from solution import go
class TestSolution(unittest.TestCase):
""" A bunch of test cases for our solution """
def test_solution_example(self):
"""Testing the example input"""
assert '0 0 N' == go(
# no movement
'''1 1
0 0 N
'''
)
assert '1 3 N\n5 1 E' == go(
# the tes... | true |
8aecd6ad500908e431f26ea8b21e8df39e10dbe7 | Python | kivy/pyjnius | /jnius/signatures.py | UTF-8 | 2,766 | 3.265625 | 3 | [
"MIT"
] | permissive | '''
signatures.py
=============
A handy API for writing JNI signatures easily
Author: chrisjrn
This module aims to provide a more human-friendly API for
wiring up Java proxy methods in PyJnius.
You can use the signature function to produce JNI method
signautures for methods; passing PyJnius JavaClass classes
as ret... | true |
8664dd494208e6f124e6758513927ace632cebb1 | Python | hi0t/Outtalent | /Leetcode/564. Find the Closest Palindrome/solution1.py | UTF-8 | 624 | 3 | 3 | [
"MIT"
] | permissive | class Solution:
def nearestPalindromic(self, n: str) -> str:
evenPal = lambda sp: int(sp + sp[::-1])
oddPal = lambda sp: int(sp + sp[::-1][1:])
sn, n = n, int(n)
if len(sn) == 1: return str(n - 1)
ans = -inf
mid = len(sn) // 2
for sp in sn[:mid], sn[:mid + 1],... | true |
efd1c6d7f845950f4d4ca616a38b70e6d6ac6e0b | Python | tmu-nlp/100knock2016 | /aron/chapter07/knock63.py | UTF-8 | 565 | 2.671875 | 3 | [] | no_license | # knock63.py
# coding = utf-8
import sys, json
import redis
r = redis.Redis(host="localhost", port=6379, db=1)
with open("artist.json", "r") as file:
for line in file:
# dic = defaultdict(lambda : 0)
dic = json.loads(line.rstrip())
if "name" in dic.keys() and "tags" in dic.keys():
name = dic["name"]
ta... | true |
f2f1d776db6c0ebece20fe733dc12af6f79aa562 | Python | goldenhairs/Convertible_bond-1 | /var.py | UTF-8 | 5,223 | 2.984375 | 3 | [] | no_license |
from tiingo import TiingoClient
import pandas as pd
import datetime
import numpy as np
import matplotlib.pyplot as plt
import warnings
import scipy
import scipy.stats
import matplotlib.pyplot as plt
# Tiingo API is returning a warning due to an upcoming pandas update
warnings.filterwarnings('ignore')
# User Set Up
da... | true |
6c6df7b1223423cfb3ff6e360a162c417f01e3a1 | Python | Dimaed90800/Python_Y | /Калькулятор 1.0.py | UTF-8 | 182 | 2.640625 | 3 | [] | no_license | import sys
if __name__ == "__main__":
if len(sys.argv) >= 2:
a = (''.format(sys.argv[1], sys.argv[-1]))
print(sum(a.split()))
else:
print("0") | true |
615a44d5f2be5ce57f5da2598fb5f35325b79adf | Python | iCarrrot/Python | /l2/z2.py | UTF-8 | 2,909 | 3.640625 | 4 | [
"MIT"
] | permissive | from abc import abstractmethod
from itertools import product
class Formula():
sign = '?'
def __str__(self):
return ' ('+self.formuly[0].__str__() + self.sign +self.formuly[1].__str__()+') '
@abstractmethod
def oblicz(self, zmienne):
pass
def zmienne(self):
wynik = set()... | true |
a99aed51eba6f7aa6c15877d6f1960887bb163d5 | Python | Nukker/HttpServer | /log.py | UTF-8 | 1,218 | 2.859375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Time:2012-02-12 17:11:45
__author__ = 'Kun'
import os,datetime,sys
try:
import config
except ImportError:
print 'Can\'t find the config file!!'
sys.exit(0)
def get_log_filename():
return datetime.datetime.now().strftime('server.%Y-%m-%d-%H-%M-%S.log')
class log():
... | true |
ecb91c34d37b690d409e069da43e9edcc7dd60a8 | Python | OscarPerez0/OLC1_Proyecto1_201213498 | /Grafo.py | UTF-8 | 5,336 | 2.984375 | 3 | [] | no_license | import pydot
from PIL import Image
class Grafo:
def __init__(self, ers):
self.l_er = ers
def generar_grafo(self):
if len(self.l_er) < 1:
return
callgraph = pydot.Dot(graph_type='digraph')
keys = list(self.l_er)
for text in keys:
if text == 'i... | true |
ab66c2291f41ba1ef7793f140a99e63a58a84ed1 | Python | appsjit/testament | /LeetCode/soljit/s239_slidingWindowMax.py | UTF-8 | 394 | 2.84375 | 3 | [] | no_license | class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if len(nums) == 0 or len(nums) < k:
return []
l, r = 0, k - 1
res = []
while l < len(nums) - k + 1:
... | true |
577d5cf0186b68219579c0db83dff6ac614652f5 | Python | LYleonard/Algorithm | /PyLeetCode/SortingAlgorithms/quicksort/lambda_quickwort.py | UTF-8 | 737 | 3.5625 | 4 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'LYLeonard'
__mtime__ = '2018/4/13'
# Code Description: 使用python的lambda表达式(匿名函数)实现快速排序
"""
import random
'''
匿名函数,一行代码实现快速排序
'''
quick_sort = lambda array: array if len(array) <= 1 else \
quick_sort([item for item in array[1:] if item <=... | true |
91bce0ed390f570c7c9f9c63bbf7b492cb1a7176 | Python | JunchuangYang/PythonInterView | /Python剑指Offer/032_把数组排成最小的数/032.py | UTF-8 | 974 | 3.78125 | 4 | [] | no_license | __author__ = 'lenovo'
"""
一般的 sorted 排序函数 都有相应的 cmp函数,用来定制化排序的比较方法。
然而 python 3中的 sorted( ) 除去的cmp 参数,推荐使用 key。
Python中有相应的函数 支持将 cmp函数转化为key的值。
cmp指定一个定制的比较函数,这个函数接收两个参数(iterable的元素),
如果第一个参数小于第二个参数,返回一个负数;
如果第一个参数等于第二个参数,返回零;
如果第一个参数大于第二个参数,返回一个正数。默认值为None
"""
import functools
def cmp(a , b):
"自定义排序... | true |
67df813999501f939e3e402246bd35e10e5be12e | Python | sholmbo/misfits | /misfits/gui/tools/base/intervals.py | UTF-8 | 3,024 | 2.65625 | 3 | [] | no_license | from matplotlib import cm
from .base import Base
from ...plot import ErrorSnake
class BaseIntervals (Base) :
def __init__(self, gui, spectrum, method):
self.fig, self.ax = gui.fig, gui.ax
self.gui, self.spectrum, self.method = gui, spectrum, method
self.artists = dict()
self.artists['spectrum'] =... | true |
33cf99052759cb48f6de9b512c7464c49a93ffa6 | Python | ebergstein/DojoAssignments | /Python/Flask_MySQL/Wall/server.py | UTF-8 | 4,226 | 2.515625 | 3 | [] | no_license | from flask import Flask, render_template, redirect, request, session, flash
from mysqlconnection import MySQLConnector
from datetime import datetime
app = Flask(__name__)
mysql = MySQLConnector(app,'wall') #BAD NAME, DON'T DO THIS
# the "re" module will let us perform some regular expression operations
import re
import... | true |
c81c8774f3a85bc723067e5f20038ab3fa20e8bd | Python | Gio-giouv/breakthru-check | /Breakthruengine.py | UTF-8 | 7,826 | 2.828125 | 3 | [] | no_license | import pygame
from tkinter import messagebox
import numpy as np
class State_Game:
def __init__(self):
self.board =[
["__", "__", "__", "__", "__", "__", "__", "__", "__", "__", "__"],
["__", "__", "__", "Sf", "Sf", "Sf", "Sf", "Sf", "__", "__", "__"],
["__", "__", "__", "__", "__", "__", "__", "... | true |
8b25d0f10151273cc9faaac4c9d1cb4531b96b4c | Python | DevAnuragGarg/Python-Learning-Basics | /listsTuples03/sorting.py | UTF-8 | 888 | 4.46875 | 4 | [
"Apache-2.0"
] | permissive | pangram = "The quick brown fox jumps over the lazy dog"
# it creates the list from the iterables
letters = sorted(pangram)
print(letters)
numbers = [2.3, 4.5, 31., 9.1, 1.6]
# here we are passing the list and get the new list in return
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# the sort function sort th... | true |
9c3eb5a60c99ae8c9de3aca31325d6b182beaae5 | Python | Zaccheaus90/holbertonschool-web_back_end-1 | /0x07-Session_authentication/api/v1/auth/auth.py | UTF-8 | 2,117 | 3 | 3 | [] | no_license | #!/usr/bin/env python3
""" Module of auth
"""
from os import getenv
from flask import request
from typing import List, TypeVar
class Auth:
""" Auth Class """
def __init__(self):
"""
Constructor
Args:
path: path to authenticate
excluded_paths: l... | true |
1f72f55c29bf0f871f804ca9016414fc5b56970c | Python | scinext/fh-kapfenberg-ss2013-raspberry-pi | /programs/thermometer-command_line_client-itm11-g1.py | UTF-8 | 1,875 | 2.984375 | 3 | [] | no_license | #! /usr/bin/python
import sys, socket
from sensors.simulation import Thermometer
class ThermoProxy():
"""Connects with a server"""
def __init__(self, host="127.0.0.1", port=1024):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self._so... | true |
d84ca0c73a094f49b83012d3598cfc14c9122844 | Python | brandonjp/SyncSettings | /tests/libs/test_gist_api.py | UTF-8 | 3,475 | 2.671875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from sync_settings.libs.gist_api import Gist
from sync_settings.libs.exceptions import GistException
from tests import *
from unittest import TestCase
class TestGistAPI(TestCase):
def __init__(self, *args, **kwargs):
super(TestGistAPI, self).__init__(*args, **kwargs)
self.api = Gist(... | true |
f9695e2279f3341f7168404c26d55496e288ebad | Python | nushackers/code-golf-nov-16 | /question2/b.py | UTF-8 | 163 | 2.71875 | 3 | [] | no_license |
def x(s, i):
if i == len(s):
return []
else:
a=x(s,i+1)
return a + [s[i-1],s[i+1]] if s[i] == 0 else a
r = lambda s: max(x(s, 0)) | true |
e16d6b3e3bd1f875f92c03ef080b588585070f8a | Python | FlaxBear/BookMarkGroup | /server/ver1_0/BookMarkGroupServer/Validate/groupFolderEditUpdValidate.py | UTF-8 | 1,689 | 2.59375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from flask_wtf import FlaskForm
from wtforms import HiddenField, StringField, TimeField, ValidationError
class GroupFolderUpdValidate(FlaskForm):
state = HiddenField()
group_folder_id = HiddenField()
group_folder_name = StringField()
group_folder_version = StringField()
json_directory_path... | true |
3062da9b5ccb35a82541ad46c520369ff1acabc0 | Python | kun-cockpit-tech/nlp | /rs/session_1/minist.py | UTF-8 | 2,166 | 2.734375 | 3 | [] | no_license | from sklearn import datasets
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.linear_model import LogisticRegression
from sklearn import tree
from sklearn.metrics import accuracy_score
import pickle
def read_data(data_file):
im... | true |
d59e19866e8d8d1cfacb65d3ff1d935bb6e72cd1 | Python | shreyb/decisionengine_modules | /util/testutils.py | UTF-8 | 1,003 | 3.296875 | 3 | [
"BSD-3-Clause"
] | permissive | '''
Utils to simplify testing
'''
# These imports needed for the `eval` blocks
from classad import classad # noqa
import datetime # noqa
import pandas as pd # noqa
def input_from_file(fname):
with open(fname) as fd:
return eval(fd.read())
def raw_input_from_file(fname):
wi... | true |
9972efb39ccb2b49b4df3a50cc0825ef17045f87 | Python | zx2229/web-scraping-with-python | /python3/chapter4/testUrllib2.py | UTF-8 | 920 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python
#-*- coding: utf-8 -*-
__author__ = 'hstking hstking@hotmail.com'
import urllib.request, urllib.error, urllib.parse
def clear():
'''该函数用于清屏 '''
print('内容较多,显示3秒后翻页')
time.sleep(3)
OS = platform.system()
if (OS == 'Windows'):
os.system('cls')
else:
os.system('clear')
def linkBaidu():
... | true |
1bffd9c1c7d06144dec9a950321a41df272af715 | Python | antiHiXY/OOP_and_Num_Methods | /Third_Task/main.py | UTF-8 | 1,631 | 3.15625 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
import sympy as smp
from scipy import integrate
import num_integr as ni
figure_size_const = (13, 6.7)
a = 0
x0 = 2
def make_plot (name, steps, errors):
plt.figure (figsize = figure_size_const)
plt.title (name)
plt.loglog (steps, errors, '-o', linewidth = ... | true |
280491a08ce14be7d4d92753511ddc862c669fe4 | Python | KerinPithawala/Visualizing | /main2.py | UTF-8 | 298 | 2.609375 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as mp
df = pd.read_csv('sobar-72.csv')
#df.plot('behavior_eating','attitude_consistency','attitude_spontaneity')
#scatter-plot for behaviour eating with cervix cancer
df.plot(kind = 'scatter', x = 'attitude_spontaneity', y = 'ca_cervix')
mp.show() | true |
31a0b363bba5bad91f1d55078a25caf128148bb5 | Python | missionpinball/mpf | /mpf/core/bcp/bcp_client.py | UTF-8 | 1,085 | 2.625 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | """Base class for all bcp clients."""
import abc
from mpf.core.mpf_controller import MpfController
class BaseBcpClient(MpfController, metaclass=abc.ABCMeta):
"""Base class for bcp clients."""
__slots__ = ["name", "bcp", "exit_on_close"]
def __init__(self, machine, name, bcp):
"""Initialise cli... | true |
c13b1cb7908e6a2250ff2e031e708d57d1d40aab | Python | mirittw/WorldOfGames | /WorldOfGames/MainScores.py | UTF-8 | 1,071 | 2.640625 | 3 | [] | no_license | from flask import Flask
import Utils
app = Flask(__name__)
@app.route('/scores', methods=['GET', 'POST', 'DELETE'])
def score_server():
try:
scores = open(Utils.SCORES_FILE_NAME, "r")
fullscore = 0
for line in scores.readlines():
if line != "" and line != "\n":
... | true |
7b88b365878ba33c5397e4011304926d4b5ab212 | Python | lazarow/decisiontrees-algs-test | /models/breast-cancer.CHAID.py | UTF-8 | 7,696 | 2.546875 | 3 | [] | no_license | def findDecision(obj): #obj[0]: 0, obj[1]: 1, obj[2]: 2, obj[3]: 3, obj[4]: 4, obj[5]: 5, obj[6]: 6, obj[7]: 7, obj[8]: 8
# {"feature": "3", "instances": 114, "metric_value": 23.7104, "depth": 1}
if obj[3] == '30-34':
# {"feature": "4", "instances": 26, "metric_value": 8.8135, "depth": 2}
if obj[4] ==... | true |
65d40584ffbab14cc3476803d678aafe83b6ef81 | Python | decodyng/mlgroup5 | /Kaggle/makeSubmission.py | UTF-8 | 998 | 3 | 3 | [] | no_license | __author__ = 'kensimonds'
def makeSubmission(clf, name):
# Input: A fitted classifier
# Output: None
# This function creates a Kaggle submission file by making predictions and storing the resulting csv file
# in the prescribed manner
testInputFile = open("../data/test.tsv") # Kaggle test set
t... | true |
a72f097e2a3fc29c0ceb5430e90e4bfb29ff83f8 | Python | Brewgarten/storm-bolt | /storm/bolt/configuration.py | UTF-8 | 6,094 | 2.703125 | 3 | [
"MIT"
] | permissive | """
Copyright (c) IBM 2015-2017. All Rights Reserved.
Project name: storm-bolt
This project is licensed under the MIT License, see LICENSE
Serializable configuration functionality
Cluster DSL
-----------
We support the following cluster syntax that includes optional deployments.
.. code-block:: bash
cluster {
... | true |
e2e7f4d78e2c59680935937521d1f695a542bc23 | Python | vetscience/Tools | /Utils/fasta.py | UTF-8 | 2,720 | 3.09375 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python
'''
Oct 10, 2017: Pasi Korhonen, The University of Melbourne
A very basic FASTA file reader.
'''
from __future__ import print_function
import sys
from . import base
###############################################################################
class Fasta(base.Base):
'''
'''
#####... | true |
3faf7d50cef0b39de2921ef319563b4c676f7e68 | Python | cs-ox-wolf3794/SentimentAnalysis | /filterJson.py | UTF-8 | 1,591 | 3.03125 | 3 | [] | no_license | import sys
import json
import difflib
# Input argument is the filename of the JSON ascii file from the Twitter API
filename = sys.argv[1]
filtered_file = sys.argv[2]
tweets_text = [] # We will store the text of every tweet in this list
tweets_location = [] # Location of every tweet (free text field - not always acc... | true |
c75b961737d6d875958f34368e59d092424b021c | Python | Haimchen/tu | /mpgi4/aufgabe01_src/tomograph.py | UTF-8 | 4,713 | 3.34375 | 3 | [] | no_license | import ellipse
import numpy as np
import matplotlib.pyplot as plt
import math
from numpy import dot
import GaussianElimination as gauss
"""
Sarah Koehler (sarah.c.koehler@gmail.com)
Dora Szuecs (szuucs.dora@gmail.com)
"""
def orthogonalVector(v):
"""
Calculates an vector u, that is orthogonal to a given vect... | true |
0e7fa08e310c295764d402886950d1fbe78f11f9 | Python | kennethgoodman/lazynumpy | /lazynumpy/internals/evals.py | UTF-8 | 735 | 2.6875 | 3 | [
"MIT"
] | permissive | """ file to hold internal _Evals class """
from lazynumpy.util import optimal_eval
# pylint: disable=fixme
class _Evals():
""" Holds delayed evals """
def __init__(self, val):
if isinstance(val, list):
self.vals = val
else:
self.vals = [val]
def __mul__(self, other... | true |
f3e64f3d48cbb31fd42de7fc2baf2460147fb372 | Python | MiguelTeixeiraUFPB/PythonM2 | /algoritmos/PythonM2/Cinema2.py | UTF-8 | 796 | 3.671875 | 4 | [
"MIT"
] | permissive | SIMPLES=17
COMPLETO=22
FILME2D=10.50
FILME3D=17.50
TipoFilme=str(input('digite o tipo de filme [2D] ou [3D] : ')).upper()
lanche=str(input('deseja comprar lanche? ')).upper()
if lanche=='SIM' and TipoFilme=='2D':
combo=input('seu combo é simples ou completo: ').upper()
if combo=='SIMPLES':
print('o va... | true |
d5dae998c756ca744ad7e92153e4da9fd9b212d9 | Python | Neeraj-kaushik/Geeksforgeeks | /Array/Smallest_Distinct_Window.py | UTF-8 | 183 | 3.4375 | 3 | [] | no_license | def smallest_window(str):
li = []
for i in range(len(str)):
if str[i] not in li:
li.append(str[i])
print(len(li))
str = input()
smallest_window(str)
| true |
95afc782b40b009feeccd2e5cc8976fb2a4c886c | Python | ejbeaty/scraper | /Craigslist_Scraper.py | UTF-8 | 10,545 | 2.53125 | 3 | [] | no_license | from bs4 import BeautifulSoup
from urllib2 import urlopen
import sys
import smtplib
import MySQLdb as mdb
import MySQLdb.cursors
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import configparser
import datetime
import os
import logging
def parse_results(search_term,min... | true |
d045f090fcc096fa961ac4a9039708dd0f45cc72 | Python | santhoshramesh2919/CodeKata--Hunter | /SubStrIndex_48.py | UTF-8 | 191 | 3.5 | 4 | [] | no_license | def substr(s1,s2):
for i in range(len(s1)-1):
for j in range(i+1,len(s1)):
if s1[i:j+1]==s2:
return i
else:
return -1
a=input()
b=input()
print(substr(a,b))
| true |
38feb1d0a92bf846928844bf1839ca7f1c2d055a | Python | nmichiels/adventofcode2020 | /day10/day10.py | UTF-8 | 1,554 | 2.953125 | 3 | [] | no_license | from itertools import combinations
import numpy as np
data = np.loadtxt('input.txt', delimiter='\n', dtype=np.int64)
data = np.sort(data, axis=-1)
effective_jolts = 0
chain = []
differences = {1: 0, 2:0, 3:0}
for i, jolts in enumerate(data):
if jolts <= effective_jolts + 3:
differences[jolts-effective... | true |
7a53e24993445e7a855070ba6fb7af37af981e08 | Python | s-light/OLA_test_pattern_generator | /pattern/gradient.py | UTF-8 | 12,566 | 3.203125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python2
# coding=utf-8
"""
gradient pattern.
generates a test pattern:
gradient
logic:
start at: _calculate_step()
calc (new) current position. (position means time)
calls: _calculate_pixels_for_position()
for every pixel:
... | true |
336a1ebe8cf0b70a74a26e2c65145e1b4afd70c0 | Python | danmenza/hackathon-dashboard | /parsePrices.py | UTF-8 | 1,113 | 2.640625 | 3 | [] | no_license | import os
import json
import datetime as dt
import pandas as pd
with open('clientList.json') as f:
client_list = json.load(f)
ticker_map = {v['ticker']:k for k, v in client_list.items()}
ticker_map
def dt_compile(d, t):
return dt.datetime.strptime("{} {}".format(d, t), '%m/%d/%Y %I:%M %p')
c... | true |
7d94ff3cb76a7af29af3f8339d5035f9f0b67c2b | Python | LubergAlexander/pywal-homeassistant | /pywal-homeassistant.py | UTF-8 | 1,303 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
import json
import requests
BASE_URL = "http://snowflake:8123"
TOKEN = "" # created a long lived token in HA
WAL_CACHE_FILE = "/home/alex/.cache/wal/colors.json"
def hex_to_rgb(value):
value = value.lstrip("#")
lv = len(value)
return tuple(int(value[i : i + lv // 3], 16) for i in r... | true |
40ac69bc595c373be08b2923ba4648a6cc79b994 | Python | venkatram64/python3_work | /day04/fib017.py | UTF-8 | 106 | 3.390625 | 3 | [] | no_license |
a, b = 0, 1 #means a = 0, b = 0
while a < 10:
print(a)
a, b = b, a + b #means a = b, b = a + b | true |
631276caf10dc23be6c969ce9d70285c912ea101 | Python | knuu/competitive-programming | /atcoder/corp/tenka1_2018_d.py | UTF-8 | 414 | 2.859375 | 3 | [
"MIT"
] | permissive | N = int(input())
yes_set = []
k = 1
while k * (k + 1) < 2 * N:
k += 1
if k * (k + 1) != 2 * N:
print("No")
quit()
ans = []
x = 1
for i in range(k + 1):
row = []
for j in range(i):
row.append(ans[j][i - 1])
for j in range(k - i):
row.append(x)
x += 1
ans.append(row)
pr... | true |
b586b86deb93a392c4a7c518048b86c2604f5e6d | Python | evanthebouncy/class_and_style | /steelbox/subset_selection/other_selections.py | UTF-8 | 1,273 | 2.640625 | 3 | [] | no_license | import numpy as np
import random
import time
import math
from copy import deepcopy
from sklearn.cluster import KMeans
from .knn import score_subset, update_weight
# ----------------- cluster in ( raw_input / embedded class ) space ----------------
def sub_select_cluster(X, Y, n_samples):
kmeans = KMeans(n_clusters... | true |
a635aaf53a45999cbaabfd528bcebc736b22a294 | Python | Rodrigodp/leetPy | /1281. Subtract the Product and Sum of Digits of an Integer.py | UTF-8 | 517 | 3.3125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 19:10:39 2020
@author: Rodrigo
"""
import unittest
class Solution:
def subtractProductAndSum(self, n: int) -> int:
ns = str(n)
pr = 1
sm = 0
for d in ns:
pr = pr * int(d)
sm = sm + int(d)
sub = pr - ... | true |
d5649950e187c86ef11e965682040a4c85a3d14b | Python | Quantumgame/dronestorm | /runtime_modules/estimate/run_estimate_kalman.py | UTF-8 | 1,680 | 2.75 | 3 | [] | no_license | """Estimate state from sensor measurements during runtime
run from terminal with
`python run_estimate_kalman.py`
"""
from __future__ import print_function
from dronestorm.comm.redis_util import DBRedis
import dronestorm.comm.redis_util as redis_util
from dronestorm.comm.redis_util import (
REDIS_IMU_CHANNEL, REDI... | true |
190f5d14d824be3e384730d91d6b67e46ccc03aa | Python | sahanal-2603/Hacktoberfest-2021 | /PYTHON/longest_bitonc_subarray.py | UTF-8 | 1,093 | 4 | 4 | [
"MIT"
] | permissive | # Function to find the length of the longest bitonic subarray in a list
def findBitonicSublist(A):
if len(A) == 0:
return
# `I[i]` store the length of the longest increasing sublist,
# ending at `A[i]`
I = [1] * len(A)
for i in range(1, len(A)):
if A[i - 1] < A[i]:
... | true |
8e360c4843b2b2264e105b6188e2628b27ac2eb4 | Python | kaitlinfrani/Python_Labs | /lab-08-kaitlinfrani-main/test.py | UTF-8 | 3,460 | 4.3125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Kaitlin Frani
CPSC 223P-01
Wed Apr 7, 2021
kaitlinfrani@fullerton.edu
"""
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
# Hangman class
class Hangman:
def __init__(self, word, triesAllowed):
self.word = word
self.triesAllowed = triesAllowed
... | true |
a2c11309be944e310f8905f767117c0c44289a45 | Python | sinister6000/cs599_project | /src/prepdata/myCorpus.py | UTF-8 | 3,617 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division
__metaclass__ = type
import codecs
import os
import types
import prepdata.twokenize as twokenize
from gensim import corpora, utils
from nltk.corpus import stopwords
from nltk.tokenize import TweetTokenizer
# logging.basicConfig(format='%(ascti... | true |
86b40094c697ab0e255080ba589fbfbbd7687ef5 | Python | laetitia-teo/replique-v2 | /blocks.py | UTF-8 | 7,275 | 2.90625 | 3 | [] | no_license | """
This module defines the different residual blocks for composing our generative
and discriminative model.
"""
import torch
import torch.nn.functional as F
from torch.nn import ModuleList
import utils as ut
### Residual Blocks ###
class ResBlockG(torch.nn.Module):
"""
Base residual block for the generator... | true |
6dfe759fb7ee7cf01365b0f6321ae3244db3afb6 | Python | sudeep0901/python | /numpy3.py | UTF-8 | 4,364 | 3.546875 | 4 | [
"MIT"
] | permissive |
#%%
import numpy as np
a = np.array([1, 2, 3])
print(a, type(a), type(np.ndarray), type(type))
angles = np.array([0, 30, 45, 60, 90])
print(angles)
print(np.sin(angles))
print(np.sin(angles))
# convert in radians
angles_radians = angles * np.pi/180
print(angles_radians)
print(np.sin(angles_radians))
print(np.radia... | true |
9472dd00f66e53c67a28fb518174f796ebcd08df | Python | germanbrunini/Microseismic-Tools-Julia-Python | /gathers.py | UTF-8 | 9,998 | 2.671875 | 3 | [] | no_license | import os
from scipy.signal import butter, lfilter
from matplotlib import rc, font_manager
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
rc('text', usetex=True)
plt.rc('font', family='serif')
path = 'gathers/';
fdr_fig_ = "gathers/"
filenames = os.listdir(path) ; # lis... | true |
35de5599a8d4f843a9e0bbfc32a58cec545667b0 | Python | HYUNMIN-HWANG/LinearAlgebra_Study | /LinearAlgebra_Function/5.05.DifferentialEquation.py | UTF-8 | 637 | 3.5625 | 4 | [] | no_license | # Differential Equation
# http://allman84.blogspot.com/2018/10/sympy-1.html
from sympy import *
x, y, z, t = symbols('x y z t')
f, g, h = symbols('f, g, h', cls=Function)
# 미분 방정식 해 구하기
y = symbols('y', cls=Function)
deq = Eq( y(t).diff(t), -2*y(t) )
result = dsolve( deq, y(t) )
print(result)
# Eq(y(t), C1*exp(-2*t)... | true |
d47487dd5c9ebc640d3f5a49930887413d584934 | Python | jpjuvo/HEnorm_python | /normalizeStaining.py | UTF-8 | 5,407 | 2.90625 | 3 | [
"MIT"
] | permissive | import os
import numpy as np
import cv2
def normalizeStaining(imgPath, saveDir='normalized/', unmixStains=False, Io=240, alpha=1, beta=0.15):
''' Normalize staining appearence of H&E stained images.
Produces a normalized copy of the input RGB image to the saveDir path.
If unmixStains=True, separate H and ... | true |
fbb0cd72d1ce618ff605a9e938df866749634241 | Python | RichyRaj/cpsc-8620-benchmark | /test.py | UTF-8 | 7,009 | 3.046875 | 3 | [] | no_license | import duckdb
from time import time
import mysql.connector
class BenchmarkResult():
'''
Represents the result of a benchmark object
'''
def __init__(self):
self.db_name = ""
self.create = 0
self.s_insert = 0
self.m_insert = 0
self.s_select... | true |
dc62f0f58ca4d851a4431fc5f55d783ebe6b1444 | Python | hagarbarakat/LeetCode | /238. Product of Array Except Self.py | UTF-8 | 520 | 2.921875 | 3 | [] | no_license | class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
prod = []
temp = 1
for i in range(len(nums)):
prod.append(1)
print(prod)
for i in range(len(nums)):
prod[i] = tem... | true |
b022190cc3cebb049dc6fbf377099829026a9616 | Python | Zhao-HP/PythonCode | /ObjectUtil.py | UTF-8 | 663 | 3.015625 | 3 | [] | no_license | #! /usr/bin/env python
# -*- coding: UTF-8 -*-
# 将数据库字段名修改为以小驼峰命名方式
def changeFieldName(fieldName):
s = str(fieldName).split("_")
resultStr = s.pop()
for i in s:
resultStr += i.capitalize()
return resultStr
# 将查询结果解析为传入的对象
def parseResultToDomain(result, field, Object):
fieldDict = {}
... | true |
a4c3191766f05eb98fb1092c3fc5480de2c6ab1a | Python | wmfxly/emqx_restart_resume_v2 | /plugin/Test.py | UTF-8 | 2,119 | 2.6875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import traceback
client = mqtt.Client(client_id='emqx_test', clean_session=False)
# 用于响应服务器端 CONNACK 的 callback,如果连接正常建立,rc 值为 0
def on_connect(mqttClient, userdata, flags, rc):
print("Connection returned with result code:" + str(rc))
def ... | true |