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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6aac0cd99a2661f20b38fc81f12bc47dddbf11cd | Python | obliviateandsurrender/pennylane | /qchem/pennylane_qchem/qchem/obs.py | UTF-8 | 39,461 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2018-2020 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... | true |
8f757e2886d37d917df87d45e11e61cb9e8c17d3 | Python | peixingtao01/dataanalysis | /Tkuang/03op操作.py | UTF-8 | 722 | 2.96875 | 3 | [] | no_license | import tensorflow as tf
# 除了加法运算之外还有其他的运算操作
#
a = tf.constant(3.0,name='a')
b = tf.constant(4.0,name='b')
# op叫操作也叫指令。就好像pv操作,就是pv指令一般
# c = tf.sub()
c = tf.add(a,b)
f = tf.placeholder(dtype=tf.int32,shape=[2,2],name='f')
# 运行回话并打印设备信息
# log_device_placement=True))
# target ---指定运行远程设备
# graph ---指定需要运行的图
# confi... | true |
e3bb6fd7c7b030d2bfab316e38b89a2959ec18e5 | Python | icmr2021-mcsf/MCSF | /src/map_summe_video_names.py | UTF-8 | 769 | 2.578125 | 3 | [] | no_license | """
This script maps the summe video numbers to their original names
"""
from os import listdir, path
import pandas as pd
from scipy.io import loadmat
from src.evaluation.summary_loader import load_processed_dataset
PROCESSED_SUMME = '../data/SumMe/processed/eccv16_dataset_summe_google_pool5.h5'
dataset = dataset = ... | true |
3ae2de0e07df68b87a0cf15d24f5432da8c4167a | Python | Alexanderklau/Algorithm | /Everyday_alg/2021/03/2021_03_29/na-ying-bi.py | UTF-8 | 986 | 3.765625 | 4 | [] | no_license | # coding: utf-8
__author__ = "lau.wenbo"
"""
桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。
示例 1:
输入:[4,2,1]
输出:4
解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。
示例 2:
输入:[2,3,10]
输出:8
"""
class Solution(object):
def minCount(self, coins):
"""
:type coins: ... | true |
02fe3d2a0f1507ed0cec9a8319de40fdb5a43488 | Python | linjiesen/Django_Student_Demo | /student/models.py | UTF-8 | 1,322 | 2.546875 | 3 | [] | no_license | from django.db import models
# Create your models here.
class Student(models.Model):
SEX_ITEMS = [
(1, 'male'),
(2, 'female'),
(0, 'unknown'),
]
STATUS_ITEMS = [
(0, 'apply'),
(1, 'pass'),
(2, 'reject'),
]
id = models.CharField(max_length=128, verbo... | true |
7c0517be71f31f4b7640bd5bd84866cf422d5ff6 | Python | tanfengshuang/ethel | /candlepin/account/create.py | UTF-8 | 3,538 | 2.828125 | 3 | [] | no_license | import logging
import requests
import json
import candlepin as env
import candlepin.utils as utils
__author__ = "tcoufal"
def __check_existence(username):
"""
Check if the account is present in Stage Candlepin
Query the Stage Candlepin API and try to login with just the accounts
username.
:para... | true |
d10c053c6262268c38a505cdc401f55f46609c96 | Python | aitch25/Jeju_prediction_for_bus_demand | /extractor/ext_weatherMerger.py | UTF-8 | 666 | 2.625 | 3 | [] | no_license | import pandas as pd
import numpy as np
if __name__=="__main__":
train = pd.read_csv('./DAT/origin/train.csv')
test = pd.read_csv('./DAT/origin/test.csv')
weather = pd.read_csv('./DAT/origin/weather.csv')
outTrain = pd.merge(train[['id', 'date']], weather, how='left', left_on='date', right_on='date')
... | true |
69daf7557b7c23ec4fffce503eedfdd0d4ca17ea | Python | CodecoolMSC2016/python-pair-programming-exercises-2nd-tw-bpekar_gugyan | /listoverlap/listoverlap_module.py | UTF-8 | 252 | 2.78125 | 3 | [] | no_license | def listoverlap(list1, list2):
result = []
for item in list1:
if item in list2:
if item not in result:
result.append(item)
return result
def main():
return
if __name__ == '__main__':
main()
| true |
e1f83322cf7973996ccd70d59581a5abdd98ce17 | Python | jygrinberg/smart_cars | /src/animator.py | UTF-8 | 13,781 | 2.921875 | 3 | [] | no_license | from Tkinter import *
import time
import copy
import util
class Animator:
def __init__(self, size, num_roads, num_cars, high_cost, my_car):
# TODO Replace fixed_cost with high_cost.
self.num_roads = num_roads
self.fixed_cost = util.highCostToFixedCost(high_cost)
self.my_car = my_car... | true |
620aa11dffff667582b02df0903a1811220df6fc | Python | yanliangchen/IT-notes | /Python_demo/coroutine.py | UTF-8 | 1,148 | 3.390625 | 3 | [] | no_license | import time
'''
协程(摘自廖雪峰老师):https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868328689835ecd883d910145dfa8227b539725e5ed000
'''
'''
看这个需要先了解生成器方法
参见收录文章 : http://codingpy.com/article/python-generator-notes-by-kissg/
在这里体现 :
generator其实有第2种调用方法(恢复执行),即通过send(value)方法... | true |
3ae04ee3cfe345707865d0a8f1223a98da71f404 | Python | wangfuchaoooooo/MachineLearning_CSDN | /code/regression/load_data.py | UTF-8 | 264 | 2.609375 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
def read_data(path):
data = np.loadtxt(path)
return data[:, :-1], data[:, -1]
# if __name__ == '__main__':
# data, la = read_data('./data/ex0.txt')
# plt.scatter(data[:,1], la)
# plt.show()
| true |
7224af4f6527b2a087a418218e876e69687512a0 | Python | nodarius/cryptopals | /11.py | UTF-8 | 1,936 | 3.03125 | 3 | [] | no_license | #!/usr/bin/python3
import random
from Crypto.Cipher import AES
def pad(text, blocksize):
n = blocksize - len(text) % blocksize
for i in range(0, n):
text += chr(n).encode();
return text
def xor_encrypt(str, key):
full_key = b''
while(len(full_key) < len(str)):
full_key += key
... | true |
92947683a14ecf6e99f9f5f24c346beb3bbf82f7 | Python | k17pine/hackerrank | /email_validating/main.py | UTF-8 | 874 | 2.921875 | 3 | [] | no_license | import string
def fun(s):
parts = s.split('@')
if len(parts) != 2:
return False
else:
if (username(parts[0])) and (len(parts[0]) != 0):
extension = parts[1].split('.')
if (len(extension) == 2) and (len(extension[1]) < 4):
if website(extension[0]) and... | true |
7227909ed84deb032668a788534e549927ddf0b5 | Python | wwdn-xiang/Focus | /Classification/Medical_evaluation.py | UTF-8 | 2,346 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : Medical_evaluation.py
@Contact : 384474737@qq.com
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
19-10-9 下午3:15 alpha 1.0 None
'''
def caculate_recall(model_1, label):
t... | true |
f2ab7f77376b4fb7146f73588918d0ac26346996 | Python | spellex/Python_Learning | /21_jinja2/task_21_1.py | UTF-8 | 1,159 | 3.171875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
'''
Задание 21.1
Создать функцию generate_config.
Параметры функции:
* template - путь к файлу с шаблоном (например, "templates/for.txt")
* data_dict - словарь со значениями, которые надо подставить в шаблон
Функция должна возвращать строку с конфигурацией, которая была сгенерирована.
Провер... | true |
b26143fdf5db89fe350682cc95cc33d2819d5df7 | Python | is3ka1/Piano-Emulator-With-Leap-Motion | /environment/Naruto's Rasengan.py | UTF-8 | 1,794 | 2.546875 | 3 | [] | no_license | import Leap
from visual import *
from my_color import rasengan_color
controller=Leap.Controller()
scene = display(title='leap motion',width=800,height=600,background=(0.5,0.6,0.5) ,autoscale = False)
hand_Demo=frame()
for _ in range(20):cylinder(frame=hand_Demo, color=(0.5,0.4,0.5)) #20 bones ,thumb has a ... | true |
395e7ba2226de07cf7eaa39f0a6a227135ea9ba9 | Python | drat/TLS-tshark-and-Threat-Intel | /TriagewithCipher.py | UTF-8 | 794 | 3.09375 | 3 | [] | no_license | #!/usr/bin/python
cipher=open("cipher2","r")
server_offer='4865,4867,4866,49195,49199,52393,52392,49196,49200,49162,49161,49171,49172,51,57,47,53,10'
client_choice='49199'
def server_cipher_offer(,server_offer):
# list the cipher and his strength
cipher=open("cipher2","r")
for line in cipher:
l=line.split(","... | true |
32174b3cec32075b0df98f9d7ea88185e7ff4a77 | Python | HigerSkill/Satellite | /scripts/parsing/time.py | UTF-8 | 537 | 3.40625 | 3 | [] | no_license | from typing import List
import datetime
import time
def parse_time_to_sec(filepath: str) -> List:
"""Read file with timestamps."""
timestamps = []
with open(filepath) as f:
for line in f.readlines():
# Parse string time like ``02/11/2021 20:08:00 GPS``
line = line.split(... | true |
f0fd17a6e4ee00f0d6a6a6e0b4f8c164353f5ab8 | Python | Saykon-k/pit | /4_semester/comp_grafic/l239/Vector_matrix_math_Using_tuples_L239/13.py | UTF-8 | 648 | 2.515625 | 3 | [] | no_license | def MxM(m1,m2):
m1 = list(m1)
m2 = list(m2)
prom = []
ne_matr = [[],[],[]]
for i in range(3):
for l in range(3):
prom.append(m2[l][i])
for j in range(3):
m1[j] = list(m1[j])
ne_matr[j].append( VxrealV(m1[j],prom))
prom.clear()
for i in ... | true |
8ea6aaf2aa0b53c1586c789332a24293b60b5b40 | Python | Nightvision53/bisection | /main.py | UTF-8 | 1,053 | 4.28125 | 4 | [] | no_license | # buraya istediğiniz fonksiyonu yazın.
def f(x):
func = (x**3)-(7*(x**2))+(14*x)-6
return func
def bisection(a, b, e, max):
step = 1
condition = True
while condition:
# ortanca değeri bulma.
m = (a + b)/2
# Bu ifade doğruysa kök a ile ortanca değer arasında.
if f(... | true |
3b03e751b727a09fb30467e69228a54ca7b6aea8 | Python | jimherd/robot_head | /lcd03_test.py | UTF-8 | 336 | 2.828125 | 3 | [] | no_license | #!/usr/bin/python
from lcd03 import LCD03
import time
#=====================================================
# LCD03_test : exercise LCD03 class
#
lcd03 = LCD03(0x63, debug=True)
print "LCD03 test started"
lcd03.clear()
lcd03.backlight_on()
value = 42
lcd03.write_str( 'r = {0}'.format(value) )
time.sleep(5)
lcd03.... | true |
a42889836bf09bd257b0ecbcb34ce39dcea94b18 | Python | imldresden/mcv-displaywall | /libavg_charts/aid_lines/deposit_aid_line.py | UTF-8 | 14,948 | 2.8125 | 3 | [
"MIT"
] | permissive | from libavg import avg
from libavg.avg import CursorEvent
from libavg_charts.aid_lines.orthogonal_aid_line import OrthogonalAidLine
from libavg_charts.axis.chart_axis_enums import Orientation
from logging_base.study_logging import StudyLog
class DepositAidLine(OrthogonalAidLine):
ADD_AID_LINE = "addAidLine"
D... | true |
db315d7f1d13b0dce04d746595461e626a60c5ae | Python | adrien-bellaiche/Repartition_Unpreferred | /main.py | UTF-8 | 1,939 | 2.515625 | 3 | [
"MIT"
] | permissive | __author__ = 'BELLAICHE Adrien'
from os import listdir
from ford_fulkerson import execute_algorithm
corresponding = {"\xeb": "e",
"\xe9": "e",
"\xe8": "e",
"\n": ""}
def clean_line(value):
thing = list(value)
for _ in range(len(thing)):
if thing[_]... | true |
adcfcd42221b6bac0d41a7c0d16651922964b3c8 | Python | zhanggh8023/python5 | /class_unit_test0403/http_request.py | UTF-8 | 1,290 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2018/4/4 20:36
# @Author : zgh
# @Email : 849080458@qq.com
# @File : httpRequest.py
# @Software: PyCharm
import requests
class httpRequest:
def __init__(self,url,data):
self.url=url
self.data=data
def getRequest(self):
result=requests.get(self.... | true |
3ed0805375f5c964e5d38eb5f413f3a1d73be3b1 | Python | dionsaputra/tsm-retrain | /dataset.py | UTF-8 | 5,237 | 2.75 | 3 | [] | no_license | from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from PIL import Image
import os
import cv2
class DatasetSplit:
train = 'train'
val = 'val'
test = 'test'
class VideoRecord(object):
def __init__(self, path, label):
self.path = path
self.label = label
cla... | true |
b99fd5b30e0427273a8afe49d8eb7ccce82ffe36 | Python | NathanaelCarauna/UriResolucoesPython | /1020.py | UTF-8 | 185 | 3.328125 | 3 | [] | no_license | dias = int(input())
meses = anos = 0
anos = dias//365
dias%=365
meses = dias//30
dias%= 30
print("{} ano(s)".format(anos))
print("%d mes(es)" %(meses))
print("{} dia(s)".format(dias)) | true |
e1671e8e919ebbfdb10da9ce864474343678730e | Python | Hackatonboiscaliswag/svpremespaghetti | /main.py | UTF-8 | 13,478 | 2.78125 | 3 | [] | no_license | import kivy
kivy.require('1.8.0')
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.checkbox import CheckBox
alimentos =... | true |
0f6eb138ef427c582817a146ce3f7045800c333d | Python | SamuelSebastianMartin/plagcheck | /prune_matches.py | UTF-8 | 2,787 | 3.625 | 4 | [] | no_license | #! /usr/bin/env python3
from operator import itemgetter # To sort tuples by 2nd number.
def prune_indices(matches):
'''Input is a list of tuples, each containing the start and end point
of a match in the essay (sa). This module sorts these tuples by the
second value (i.e. the end point of each matched s... | true |
ddd7c5e64d5b7c2b9a1999ca298bb3110e24efac | Python | ristotoldsep/stockmarket_app | /stockmarket_app.py | UTF-8 | 1,210 | 2.890625 | 3 | [] | no_license | import requests
import time
ticker = "TSLA"
<<<<<<< HEAD
api_key = "<api key>" # apikey from twelvedata
=======
api_key = "<api key>" #api_key from twelvedata
>>>>>>> f09a06682ded668da12c60e8c08e1f92afc53adc
def get_stock_price(ticker_symbol, apikey):
url = f"https://api.twelvedata.com/price?symbol={ticker_symb... | true |
9316d82817782f8d0351c47d6a76a0161a15f184 | Python | gregory-volkov/FormalLangs5sem | /gss/gll.py | UTF-8 | 5,707 | 2.96875 | 3 | [] | no_license | from collections import defaultdict
from string import ascii_uppercase, digits
from itertools import product
class MyGraph:
def __init__(self, node):
# nodes is a dict: node -> set((node, label))
self.nodes = defaultdict(set)
self.nodes = {node: set()}
def add_node(self, fr, to, labe... | true |
0b35aeedc2eb77b34073e78c1098dbb8f0849bf4 | Python | dmitryhd/raspberry_led | /web.py | UTF-8 | 862 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python2
from flask import Flask, request, render_template
#from led import *
RED_LED = 0
GREEN_LED = 1
def power_on(led_num):
print('execute power on', led_num)
def power_off(led_num):
print('execute power off', led_num)
app = Flask(__name__)
@app.route('/')
def led_control():
red_state ... | true |
3ba89f5d1fada4532a607cfeebb6f8c67d8cb930 | Python | PRADEEPSINHCHAVDA/Python-work | /10.py | UTF-8 | 327 | 3.5 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
@author: PRADEEPSINH
"""
def simple_interest(amount,time,rate):
si=(amount*time*rate)/100
print("simple interest:",si)
print("enter amount:")
amount=int(input())
print("enter time:")
time=int(input())
print("enter rate")
rate=float(input())
simple_interest(amount,tim... | true |
3bc068fdd32bd769dab3c51342261595b7a51d96 | Python | gaya38/Python-L1-topgear | /1.py | UTF-8 | 145 | 2.921875 | 3 | [] | no_license | mylist = range(4)
seclist = mylist
print seclist
mylist.append(4)
print seclist
seclist = mylist[:]
print seclist
mylist.append(5)
print seclist
| true |
0731c8b47b2792a289faebfe7fb67cc982073695 | Python | saikiran-tech/KR | /Guess game.py | UTF-8 | 524 | 3.578125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 09:12:12 2019
@author: SAI KIRAN REDDY
"""
import random as rand
r = rand.randint(1,9)
guess = 0
count = 0
while guess!= "exit":
guess = input("Guess the number: ")
if guess == "exit":
break
guess = int(guess)
count+=1
... | true |
e6342dc6a3ef9b74a48ebcb5c955a9dbc968e8fb | Python | jarfo/sort | /cardinality.py | UTF-8 | 2,958 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
""" Encondings of cardinality constraints
Based on the encoding into SAT proposed by:
Abío, Ignasi, Robert Nieuwenhuis, Albert Oliveras, and Enric Rodríguez-Carbonell.
"A parametric approach for smaller and better encodings of cardinality constraints."
In International Conference on Principles... | true |
f3e4765c79ac8c34fda162f8f416e918d4dcdcd5 | Python | PeriklisPetr/periklis-conversion | /conversion.py | UTF-8 | 313 | 3.1875 | 3 | [] | no_license | def dollars2cents(dollars):
cents = dollars * 100
return cents
#My conversion function is better than yours
def km2miles(km)
miles=km*0.621
return miles
def gallons2liters(gallons):
gallons = liters * 4.54
return liters
def moles2atoms(moles):
atoms = moles*32343491maybe
return liters
| true |
1be0d337e27d5d5b6a5300533df3e179ef303e3d | Python | MaseraTiGo/4U | /codes/algorithm/dynamic_programming/climb_stairs.py | UTF-8 | 369 | 3.578125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
# file_func :
# file_author: 'Johnathan.Wick'
# file_date : '6/24/2019 5:45 PM'
def climb_stairs(k: int) -> int:
solution = [0] * (k + 1)
solution[0] = 0
solution[1] = 1
solution[2] = 2
for i in range(3, k + 1):
solution[i] = solution[i - 1] + solution[i - 2]
... | true |
502b950ae071fbbdaaed8924edf582fce85625c2 | Python | MihaiTheCoder/tensorflow | /FirstExample.py | UTF-8 | 205 | 2.65625 | 3 | [] | no_license | import tensorflow as tf
x1 = tf.constant(5)
x2 = tf.constant(6)
#result = x1 * x2
result = tf.mul(x1, x2)
print(result)
with tf.Session() as session:
output = session.run(result)
print(output) | true |
9133b981db5f3e995a38f69df696ed53fd4b857a | Python | vishaal-ranjan/Leetcode-Challenge-April | /25_Jump_Game.py | UTF-8 | 357 | 2.75 | 3 | [] | no_license | class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
if n<=1:
return True
can_reach = 0
i = 0
while i <= can_reach:
if i == n-1:
return True
can_reach = max(can_reach, i+nums[i])
i +... | true |
f412f730dea237fada850d783f15d5ec61eb0cea | Python | m-evtimov96/softUni-python-fundamentals | /4 - Functions/MExer-1.py | UTF-8 | 313 | 3.890625 | 4 | [] | no_license | def calculate(type, thing):
if type == 'int':
thing = int(thing)
print(thing*2)
elif type == 'real':
thing = float(thing)
print(f'{thing*1.5:.2f}')
elif type == 'string':
print(f'${thing}$')
thing_type = input()
thingy = input()
calculate(thing_type, thingy)
| true |
c346abc0125c1ecf1445338fda8f5ec7e0dd0011 | Python | farhan-netizen/IoT-Edge-Server-Program | /thread.py | UTF-8 | 2,022 | 2.953125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 16 19:50:19 2021
@author: ashra
"""
import threading, os, edge_fileread, json, requests
stopFlag = threading.Event()
def retrySendingdata(self, row):
while not self.stopped.wait(5):
#Call HTTP API
json_stirng = json.dumps(r... | true |
d39a88062208b4b4ee20ad93520d18f71a830046 | Python | MrLYC/schemaconvertor | /schemaconvertor/tests/test_demo.py | UTF-8 | 4,880 | 2.90625 | 3 | [] | no_license | #!/usr/bin/env python
# encoding: utf-8
from unittest import TestCase
from collections import namedtuple
from schemaconvertor.convertor import convert_by_schema
Tag = namedtuple("Tag", ["name", "value"])
class User(object):
Role = "Normal"
def __init__(self, name, email):
self.name = name
... | true |
3226b902d2024c3384dcf91a05abdd65d0808030 | Python | Eduardo-Raymond-Beniste66/python2 | /String3.py | UTF-8 | 132 | 3.0625 | 3 | [] | no_license | #incremento no fatiamento
#posso usar um incremento ao fatiar a string
texto = 'batatinha quando nasce'
texto[::2]
texto[::-1]
| true |
cebfa42eddea2b42117520fd35a2cbbce014d77f | Python | sgamage2/dnn_intepretability_p1 | /sequential_explanations/models/ann_toy_problem.py | UTF-8 | 4,045 | 2.640625 | 3 | [] | no_license | import numpy as np
import logging, time, os
import models.ann
import utility
import matplotlib.pyplot as plt
exp_params = {}
exp_params['results_dir'] = 'output'
exp_params['exp_id'] = 'ann_toy'
exp_params['num_train_samples'] = 5000
exp_params['num_test_samples'] = 2500
exp_params['num_features'] = 16
exp_params['a... | true |
3775d5372190c4aae479b32b834cef12c6eec685 | Python | abarnert/slices | /slices.py | UTF-8 | 3,230 | 3.171875 | 3 | [
"MIT"
] | permissive | import collections.abc
import functools
import unittest
def lexical_less(it1, it2):
sentinel = object()
for x, y in itertools.zip_longest(it1, it2, fillvalue=sentinel):
if x is sentinel:
return True
elif y is sentinel:
return False
elif x < y:
return ... | true |
11425852b0e79a1b5f91eba4ba96bc0b4fdff423 | Python | chestnutcone/switcheroo | /user/models.py | UTF-8 | 1,726 | 2.515625 | 3 | [] | no_license | from django.db import models
from django.contrib.auth.models import AbstractUser
class EmployeeID(models.Model):
employee_id = models.IntegerField(primary_key=True,
help_text='enter unique employee id')
is_manager = models.BooleanField(default=False)
def __str__(self... | true |
fbaed5166c47a4dc33e7753519459a8ddab4668f | Python | xiaoxiaofengzi/tmp_file | /Utils/TextClass.py | UTF-8 | 2,374 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from project_demo.tools.fenci import *
from collections import *
class textPandas:
def __init__(self, textdf, col, targetcol=None):
self.textdf = textdf
self.col = col
self.targetcol = targetcol
def text2list(self,targetcol,isjieba=False,**kargs):
... | true |
b4ae9b7cf60da5e359c877a9c5a221d4d654efc2 | Python | daniel-reich/ubiquitous-fiesta | /zhqL89ZWgbxbixsdD_10.py | UTF-8 | 170 | 3.15625 | 3 | [] | no_license |
def is_exact(n, fac=1, i=1):
# Your recursive implementation of the code.
return is_exact(n, fac*i, i+1) if fac < n else ([fac, i-1] if fac == n else "Not exact!")
| true |
8dd5e01fe71727c48307b0f58dc1ecbc5e99716f | Python | valentin1993/Etat_civil | /Identity/Logger.py | UTF-8 | 712 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python
# -*-coding:Latin-1 -*
""""
Module to login and logout users to the GED
"""
import Gedurl
import zeep
import sys
#Declaration of the URL service
Auth = Gedurl.GEDurl + '/services/Auth?wsdl'
#Declaration of the client SOAP via Zeep
client = zeep.Client(wsdl=Auth)
#Connect the us... | true |
5a142a9a26babd05d7530248eb4f9875eb0df7cb | Python | asdewar/event_conversor | /src/converters/aedatConverterVersions/aedat4Converter.py | UTF-8 | 855 | 2.546875 | 3 | [] | no_license | from src.format.EventClass import Event
from src.utils.utils import nsecsToSecs
from src.ui.UI import UI
import aedat
def aedat4ToAbstract(input_file):
UI().objectUI.showMessage("Starting to read aedat4 file", "w")
decoder = aedat.Decoder(input_file)
event_list = []
UI().objectUI.showMessage("Startin... | true |
034fe03207546cd319404b2b1414b16dbbbff3fe | Python | VittorioYan/Leetcode-Python | /121.py | UTF-8 | 712 | 2.859375 | 3 | [] | no_license | from typing import List
import collections
import bisect
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
_min = prices[0]
ans = 0
for price in prices[1:]:
ans = max(ans,price-_min)
_min = min(_min,price)
... | true |
509086b9ed4db1054e03df4d274176c0051efea6 | Python | vrushankjani/aws-soe-ami-end-to-end-automation | /consuming/pipeline/test/conftest.py | UTF-8 | 1,178 | 2.53125 | 3 | [] | no_license | import pytest
from mock import MagicMock
class CodePipelineClientMock(object):
def __init__(self, monkeypatch, module_path):
self.success_mock = MagicMock()
self.failure_mock = MagicMock()
monkeypatch.setattr(
'%s.codepipeline_client.put_job_success_result' % module_path,
... | true |
f51068edfd1e054a6f6ca13c28e5d56268db0e3e | Python | AmritTalwar/tech-interview-questions | /arrays_and_strings/move_zeroes_to_end.py | UTF-8 | 909 | 3.984375 | 4 | [] | no_license | # SOURCE: https://leetcode.com/problems/move-zeroes/
"""
TIME COMPLEXITY: O(N) N = number of elements in array
Worse case there are no zeroes, so we perform operations on every single element (swapping it with itself). The 'actual' time complexity or best
case is O(numer of non zero elements).
SPACE COMPLEXITY: O(1)... | true |
08d722177784a8e11d7c07ea5033641974e7bcae | Python | Reikenzan/Some-Python | /SomeWork/Spring2013/Q_5.py | UTF-8 | 212 | 3.71875 | 4 | [] | no_license | """What is returned when the function is invoked on the inputs below:
"""
def sum(a,b):
return a+b
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, sum(a,b)
return a
| true |
c7f83e03368c1bc54fae77f83dc808016bbae094 | Python | Umeshbhatt144/kaggleProjects | /Kaggle/HackerRank/30 Days of Code/Day 16_ Exceptions - String to Integer.py | UTF-8 | 192 | 3.3125 | 3 | [] | no_license | # Link : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem
#!/bin/python3
import sys
S = input().strip()
try:
print(int(S))
except:
print("Bad String")
| true |
28981ceb0c2d3a968701e7770b794c341b12fa12 | Python | gabrielrmodesto/python | /app.py | UTF-8 | 1,392 | 4.1875 | 4 | [] | no_license | # -*- coding: UTF-8 -*-
import re
def cadastrar(nomes):
print 'Digite seu nome'
nome = raw_input()
nomes.append(nome)
def listar(nomes):
print 'Lista de nomes'
for nome in nomes:
print nome
def remover(nomes):
print 'Quem voce deseja tirar?'
nome = raw_input()
nomes.remove(nome)
def alterar(nomes):
print... | true |
61904f21b16fb63fc3421c0064e1d944c29b1c47 | Python | DloBagari/python_scripts | /oop/test_asscess_layer_sqlite.py | UTF-8 | 450 | 2.53125 | 3 | [] | no_license | from access_layer_sqlite import *
from mapping_object_to_sql import *
from create_tables import *
s = Access()
s.open("dd.db")
s.build_tables(CreateTables.create())
b = Blog(title = "dlo")
p = Post(title="post1", date="2016",rst_text="some thext")
p.append("tag1")
p.append("tag2")
b.append(p)
s.add_blog(b)
b2 = s.g... | true |
937f3f021b2d64aee84f45272ad6443f339e8e99 | Python | datAnir/GeekForGeeks-Problems | /Binary Tree/remove_node_with_1_child.py | UTF-8 | 911 | 3.859375 | 4 | [] | no_license | '''
https://practice.geeksforgeeks.org/problems/remove-half-nodes/1
Given A binary Tree. Your task is to remove all the half nodes (which has only one child).
Input:
2
7 7 8 2
2 7 5 N 6 N 9 1 11 4
Output:
2 7 8
1 6 11 2 4
Explanation:
Test Case 1: The given tree is:
7
/ \
7 8
/
2
Modified tree af... | true |
f8eb4450993125dd75112a1ac8dd6e6f9ab7ffd6 | Python | eduardochagas/material-ref-estudo | /material-ref-python3/metodos_de_array/metodos_de_array.py | UTF-8 | 14,627 | 4.59375 | 5 | [] | no_license | ##################################
#
# Metodos de array
#
##################################
print('-=' * 50)
print('--------- Metodos de Array ---------')
print('-=' * 50)
print()
print('Um array comum.')
alfabeto = ['a', 'b', 'c']
print(alfabeto)
print()
#----------------------------------------
#
# inserindo ... | true |
ce92b8bd8af8598baca19f9cf5384793ab81decc | Python | nirzaf/python_excersize_files | /section5/lecture_017.py | UTF-8 | 119 | 3.765625 | 4 | [] | no_license | months = ['january', 'february', 'march', 'april']
message = "I was born in " + months[3].title() + "."
print(message) | true |
875604503037370fe5d81d753ba516ec60e9cca3 | Python | vturrisi/pytorch101 | /simple_cnn/second.py | UTF-8 | 5,318 | 2.71875 | 3 | [] | no_license | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
from torchvision import transforms, datasets
train_data = MNIST('mnist', download=True, train=True)
test_data = MNIST('mnist', download=True, train=False)
# https://... | true |
2b5d1ee776bb373b4a4dfc0229b3a0977e1b26d5 | Python | sleepyeye/random-fourier-features-pytorch | /examples/image_representation_mlp.py | UTF-8 | 1,909 | 2.765625 | 3 | [
"MIT"
] | permissive | import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import rff
from itertools import repeat
from tqdm import tqdm
class MultiLayerBlock(nn.Module):
def __init__(self, hidden_layer_size: int = 256):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(hidden_layer_si... | true |
ed67de86b531c69862b142ded7931107192aa9c6 | Python | JMoicano/Metaheuristica | /City.py | UTF-8 | 471 | 3.71875 | 4 | [] | no_license | class Point(object):
"Euclidian point"
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(%.3f, %.3f)" %(self.x, self.y)
def __sub__(self, p):
return int(((self.x - p.x)**2 + (self.y - p.y)**2)**(.5)+0.5)
def __eq__(self, other):
return self.x == other.x and self.y == other.y... | true |
78b1b39fa2dd541e46fbc430bcf610b77c54032e | Python | diaz2691/Realstate-geofencing | /PQLogin/PQLogin.py | UTF-8 | 4,826 | 2.5625 | 3 | [] | no_license | # import requests
# from bs4 import BeautifulSoup
# with requests.Session() as c:
# url = "https://pqweb.parcelquest.com/#login"
# user = 'baycapital'
# passw= 'realestate'
# c.get(url)
# login_data = dict(UserName=user, Password=passw)
# c.post(url, data=login_data)
# page = c.get('https://pqweb.parcelquest.c... | true |
1592faae33a8d5293905b50f02db7e87cb4b1d30 | Python | sbl1996/pytorch-snippets | /auto_encoder.py | UTF-8 | 2,048 | 2.578125 | 3 | [] | no_license | from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader, Dataset
from torch.autograd import Variable
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
from trainer import ModuleTrainer
class Auto... | true |
a93d7965be35dc78bf769c389c89075752d69ec3 | Python | a-ndujiuba/A-B-Test-Data-Analysis | /ab_test_project.py | UTF-8 | 8,532 | 3.171875 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Obtain 4 pie charts showing the different locationStep
# completions, and if they performed a searchCTA
# Plot bar chart with 3 bars, showing the different test variants,
# and if they performed a searchCTA - layer the bar charts to show %... | true |
1b95fb76d12b6499c74e82753b6c7bba46fde67d | Python | deepanshu-yadav/mstar_classification | /src/plotting/plotter.py | UTF-8 | 5,958 | 2.90625 | 3 | [] | no_license | import matplotlib.pyplot as plt
# import tensorflow as tf
import numpy as np
# import time
# from datetime import timedelta
# import os
# import glob, pickle
# import sys
# # Functions and classes for loading and using the Inception model.
from scipy.misc import imsave
from PIL import Image
def plot_ima... | true |
323792d57fc943304c361506d07e094935cda8b6 | Python | peeraponw/disease_sim | /diseaseSim_multi.py | UTF-8 | 6,772 | 3.109375 | 3 | [] | no_license | #
# diseaseSim.py - simulates the spread of disease through a population
#
# Student Name :
# Student Number :
#
# Version history:
#
# 25/4/19 - beta version released for FOP assignment
#
import numpy as np
import matplotlib.pyplot as plt
import random
import pandas as pd
import sys
# Keep these numbers to mainta... | true |
1cc6ba282972367783b8b430872e10661db6f851 | Python | Alain-TC/kaggle_real_estate | /kaggle_blueprint/preprocessing/transformers/add_column_transformer.py | UTF-8 | 1,269 | 3.109375 | 3 | [] | no_license | from sklearn.base import TransformerMixin
class CreateSumTransformer(TransformerMixin):
def __init__(self, target_features_list):
self.target_features_list = target_features_list
def fit(self, df=None, y=None):
return self
def transform(self, df):
for couple in self.target_featur... | true |
6640b63682f40c4a8f698e539d24dd9ab4eebd93 | Python | trimcao/artificial-intelligence-uc-berkeley | /4.bayesNet/powerChoosingAgents.py | UTF-8 | 2,822 | 3.328125 | 3 | [] | no_license | # powerChoosingAgents.py
# ----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http... | true |
63c9d59db0230688495148136629ace01fa76136 | Python | MrCsabaToth/IK | /2019Nov/sorting2/four_billion_10MiB_9bit_buckets_coderpad.py | UTF-8 | 2,140 | 3.359375 | 3 | [
"Apache-2.0"
] | permissive | def find_integer(arr):
# 1. Bucketized counts
bucket_bits = 9
bucket_size = 2 ** bucket_bits
bucket_count = 2 ** (32 - bucket_bits)
buckets = [0] * bucket_count
for a in arr:
i = a // bucket_size
buckets[i] += 1
# 2. Pick a bucket
b = 0
for bucket in buckets:
... | true |
371027eee0fcadebbb745c1936fd84a9be9f2cf7 | Python | rhedshi/project-euler | /python/problems/010_problem.py | UTF-8 | 389 | 3.515625 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Problem 10 - Summation of primes
================================
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
from utils.prime import gen_prime
sum = 0
for prime in gen_prime():
if prime > 2000000... | true |
6b6f56109afa5a882044f339ad8954babfc91ba1 | Python | luhy-work/Recommended_System_Homework | /Week2/TagBased_TDIDF.py | UTF-8 | 5,379 | 3.078125 | 3 | [] | no_license | # 使用TagBased_TDIDF算法对Delicious2K数据进行推荐
# 数据格式: userID bookmarkID tagID timestamp
import random
import math
import operator
class TagBased_TDIDF():
# 构造函数
def __init__(self, filename):
self.filename = filename
self.loadData()
self.randomlySplitData(0.2)
s... | true |
db2f2a90ab0894fca0015de7d08216bfc8c6a63a | Python | EstiT/LogicCircuitEval | /LogicCircuitEval.py | UTF-8 | 4,122 | 3.546875 | 4 | [] | no_license | #Collier, R. "Lectures Notes for COMP1405B – Introduction to Computer Science I" [PDF document].
#Retrieved from cuLearn: https://www.carleton.ca/culearn/ (Fall 2015).
from SimpleGraphics import *
def main ():
a,b,c,d,e=input("Enter either (T)rue or (F)alse five times without spaces: ")
Val1,Val2,Val3,Val... | true |
50b03cae001563f6ffc5449a57cfca3aa89e9b9e | Python | tainenko/Leetcode2019 | /leetcode/editor/en/[1196]How Many Apples Can You Put into the Basket.py | UTF-8 | 1,150 | 3.40625 | 3 | [] | no_license | # You have some apples and a basket that can carry up to 5000 units of weight.
#
# Given an integer array weight where weight[i] is the weight of the iᵗʰ apple,
# return the maximum number of apples you can put in the basket.
#
#
# Example 1:
#
#
# Input: weight = [100,200,150,1000]
# Output: 4
# Explanati... | true |
579adaedbbeaa1ea4c3f51433ee02a1f438b2a05 | Python | chinawindofmay/multi-objective-optimization-NSGA2 | /B_MOO_004_NSGA3_0810_PS/b_route_planner.py | UTF-8 | 1,698 | 2.65625 | 3 | [] | no_license | # -*- coding:utf-8 -*-
"""
基类:路径规划基础对象
作用:存储URL格式、控制是否是批量请求的方式、解析返回结果的解析逻辑
"""
class BaseRoutePlanner(object):
URL = ''
def __init__(self, demand_id,provider, *args):
self.API_KEY = "234e96d7ab5d31365ddd32c213cffb7b"
# self.API_KEY = "ccf0b26003c9f5b55ce2c47f1ac67bdb"
# self.API_KEY = "... | true |
aafc53d5f149b81260a92d4ea6fb62fae17c1057 | Python | Adinai949/chapter3t4 | /chapter3t4.py | UTF-8 | 260 | 3.25 | 3 | [] | no_license | lst = input('Введите числа через пробел: ').split(' ')
lst = list(map(int, lst))
m = max(lst)
m =int(m)
if m < 0:
print(1)
else:
for n in range(1,m + 2):
if n not in lst:
print(n)
break
| true |
b60b9f3b87d8694bab75ffc7544b4ff2c5efc5c5 | Python | androidjp/py-practice | /base/2.if_else/IfElse.py | UTF-8 | 495 | 4.34375 | 4 | [] | no_license | print('===================================')
print('[例子A]')
print('------')
if False:
print('That is true')
else:
print('that is false')
print('===================================')
print('[例子B]')
print('------')
you = "A"
if you == "B":
print('You are B')
elif you == "A":
print("You are A")
else:
... | true |
8eacfb1962fc4315cfa91d14a2c06b88c67194e7 | Python | strama/CTF-TOOLS | /brainfuck.py | UTF-8 | 1,469 | 3.265625 | 3 | [] | no_license | #!/usr/bin/python
#Brainfuck Decoder
import sys
ALLOWED_CHARS = '+-.,<>[]'
MEN_SIZE = 30000
def run(prog):
mem = [0] * MEN_SIZE
prog = ''.join(c for c in prog if c in ALLOWED_CHARS)
matching_brackets = precompute_matching_brackets(prog)
ip = 0 #Instruction Pointer
dp = 0 #Data Pointe... | true |
60a563d1f8f3cde63974871a82d8492693f7b549 | Python | EC-SEAL/reconciliation | /lib/comparison.py | UTF-8 | 4,516 | 3.359375 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Factory for the different comparison methods for a pair of strings
# Supports library loading of additional comparators
# Classes must implement:
# def compare(self, source, target):
# Receive 2 strings, return a string similarity rate between 0 and 1
from lib.comparator... | true |
fe0e54c718b1309211ec7a01e4d1c445b548b844 | Python | weelin-zhang/bookmarks | /account/authentication.py | UTF-8 | 1,924 | 2.546875 | 3 | [] | no_license | from django.contrib.auth.models import User
from django.conf import settings
import ldap
class EmailAuthBackend(object):
"""
Authenticate using e-mail account.
"""
def authenticate(self, username=None, password=None):
print(self.__class__.__name__)
try:
user = User.objects.g... | true |
5f520e3a80f84a18e5d9066e7d3b8df1820ab60a | Python | HelloHuDi/Python_Learn | /learnGrammar/io_learn.py | UTF-8 | 2,546 | 3.90625 | 4 | [
"Apache-2.0"
] | permissive | with open("testFile/read.txt") as file:
# print(len(file.read().strip().split()))
for line in file:
print(line.strip().split(","))
# r :只读 ,w:只写,文件若存在则清空内容,不存在则创建,a:追加,不会清空内容,r+ :读写模式
""""
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文... | true |
6cb63ede670b07ab1f6ca253736498f75acc5d3c | Python | zhangfuli/leetcode | /手把手刷数据结构/twoSum问题/1. 两数之和.py | UTF-8 | 753 | 3.609375 | 4 | [] | no_license | # 给定一个整数数组 nums和一个整数目标值 target,
# 请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
# 你可以按任意顺序返回答案。
#
#
# 示例 1:
#
# 输入:nums = [2,7,11,15], target = 9
# 输出:[0,1]
# 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
class Solution:
def twoSum(self, nums, target):
hashmap = {}
... | true |
d8e7e1b5315e973aa64e07d1f52d9707a0005812 | Python | Rosster/MLFinalProject | /src/model_generators/tree_regressor.py | UTF-8 | 3,185 | 2.703125 | 3 | [
"MIT"
] | permissive | from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
import pandas as pd
from sklearn import metrics
import numpy as np
RESPONSE_VARIABLE = 'count'
def construct(train_df, algo, opts={}, remove_features=None):
feature_cols = [col for col in train_df.columns if RESPONSE_VARIABLE not in col]
... | true |
1be086833ad08dff77a4e7b6e38047beb5f09505 | Python | sukrutrao/crowdsourced-data-simulator | /simulator.py | UTF-8 | 7,987 | 2.796875 | 3 | [
"MIT"
] | permissive | import bisect
import csv
import numpy as np
class Simulator:
def __init__(self, num_people, num_questions, options_per_question, answers_per_question="single", sparsity=0):
assert(sparsity >= 0 and sparsity <= 1)
assert(num_people > 0)
assert(num_questions > 0)
assert(options_per_... | true |
ec987705d1b610cf2e05a3746bcc8a7fd80a7812 | Python | Mishlen337/DaisyKnitTelegramBot | /utils/db_api/models/question_order.py | UTF-8 | 481 | 2.546875 | 3 | [] | no_license | """Module to declare question order model."""
from .question import Question
from .survey import Survey
from numpy import uint32
class QuestionOrder:
"""Class to declare question order model."""
def __init__(self, question: Question, survey: Survey):
self.question = question
self.survey = sur... | true |
96101831b6ac82a2efc5f77de432e90802ff632e | Python | neu-velocity/code-camp-debut | /codes/MartinMa28/python3/0127_word_ladder.py | UTF-8 | 1,395 | 3.453125 | 3 | [] | no_license | class Solution:
def _replacement(self, word: str) -> list:
reps = []
for l_i, l in enumerate(word):
reps.append(word[:l_i] + '*' + word[l_i + 1:])
return reps
def ladderLength(self, beginWord: str, endWord: str, wordList: list) -> int:
if wordList == []:
... | true |
40e05afa41c6be41d33a733b8275aa5c5bdd51e5 | Python | byceps/byceps | /tests/integration/api/v1/tourney/match/comments/test_update.py | UTF-8 | 2,034 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | """
:Copyright: 2014-2023 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from byceps.services.tourney import (
tourney_match_comment_service,
tourney_match_service,
)
def test_update_comment(api_client, api_client_authz_header, comment, user):
original_comm... | true |
705d17ee3e98e151a56733826761f2dc9d4730d1 | Python | cafpereira/coding_practice_2018 | /interview-bit/14_prob_jump_lvl6/longest_consecutive.py | UTF-8 | 517 | 3.21875 | 3 | [] | no_license | class Solution:
# @param A : tuple of integers
# @return an integer
def longestConsecutive(self, A):
S = set()
res = 0
for i in A:
S.add(i)
for i in A:
if i + 1 in S:
continue
count = 1
prev = i - 1
... | true |
32d10dc8d33f1328c1f4d95799a45ffdf204207e | Python | JoTaijiquan/Python | /Python101-New130519/2-7-1.py | UTF-8 | 1,462 | 3.515625 | 4 | [] | no_license | #Python 3.9.5
#Example 2-7-1
'MORSE Code encoder/decoder'
morse_dict= {
'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..',
'e':'.', 'f':'..-.', 'g':'--.', 'h':'....',
'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..',
'm':'--', 'n':'-.', 'o':'---', 'p':'.--.',
'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
... | true |
8979ba333329c3b28996365ce6649235501613cc | Python | lingzhi42166/Python | /11_网络编程/6_TCP粘包问题.py | UTF-8 | 3,754 | 3.46875 | 3 | [] | no_license | """
什么是粘包:
上一次传输的数据 没有被完全接收掉
保存在了缓存区 下一次再往该地方发数据
就会跟着一起发送过去了,导致数据全部乱了
为什么会粘包:
1、因为TCP是基于流传输数据的 流式协议 数据像水一样流过去 数据与数据之间没有边界
使用了优化方法(Nagle算法),将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包。
2、TCP协议的接收方和传输方 都有一个缓存机制
所有数据都先经过缓存区 然后再根据设置的大小提取数据
所以导致如果同一次连接发送的数据 没有被完全接收 就会遗留在缓冲区中 并跟随下一次继续传输
为什么不... | true |
e761ec9bd287a974e3e1c187ceea26aa1490dd12 | Python | Dashora7/Twitter-Streaming-and-Analysis | /twitter_streamer.py | UTF-8 | 1,800 | 2.78125 | 3 | [] | no_license | # Import the necessary package to process data in JSON format
try:
import json
except ImportError:
import simplejson as json
# Import the tweepy library
import tweepy
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = ''
ACCESS_SECRET = ''
CONSUMER_KEY = ''
CONSU... | true |
37f75a6ecfa180d91da42c8a8c3cf3c8adf95a0e | Python | OvanGarderen/ProjectWiskunde | /FFT2util.py | UTF-8 | 5,641 | 2.765625 | 3 | [] | no_license | import cmath,math,copy
import numpy as np
from DFTutil import *
from cmath import pi
VERSION = 1
def FFT( ls ):
N = len(ls)
ls += [0 for i in range( minimaxpow2(N) - N)]
return _FFT(ls)
def _FFT( ls ):
N = len(ls)
if N <= 1:
return ls
else:
# De e-machten in de sommatie zijn... | true |
80145bb961b53d1b153cd9fd7c9cf52b903efc15 | Python | 625781186/lgd_spiders | /projects/12306/12306.py | UTF-8 | 11,712 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
# @Time : 2019/9/21 14:52
# @Author : LGD
# @File : 12306.py
# @功能 : 爬取12306的车票信息
import json
import requests
import datetime
from colorama import init, Fore
from prettytable import PrettyTable
init(autoreset=False)
# 获取车站的版本信息,进而获取车站的全拼,简拼,代码等信息
def get_station_version(stations):
... | true |
e501064d45756d57adb90473ead16de67be1ebb4 | Python | Sangarshanan/geopatra | /geopatra/folium/geojson.py | UTF-8 | 1,900 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | """Folium geojson Plot."""
import folium
from .utils import _random_color_hex, _folium_map, _get_tooltip, _random_string
def geojson(
gdf,
name="layer",
width="100%",
height="100%",
location=None,
color="blue",
tooltip=None,
zoom=7,
tiles="OpenStreetMap",
attr=None,
style=... | true |
6326ede2ace72a5b26ec8ed8f46c7eeb2c1d7df9 | Python | league-python-student/level0-module1-bloobglob | /_04_int/_1_riddler/riddler.py | UTF-8 | 1,135 | 3.9375 | 4 | [] | no_license | '''
* Write a python program that asks the user a minimum of 3 riddles.
* You can look at riddles.com if you don't already know any riddles.
* Collect the response of each riddle from the user and compare their
answers to the correct answer.
* Use a variable to keep track of the correctly answered riddles... | true |
784b3fbfc3c08e7888ed5d238aa061dba8e7821f | Python | tulcas/master-python | /21-tkinter/02-textos.py | UTF-8 | 797 | 3.484375 | 3 | [
"MIT"
] | permissive | from tkinter import *
ventana = Tk()
ventana.geometry("700x500")
texto = Label(ventana, text="Bienvenido a mi programa...")
texto.config(
fg="white",
bg="black",
padx=500,
pady=20,
font=("Consolas", 30)
)
texto.pack()
texto = Label(ventana, text="Soy Victor... | true |
26ad5240c080520c1aea083bfeafdbbdc6277f48 | Python | karpov78/rosalind-algo | /python/coursera/21.py | UTF-8 | 118 | 2.640625 | 3 | [] | no_license | import math
prob = math.pow(0.25, 9)
print prob
prob1000 = prob * (1000 - 9 + 1)
print prob1000
print prob1000 * 500
| true |
e9d05bad266cf79abb1d63794e93966fb82c8b4d | Python | staciajohanna/18.065-covid-final-project | /lasso_regression.py | UTF-8 | 1,260 | 2.609375 | 3 | [] | no_license | from sklearn.linear_model import Lasso
from sklearn.metrics import r2_score, mean_squared_error
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
train_y = pd.read_csv("data//train_y.csv")
val_y = pd.read_csv("data//val_y.csv")
alpha = np.linspace(0.01,0.4,10)
alpha = np.linspace(0.01,0.4,10)
for... | true |
a665abf3df09619bf8e56046f3465cf863353b24 | Python | tinnguyenhuuletrong/Learning | /webrtc-playground/python/util/ImageViewStreamTrack.py | UTF-8 | 893 | 2.671875 | 3 | [] | no_license | import math
import cv2
from av import VideoFrame
from aiortc import (
VideoStreamTrack,
)
class ImageViewStreamTrack(VideoStreamTrack):
"""
A video track that returns an animated flag.
"""
def __init__(self, img_path):
super().__init__() # don't forget this!
self.img = cv2.imread... | true |