seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
8855381653 | import re
import string
import pyarabic.araby as ab
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# nltk.download('stopwords')
stopwords = stopwords.words('Arabic')
tw = []
tweets = 0
class pre_processing:
def clean_data(self):
for tweets in self:
tash... | Minaaa01/Arabic-Tweets-Classification | preprocessing.py | preprocessing.py | py | 1,601 | python | en | code | 0 | github-code | 50 |
21542153332 | N = int(input())
v = [0]
f = 0
for i in range(N):
v.append(int(input()))
for i in range(1, N+1):
for j in range(i+1, N+1):
lie = []
a = [1]*(N+1)
a[i] = a[j] = -1
for k in range(1, N+1):
if v[k]*a[abs(v[k])] < 0:
lie.append(k)
if len(lie) == 2 ... | hurttttr/MyPythonCode | PAT/1089 狼人杀-简单版.py | 1089 狼人杀-简单版.py | py | 475 | python | en | code | 3 | github-code | 50 |
41512522344 | # -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: pip install fastapi uvicorn
"""
import argparse
import uvicorn
import sys
import os
from fastapi import FastAPI, Query
from starlette.middleware.cors import CORSMiddleware
from loguru import logger
sys.path.append('..')
from nerpy import NERMod... | shibing624/nerpy | examples/server_demo.py | server_demo.py | py | 1,439 | python | en | code | 84 | github-code | 50 |
40094658430 | from __future__ import print_function
import os
import FWCore.ParameterSet.Config as cms
# for json support
try: # FUTURE: Python 2.6, prior to 2.6 requires simplejson
import json
except:
try:
import simplejson as json
except:
print("Please use lxplus or set an environment (for example crab... | cms-sw/cmssw | Alignment/MuonAlignmentAlgorithms/python/gather_cfg.py | gather_cfg.py | py | 19,154 | python | en | code | 985 | github-code | 50 |
22647988119 | from typing import List
import bisect
class Solution:
# 풀이 1. 투 포인터
def twoSum1(self, numbers: List[int], target: int) -> List[int]:
left, right = 0, len(numbers) - 1
while not left == right:
if numbers[left] + numbers[right] < target:
left += 1
elif num... | Wooyongjeong/python-algorithm-interview | 18 이진 검색/68 두 수의 합 2.py | 68 두 수의 합 2.py | py | 2,272 | python | en | code | 0 | github-code | 50 |
26187968939 | import os
import sys
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
)
from megatron.training import forward_step
from megatron.utils import setup_for_inference_or_eval, init_wandb
from megatron.logging import tb_wandb_log
from eval_tasks import run_eval_harness
from pprin... | EleutherAI/gpt-neox | evaluate.py | evaluate.py | py | 1,707 | python | en | code | 6,191 | github-code | 50 |
35209467789 | import logging, py_libgit.settings
logger = logging.getLogger(__name__)
from py_libgit.core.commit_blob import CommitBlob
from py_libgit.core.repo import Repo
class Commit:
def __init__(self):
logger.info('Create the Commit object')
self.repo = Repo()
def create_commit(self, author, commit_me... | tony-yang/e-libgit | py_libgit/py_libgit/api/commit.py | commit.py | py | 619 | python | en | code | 0 | github-code | 50 |
41851812122 | import cv2
import numpy as np
import smtplib
import threading
import geocoder
from datetime import datetime
# Global variables
Alarm_Status = False
Email_Status = False
Fire_Reported = 0
# Function to send an email with incident location and screenshot
def send_mail_function(lat, lon, screenshot_path):
... | dharaneesh-202/fire-dehazing | mail_fire.py | mail_fire.py | py | 4,702 | python | en | code | 0 | github-code | 50 |
31040691362 | import torch
import torch.nn as nn
from ..gnn.nf import NFGNN
from ..readout.sum_and_max import SumAndMax
__all__ = ['NFPredictor']
# pylint: disable=W0221
class NFPredictor(nn.Module):
"""Neural Fingerprint (NF) for regression and classification on graphs.
NF is introduced in `Convolutional Networks on Gra... | awslabs/dgl-lifesci | python/dgllife/model/model_zoo/nf_predictor.py | nf_predictor.py | py | 4,890 | python | en | code | 641 | github-code | 50 |
40200792380 | import FWCore.ParameterSet.Config as cms
TrackerDTCAnalyzer_params = cms.PSet (
InputTagAccepted = cms.InputTag( "TrackerDTCProducer", "StubAccepted" ), # dtc passed stubs selection
InputTagLost = cms.InputTag( "TrackerDTCProducer", "StubLost" ), #... | cms-sw/cmssw | L1Trigger/TrackerDTC/python/Analyzer_cfi.py | Analyzer_cfi.py | py | 991 | python | en | code | 985 | github-code | 50 |
27211452073 | # 差分数组工具类
class Difference(object):
def __init__(self):
self.diff = []
# 输入一个初始数组,区间操作将在这个数组上进行
def difference(self, nums):
assert len(nums) > 0
m = len(nums)
# 根据初始条件构造差分数组
self.diff = [0] * (m+1) # 创建和nums长度一致的全0数组
nums.insert(0, 0) # 往前面的数组增加一个0元素,方便后续操作... | zranguai/leetcode-solution | LeetCode/数组题/370.区间加法(差分数组).py | 370.区间加法(差分数组).py | py | 2,257 | python | en | code | 1 | github-code | 50 |
74781837275 | class Settings:
def __init__(self):
self.screen_with = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed = 1.5
# 子弹设置
self.bullet_speed = 1.0
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60,... | eatureide/python | alien_invasion/settings.py | settings.py | py | 558 | python | en | code | 0 | github-code | 50 |
72961458395 | from os import path
from config import load_config
import subprocess
def valid_signature(fpath, sig_fpath):
command = ['gpg', '--verify', sig_fpath, fpath]
rc = subprocess.call(command)
return not rc
def sign_file(fpath, sig_fpath):
command = ['gpg', '--output', sig_fpath, '--detach-sig', fpath]
... | dateutil/tzdata | generate_signatures.py | generate_signatures.py | py | 1,919 | python | en | code | 1 | github-code | 50 |
11981791114 | # coding=utf-8
import os
import shutil
import requests
import img2pdf
from tqdm import tqdm
from zipfile import ZipFile
from PyPDF2 import PdfFileWriter, PdfFileReader
from threading import Thread
from config import Config
headers = {
'User-Agent': '环球银幕HD 2.2 rv:1.0 (iPad; iOS 12.1.3; zh_CN)'.encode('utf-8'),
... | moriwang/WorldScreen | main.py | main.py | py | 4,014 | python | en | code | 0 | github-code | 50 |
40343609822 | """Chatbot101 with AWS Lambda Console Script.
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
"""
impo... | coleyr/Lambda_webex_bot | app.py | app.py | py | 3,967 | python | en | code | 0 | github-code | 50 |
74187664474 | from insanonym_utils.runner import Runner
from insanonym_utils.utils import _readModel
from insanonym_utils.models import FileConfigModel, DeleteAlgorithm, DeleteOptions
from os import getcwd
from pandas import isnull
def test_create_dataframe():
model = _readModel(getcwd(), 'parser.cfg')
df = Runner(model)
... | danymat/INSAnonym-utils | tests/test_anon.py | test_anon.py | py | 719 | python | en | code | 8 | github-code | 50 |
41735345882 | from tkinter import *
from PIL import ImageTk, Image
import random
import numpy as np
root=Tk()
########SCORES####################
global scored7
scored7=None
global task1_score
global task2_score
global task3_score
global task4_score
global task5_score
global task6_score
global task_7_score
global... | allstemconsults/MemoryApp | logosCogni.py | logosCogni.py | py | 40,082 | python | en | code | 0 | github-code | 50 |
34405940578 | #Quesion 1
import numpy as np
class Question1():
def __init__(self):
self.cluster1 = np.empty((20,2)) #cluster variable
self.cluster2 = np.empty((20,2)) #cluster variable
self.cluster3 = np.empty((20,2)) #cluster variable
self.cluster4 = np.empty((20,2)) #cluster... | AceAtomz/ML-Clustering-Tut | Quesion1.py | Quesion1.py | py | 954 | python | es | code | 0 | github-code | 50 |
6991523771 | # encoding: UTF-8
from collections import defaultdict
import functools
from itertools import chain
from twisted.python import log
from twisted.internet import defer, reactor
from .. import command
from . import ircutil
"""
The auth module provides the Auth plugin, which handles authorization of irc
users. It identi... | brownan/abbott | abbott/plugins/auth.py | auth.py | py | 24,312 | python | en | code | 9 | github-code | 50 |
24117747636 | import math
# Press the variable dot tab tab will show you all the methods you can perform on itd
radius_str = input("Enter the radius of the circle: ")
radius_int = int(radius_str)
circumference = 2 * math.pi * radius_int
area = math.pi * (radius_int ** 2)
print("The circumference is: ", circumference, " and the ar... | SamAdesoba/Python-codes | deitel_exercises/class_works/area.py | area.py | py | 336 | python | en | code | 2 | github-code | 50 |
2978234686 | import os
class Recorder:
def __init__(self, snake, food):
"""
Constructor for the recorder, initializes it's variables
:param snake: the starting snake of the game - to be recorded
:param food: the starting food of the game - to be recorded
"""
self.snakes = [snake... | OrelAvraham/Final-Project-Snake | game_viewer/recorder.py | recorder.py | py | 1,716 | python | en | code | 0 | github-code | 50 |
33215429968 | import sys
n, m = map(int, sys.stdin.readline().rstrip().split())
parents = [i for i in range(n+1)]
def find(node):
if parents[node] == node: return node
else:
parents[node] = find(parents[node])
# 메모라이제이션
return parents[node]
def union(node1, node2):
root1, root2 = find(node1), f... | PJunyeong/Coding-Test | Baekjoon/1717_집합의 표현.py | 1717_집합의 표현.py | py | 773 | python | en | code | 0 | github-code | 50 |
39205271761 | try:
import numpy
except ImportError:
pass
else:
import unittest
from contracts import decorate, new_contract, ContractNotRespected
new_contract('rgb', 'array[HxWx3],H>0,W>0')
new_contract('rgba', 'array[HxWx4],H>0,W>0')
def blend_function(image1, image2, bug=False):
"""
... | AndreaCensi/contracts | src/contracts/testing/array_extended_test.py | array_extended_test.py | py | 2,648 | python | en | code | 392 | github-code | 50 |
41048378978 | from collections import defaultdict
def readFile(input):
infile = open(input, 'r').read().split('\n\n')
return infile
def parseFields(fields):
classes = defaultdict(list)
separated = fields.split('\n')
for field in separated:
name, ranges = field.split(': ')
separatedRanges = range... | ryanlberg/AdventOfCode2020 | day16/ticket_translation.py | ticket_translation.py | py | 3,643 | python | en | code | 0 | github-code | 50 |
2886527281 | from flask_wtf import FlaskForm
from govuk_frontend_wtf.wtforms_widgets import GovRadioInput, GovSelect, GovSubmitInput
from wtforms.fields import RadioField, SelectField, SubmitField
from wtforms.validators import AnyOf, InputRequired
class CookiesForm(FlaskForm):
functional = RadioField(
"Do you want to... | communitiesuk/funding-service-design-post-award-data-frontend | app/main/forms.py | forms.py | py | 1,307 | python | en | code | 0 | github-code | 50 |
28127292160 | # -*- coding: utf-8 -*-
"""
Name: Royston Marian Mascarenhas
USC email: rmascare@usc.edu
EE559 Final Project
Spring 2019
@author: royma
"""
from util import *
class Transform():
def __init__(self,data,labels,tdata,tlabels):
self.data = data
self.labels = labels
self.tdata = tdata
... | rmmasc/Course-Project---Prediction-of-Air-Pressure-System-Failure-at-Scania-Trucks | Transform.py | Transform.py | py | 3,849 | python | en | code | 1 | github-code | 50 |
26396772126 | class Solution:
def reverse(self, x: int) -> int:
ans_max = (2**31 - 1) // 10
ans_min = -2**31//10 + 1
b = abs(x)
ans = 0
while True:
if ans_min <= ans <= ans_max:
ans = b % 10 + ans * 10
else:
return 0
if b... | steve3ussr/PyCharmProject | LeetCode/LeetCode100/reverse_opt.py | reverse_opt.py | py | 511 | python | fr | code | 0 | github-code | 50 |
28569555137 |
# The solution has a time complexity of O(n), where n is the length of the input strings. This is because the solution iterates over the characters of both strings once to count their occurrences and then compares the counts.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# check if le... | aakashmanjrekar11/leetcode | 4. String/242. Valid Anagram.py | 242. Valid Anagram.py | py | 1,211 | python | en | code | 0 | github-code | 50 |
74529773914 | from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import base64
from PIL import Image
from io import BytesIO
import onnxruntime
app = Flask(__name__)
CORS(app)
ort_session = onnxruntime.InferenceSession("captcha_reader_model5.onnx")
@app.route('/', methods=["POST"])
def main_fu... | himanshukumargupta11012/AIMS_captcha_autofill | flask-api/app.py | app.py | py | 3,534 | python | en | code | 1 | github-code | 50 |
11155030454 | import matplotlib
import pandas as pd
import torch
from matplotlib import pyplot as plt
from pandas import read_csv
from torch import nn, optim
from torch.utils.data import DataLoader, TensorDataset
matplotlib.use('TkAgg')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def init_data(csv_path... | Steven-Zhl/YNU_ISE_Courses | MachineLearning/Experiments/Exp4/Code/neural_network.py | neural_network.py | py | 6,747 | python | en | code | 3 | github-code | 50 |
10627039940 | from create_node import Node
class LinkedList:
def __init__(self):
self.head = None
def push(self, name, value):
#if new list
newNode = Node(name, value)
if not self.head:
self.head = newNode
else:
#save head's current position
temp = ... | ChadMcintire/data_structures | ll.py | ll.py | py | 562 | python | en | code | 0 | github-code | 50 |
9639247764 | import tkinter as tk
root = tk.Tk()
COLS_COUNT = 4
STATES_COLORS = dict({
'gut': 'green',
'schlecht': 'red',
'repair': 'yellow'
})
def create_grid_from_list(data):
"""
Creates a multi-dimensional array from a flat array,
used for visualizing a grid
:param data: One dimensional array
... | OverDriveGain/yazan-project | GUI/start.py | start.py | py | 2,496 | python | en | code | 0 | github-code | 50 |
9919933010 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Adatok beolvasása
df = pd.read_csv('adatok2.csv')
# Első öt sor megjelenítése
print(df.head())
# Matplotlib használata egy egyszerű diagramhoz
plt.figure(figsize=(10, 6))
plt.plot(df['YEAR'], df['ESTIMATE'])
plt.title('Matplotli... | wodor1/python_data_vis | app.py | app.py | py | 968 | python | hu | code | 0 | github-code | 50 |
36484915030 | import sys
ans = sys.maxsize
#정수 arr의 최대 최소 구하기
#최소값구하기
arr= [162,5784,789321,75364757]
for i in arr:
if ans>i:
ans = i
print(ans)
#진법 변환
#from 10진법 to n진법
bin(100) #2진법
oct(100) #8진법
hex(100) #16진법
#출력결과 각각
#0b1100100
#0o144
#0x64
#n진법 to 10진법
int('0b1100100',2)
int('0o144',8)
int('0x64',16)
#백준27... | Mullan2020/python_practice | test_d3.py | test_d3.py | py | 1,003 | python | ko | code | 0 | github-code | 50 |
10101806680 | """Test setup for integration and functional tests.
When we import PloneTestCase and then call setupPloneSite(), all of
Plone's products are loaded, and a Plone site will be created. This
happens at module level, which makes it faster to run each test, but
slows down test runner startup.
"""
from Products.Five import... | collective/Products.PloneboardNotify | Products/PloneboardNotify/tests/base.py | base.py | py | 3,649 | python | en | code | 0 | github-code | 50 |
4806969389 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import VarianceThreshold
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from skl... | antreashp/DataMining_2020 | dim_reduction.py | dim_reduction.py | py | 2,762 | python | en | code | 0 | github-code | 50 |
10670426989 | import argparse
import numpy as np
from matplotlib import pyplot
from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('expt1.pdf')
pyplot.figure()
pyplot.clf()
parser = argparse.ArgumentParser()
parser.add_argument('-file', '--file', type=str, default='expt1.out', help='IP of server')
args = parser.pa... | martiansideofthemoon/cs747-assignments | assign4/plot.py | plot.py | py | 779 | python | en | code | 0 | github-code | 50 |
25367093919 | #!/usr/bin/env python3
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
import time
import math
import sys
#Functions Setup
def Convert(DesDist, diam): #Conversion from DesDist (Desired Distance) to number of rotations based on the physical diameter of the wheels
NumRot = DesDist/(math.pi*diam)
... | jjaram117/EV3-Lidar | RunEV3.py | RunEV3.py | py | 2,585 | python | en | code | 0 | github-code | 50 |
40806260266 | # python3
import itertools
n, m = map(int, input().split())
edges = [ list(map(int, input().split())) for i in range(m) ]
# This solution prints a simple satisfiable formula
# and passes about half of the tests.
# Change this function to solve the problem.
clauses = []
vertices = range(1,n+1)
paths = range(1,n+1)
s_p ... | AYUSHNSUT/Algorithms-Specialization-Coursera | Advanced-Algorithms-and-Complexity/w3/cleaning_apartment/cleaning_apartment.py | cleaning_apartment.py | py | 1,938 | python | en | code | 0 | github-code | 50 |
8426369810 | import sys
import abc
import numpy as np
from scipy.stats import geom, nbinom, poisson
import torch
from torch.autograd import Variable
from utils.helper import preprocess_gradients, get_step_loss
from utils.common import get_batch_functions, get_func_loss
from utils.helper import tensor_and, tensor_any, LessOrEqual
... | toologicbv/meta_learner | utils/batch_handler.py | batch_handler.py | py | 46,663 | python | en | code | 0 | github-code | 50 |
5922189513 | """A syllable written with IPA symbols."""
import enum
from typing import NamedTuple
class SyllableRegion(enum.Enum):
"""A region of a syllable."""
ONSET = enum.auto()
NUCLEUS = enum.auto()
CODA = enum.auto()
class SyllableAtom(NamedTuple):
"""The smallest block of a syllable."""
phoneme:... | AndrewHess/steno-tools | generator/syllable.py | syllable.py | py | 3,120 | python | en | code | 6 | github-code | 50 |
7523605773 | import pandas as pd
import csv
schedule_df = pd.read_csv(r"C:\Users\rober\OneDrive\Documents\Roberts Side Projects\May 22 output\2018-2019 actual_schedule_different_format.csv")
output_file_path = r"C:\Users\rober\OneDrive\Documents\Roberts Side Projects\May 22 output\back_to_back_output.csv"
def home_and_away_... | robertforderer/nba_schedule_site | count_back_to_backs.py | count_back_to_backs.py | py | 1,779 | python | en | code | 0 | github-code | 50 |
5696964000 | menosVinte = 0
maiorDeIdade = 0
homens = 0
while True:
print('-'*30)
print(' CADASTRE UMA PESSOA')
print('-'*30)
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: '))
while sexo not in 'MmFf':
sexo = str(input('Sexo [M/F]: '))
if idade > 18:
maiorDeIdade += 1
... | LeandroAlves05/python-cev | desafios/d069.py | d069.py | py | 817 | python | pt | code | 0 | github-code | 50 |
14605221762 | # -*- coding: utf-8 -*-
"""
"""
__version__ = "1.0"
__author__ = "si wen wei"
import io
import sys
import argparse
import pytest
from sevenautotest import settings
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
class TestRunner(object):
CMD_MODEL_ARG_NAME = '-cmdmode'
def __init__(s... | ssofnh/SevenPytest_first_linwei_2021-01-24 | SevenPytest/TestRunner.py | TestRunner.py | py | 1,424 | python | en | code | 0 | github-code | 50 |
28859937876 | '''module dedicated to the biject class'''
class Biject:
'''class representing a bijection'''
def __init__(self, start_dict=None):
'''start_dict can be provided to
fill the bijection with something
otherwise, an empty bijection is created'''
self._left = {}
self._right ... | ufosc/swampymud | swampymud/util/biject.py | biject.py | py | 2,237 | python | en | code | 21 | github-code | 50 |
40759311695 | from pyspark import SparkContext, SparkConf
from datetime import datetime
import numpy as np
import csv
import base64
from math import sqrt
def remove_header(csv):
csv_header = csv.first()
header = sc.parallelize([csv_header])
return csv.subtract(header)
conf = SparkConf().setAppName("YelpReviews").setMas... | mathiasnh/TDT4305-project | project_part1/task4.py | task4.py | py | 1,911 | python | en | code | 1 | github-code | 50 |
40125488520 | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.MCTunes2017.PythiaCP5Settings_cfi import *
generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter",
pythiaPylistVerbosity = cms.untracked.int32(0),
pythiaHepMCVerbosity = cm... | cms-sw/cmssw | Configuration/Generator/python/Psi2SToJPsiPiPi_14TeV_TuneCP5_pythia8_cfi.py | Psi2SToJPsiPiPi_14TeV_TuneCP5_pythia8_cfi.py | py | 4,371 | python | en | code | 985 | github-code | 50 |
7739158161 | from qgis.PyQt.QtWidgets import QTableWidgetItem
def add_row(table):
row = table.rowCount()
table.setRowCount(table.rowCount() + 1)
table.setItem(row, 0, QTableWidgetItem())
table.setItem(row, 1, QTableWidgetItem())
def remove_rows(table):
for item in table.selectedItems():
table.removeRow... | infogeo54/CartoGIS54-config | utils/server.py | server.py | py | 547 | python | en | code | 0 | github-code | 50 |
70679378075 |
from __future__ import print_function
# TODO : Write a test that does the split+merge to see if you get the identity map.
# TODO : implement a variant that doesn't do the exponential thing because it's hard to reconcile on the first layer
# Note that this splitting pattern will affect all the firsts from input to... | gyom/ift6266h15 | code/lasagne/split_maractus.py | split_maractus.py | py | 8,107 | python | en | code | 0 | github-code | 50 |
22578365660 | def zl(st):
# 第一步:统一符号 对字符串的处理,用replace()
st = st.replace("''",'"')
print(st)
# 第二步:去掉中括号 字符串截取 [:: ]
st = st[2:-2]
print(st)
# 第三步:变成list 字符串切片 .split() 新建一个list变量
st_li = st.split('" , "')
print(st_li)
# 第四步:取出后面的数字 循环遍历取出list里面的每个值,对这个值进行截取
st_dict = {}
for i i... | zhangli1229/gy-1906A | demo/day-04/practise.py | practise.py | py | 1,977 | python | zh | code | 0 | github-code | 50 |
16321492868 | from bs4 import BeautifulSoup
import time
import json
htmlTinkoff = 'tinkoff.html'
htmlSber = 'sberbank.html'
htmls = [htmlTinkoff, htmlSber]
res = []
def getData():
for i in range(0, len(htmls)):
print(htmls[i])
with open(htmls[i], 'r') as f:
contents = f.read()
soup = Beau... | injirez/bankNews | parserNewsHtml.py | parserNewsHtml.py | py | 1,065 | python | en | code | 0 | github-code | 50 |
15074024125 | import tables
import numpy
import numpy.lib.recfunctions
import multiprocessing as mp
import collections
import logging
import signal
import shutil
import time
import os
import sys
import functools
import json
from tqdm import tqdm
from queue import Empty
from .db import Database
from .models import ProteinEntry
from ... | DessimozLab/pyoma | pyoma/browser/compute_cache.py | compute_cache.py | py | 16,864 | python | en | code | 0 | github-code | 50 |
5940123823 | from transformers import Trainer, TrainingArguments
from transformers import T5Model, T5ForConditionalGeneration, AutoTokenizer
import wandb
from torch.utils.data import Dataset
from tokenizers import Tokenizer
from tokenizers import decoders
import pandas as pd
import torch
import json
wandb.init(project="tester", en... | haresh121/Multi-Lingual-Paraphraser | scripts/main_trainer.py | main_trainer.py | py | 1,835 | python | en | code | 0 | github-code | 50 |
30078284715 | import json
import requests
r = requests.get('http://localhost:3000')
data = r.json()
stringArray = []
for p in data:
sentence = "{0} is color: {1}".format(p["name"], p["color"])
stringArray.append(sentence)
print(sentence)
print(stringArray) | UndecidedTech/it3038c-scripts | Labs/Lab9/test.py | test.py | py | 258 | python | en | code | 1 | github-code | 50 |
71635261915 | import numpy as np
from pydub import AudioSegment
from PIL import Image
import requests
from pathlib import Path
import base64
import os
import random
from riffusion.spectrogram_converter import SpectrogramConverter
from riffusion.spectrogram_params import SpectrogramParams
from riffusion.spectrogram_image_converter i... | willsaliba/MusicMagicPlugin1.0 | AI_Model/scripts/generate.py | generate.py | py | 3,094 | python | en | code | 0 | github-code | 50 |
43659718119 | import sys
import pandas as pd
import geocoder as g
if __name__ == "__main__":
print("Caution! The number of requests is highly limited. Please, double-check the input arguments and write \"Okay, proceed\"")
proceed = input(": ")
if proceed == "Okay, proceed":
if len(sys.argv) <= 4:
pri... | DaniilOkrug/postomats-breach-department | ldt_model/collectors/apartments.py | apartments.py | py | 966 | python | en | code | 0 | github-code | 50 |
36559632589 | # doublingtime.py
# Name: Brittany Kyncl
# Date: 9.5.22
# Course: CSD205
# Mod 7 Assignment: Time it will take to double investment
# main program purpose message
print('\nWelcome, lets calculate how long it will take for your investment to double!\nFirst, please enter your information below...')
while True:
... | bkyncl/Python-Projects-CSD-200 | Investment Doublin/doublingtime.py | doublingtime.py | py | 1,219 | python | en | code | 0 | github-code | 50 |
31704470383 | import tkinter as tk
class Application(tk.Frame):
'''Sample tkinter application class'''
def __init__(self, master=None, title='<application>', **kwargs):
'''Create root window with frame, tune weight and resize'''
super().__init__(master, **kwargs)
self.master.title(title)
se... | alexey-kaz/pythonprac | 20210322_1/task1.py | task1.py | py | 3,780 | python | en | code | 0 | github-code | 50 |
38741574975 | #================================================
from functions import *
from manager.GManager import GManager
from manager.GCode import GCode
#================================================
class GCalculator(GManager):
#================================================
def __init__(self):
GManager.__... | gkesse/ReadyCode | app/python/server/code/src/manager/GCalculator.py | GCalculator.py | py | 1,641 | python | en | code | 0 | github-code | 50 |
28077901072 | # -*- coding: utf-8 -*-
"""
@Author 坦克手贝塔
@Date 2023/1/20 19:49
"""
from collections import deque
from typing import List
"""
病毒扩散得很快,现在你的任务是尽可能地通过安装防火墙来隔离病毒。
假设世界由 m x n 的二维矩阵 isInfected 组成, isInfected[i][j] == 0 表示该区域未感染病毒,而 isInfected[i][j] == 1 表示
该区域已感染病毒。可以在任意 2 个相邻单元之间的共享边界上安装一个防火墙(并且只有一个防火墙)。
每天晚上,病毒... | TankManBeta/LeetCode-Python | problem749_hard.py | problem749_hard.py | py | 6,811 | python | zh | code | 0 | github-code | 50 |
4019027960 | import re
def lexer(input_string):
keywords = ['if', 'else', 'while', 'for', 'int', 'float']
operators = ['+', '-', '*', '/', '=', '==', '<', '>', '<=', '>=']
symbols = ['(', ')', '{', '}', ',', ';']
token_patterns = [
(r'\b(' + '|'.join(keywords) + r')\b', 'PALABRA_CLAVE'),
(... | NexusAOD/Proyecto-Traductores-de-Lenguaje-II | Etapa del proyecto analizador léxico completo/Analizador Lexico.py | Analizador Lexico.py | py | 1,390 | python | es | code | 0 | github-code | 50 |
22925276009 | #python program to print all prime numbers in a given interval
lower = int(input("enter lower value:"))
upper = int(input("enter upper value:"))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num ... | aryngpt11/PythonProgramming | lab2python/primeno2.py | primeno2.py | py | 391 | python | en | code | 2 | github-code | 50 |
32732784672 | import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal, pyqtSlot
import re
import sys
from mytreeview import MySortFilterProxyModel, ArticleViewer, SourceArticleDBModel
from comparator import ComparatorTableModel, ComparatorViewer, Comparator... | lewisjiang/PaperMatrix | src/tabpagewidgets.py | tabpagewidgets.py | py | 17,897 | python | en | code | 4 | github-code | 50 |
25781649937 | # 斐波那契数列
# yield的用法
def fab2(max):
n,a,b=0,0,1
fab_list=[]
for i in range(max):
fab_list.append(b)
yield fab_list
a,b=b,a+b
for n in fab2(40):
print ( n )
| domclass/Pyhton_Exercise_Codes | 斐波那契数列.py | 斐波那契数列.py | py | 216 | python | en | code | 0 | github-code | 50 |
75303305435 | from grai_schemas.v1.source import SourceV1
from .base import IntegrationAdapter
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from grai_source_mssql.base import MsSQLIntegration
class MssqlAdapter(IntegrationAdapter):
def get_integration(self) -> "MsSQLIntegration":
from grai_source_mssql.base... | grai-io/grai-core | grai-server/app/connections/adapters/mssql.py | mssql.py | py | 1,087 | python | en | code | 241 | github-code | 50 |
6578498398 | from collections import deque
class Solution:
#Function to return list containing vertices in Topological order.
def topoSort(self, V, adj):
#Kahns algorithm
# Code here
q = deque()
indegree = [0] * V
for i in range(V):
for it in adj[i]:
i... | dhruvv173/Leetcode | Topological sort - GFG/topological-sort.py | topological-sort.py | py | 2,255 | python | en | code | 1 | github-code | 50 |
18952296654 | '''This module contains the following:
Controller
A class for Keras (Tensorflow backend) based OpenAI gym controllers.
Models
A class implementing and supplying Keras models to the Controller
class.
ActionTransformations
A container class for methods that transform the controller (Keras model)
outpu... | NiMlr/High-Dim-ES-RL | applications/control/gymcontrollers.py | gymcontrollers.py | py | 11,832 | python | en | code | 25 | github-code | 50 |
42597415594 | from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import google.auth
import io
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
from pathlib import Path
from dotenv import load_dotenv
SCOPES = ["https://www.googleapis.com/auth/drive"]
class CCGPDrive:
"... | cademirch/ccgp-data-wrangling | utils/gdrive.py | gdrive.py | py | 4,861 | python | en | code | 1 | github-code | 50 |
34242307761 | import pandas as pd
from os import listdir
from pandas import read_csv
from pickle import load
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pandas as pd
def label_encoder_data(data):
columns_to_encode = list(data.select_dtypes(include=['object']))
le = LabelEncoder()
for featu... | hurtishka/Machine-Learning-App | classification.py | classification.py | py | 2,081 | python | en | code | 0 | github-code | 50 |
15405978308 | import tensorflow as tf
from tensorflow.keras.layers import (
Input,
)
from tensorflow.keras.models import Model
from tensorflow.keras.applications import MobileNetV2
from indian_mobilnet_unet.mobileunet import decoder_block, loss_IoU
print("TF Version: ", tf.__version__)
def build_mobilenetv2_unet2(input_shape... | sugartechnology/foot-detector-tracker-public | mobileunet2.py | mobileunet2.py | py | 2,991 | python | en | code | 0 | github-code | 50 |
34467643685 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
class SoftmaxClassifier(object):
'''
Basic implementation of a softmax classifier.
Parameters
----------
random_state: int (default: 1337)
Defines the random state of numpy for a particular class instance.
n_clas... | mxmeier/smd_examples | examples/softmax_regression.py | softmax_regression.py | py | 9,594 | python | en | code | 0 | github-code | 50 |
12064032600 | from django import forms
from django.core.mail import send_mail
from django.core.validators import validate_email
from meetings.models import Template
class MultiEmailField(forms.Field):
def to_python(self, value):
"""Normalize data to a list of strings."""
# Return an empty list if no input was g... | timptner/farafmb | meetings/forms.py | forms.py | py | 1,857 | python | en | code | 0 | github-code | 50 |
6214229480 | #!/usr/bin/python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gtk
from os import path
from utils import uri_to_path
class CreateWindow(GObject.GObject):
__gsignals__ = {
'refresh': (GObject.SIGNAL_RUN_FIRST, None, ())
}
def __init__(self, window, file, uri):
... | luaVolk/nautilus-create-desktop-entry | src/windows/create.py | create.py | py | 2,924 | python | en | code | 0 | github-code | 50 |
22896711019 | import os
import json
import tornado
import memcache
import htmlmin
from config import config, base_path
from handler import Handler
ioloop = tornado.ioloop.IOLoop.instance()
class Application(object):
def __init__(self, urls):
urle = []
for url, method in urls:
handler = type(me... | deceq/t4p | t4p/application.py | application.py | py | 2,125 | python | en | code | 0 | github-code | 50 |
31974298904 | from django.db.models.signals import post_save, post_delete
from models import LogWorks
def my_callback(sender, **kwargs):
"""
This function add into model LogWorks
log works (creation/editing/deletion) with all models
"""
if sender._meta.object_name == 'LogWorks':
return None
... | myar/FortyTwoTestTask | apps/hello/signals.py | signals.py | py | 605 | python | en | code | null | github-code | 50 |
37957507223 | # 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
i... | ruizhang84/LeetCode-OJ | binaryTreePaths.py | binaryTreePaths.py | py | 751 | python | en | code | 0 | github-code | 50 |
26146602117 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^hello/$','mysite.vie... | jarod-chan/mysite | mysite/urls.py | urls.py | py | 416 | python | en | code | 0 | github-code | 50 |
6923251571 | import pandas
import time
import random
import csv
from google_search import Search
import os
from os import listdir
from os.path import isfile, join
from difflib import SequenceMatcher
# Paths for the data to be analyzed
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
ARTICLES_PATH = BASE_PATH + "/data/datas... | IliassAymaz/Propaganda-detector-political-polarization | date_annotation/analyze_data.py | analyze_data.py | py | 1,822 | python | en | code | 0 | github-code | 50 |
19847824669 | # def Nhap():
# n = int(input("Nhập n : "))
# m = int(input("Nhập m : "))
# a = []
# for i in range(n):
# k = [0]*m
# for j in range(m):
# k[j] = float (input('a[{}][{}] = '.format(i, j)))
# a.append(k)
# return a
#
# def write_file(a):
# f = open('D:/MATRIX.txt... | linhlukar/PYTHON | Python/TH4/41.py | 41.py | py | 1,478 | python | vi | code | 0 | github-code | 50 |
71425539355 | from flask import Flask, jsonify
from rpc_publisher import RpcClient
from notification_publisher import publish
import json
from apscheduler.schedulers.background import BackgroundScheduler
app = Flask(__name__)
scheduler = BackgroundScheduler()
scheduler.start()
@scheduler.scheduled_job('cron', day='*', hour='18', ... | cdchinmoy/CRON_RabbitMQ_Redis_Flask_Application | cron/app.py | app.py | py | 1,489 | python | en | code | 0 | github-code | 50 |
30413359151 | """ Environment Map Class for storing information about the simulation
environment. Contains lists of environmental features in the form of
(x, y) coordinate pairs. """
class EnvMap:
""" Container entity for environmental features. """
def __init__(self, width, height, air, surface, dead,
... | bcwarner/covid-modeling | image_mapping/envmap.py | envmap.py | py | 971 | python | en | code | 0 | github-code | 50 |
26478914076 | #!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 2019/5/22 11:44
@Author : Damon
@Email : kangming40@163.com
@File : test_playPlan.py
@Software : PyCharm
"""
import ast
import json
import time
import unittest
from ddt import ddt, data
from common.logger import logger
from common import do_excel
from ... | likangming/Ala_autotest | test_case/shop/test_shop.py | test_shop.py | py | 1,724 | python | en | code | 0 | github-code | 50 |
37683019587 | import numpy as np
import torch
from torch.utils.data import DataLoader
from solution.data import SCDataset
def run_epoch(epoch, train_loader, model, loss_fn, optimizer, device):
loss_acc = 0
for batch, (x, y) in enumerate(train_loader):
x = x.to(device=device)
y = y.to(device=device)
... | nikolaims/speech_command_detector | solution/learning.py | learning.py | py | 1,955 | python | en | code | 0 | github-code | 50 |
18669324787 | '''
from pywget import wget
Linux
source /opt/intel/openvino/bin/setupvars.sh
# Linux
cd /opt/intel/openvino/deployment_tools/tools/model_downloader
Model Downloader
python3 downloader.py --name face-detection-adas-0001 --precisions FP32 -o /home/workspace
python3 downloader.py --name gaze-estimation-adas-0002 -o /ho... | ET-Technologies/stepbystep | Openvino/download_model_openvino.py | download_model_openvino.py | py | 1,295 | python | en | code | 0 | github-code | 50 |
36064317392 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
origin=[0,0]
result=[]
newresult=[]
output=[]
for i in range(0, len(points)):
n=points[i][0]-origin[0]
m=points[i][1]-origin[1]
z=n**2 + m**2
... | nicole-mulela/Competitive-Programming | KClosestPointstoOrigin.py | KClosestPointstoOrigin.py | py | 829 | python | en | code | 0 | github-code | 50 |
33997388755 | import speech_recognition as sr
import pyaudio
def Listen():
r=sr.Recognizer()
with sr.Microphone() as source:
print("")
print("Listening... ")
r.pause_threshold=1
audio=r.listen(source)
try:
print("Recognizing..")
query=r.recognize_google(audio,language="e... | Ethancoder012/AI-Assistant | listen.py | listen.py | py | 486 | python | en | code | 0 | github-code | 50 |
8712881705 | from django.urls import path
from . import views
app_name = 'secMes'
urlpatterns = [
path('', views.home, name='home'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('signup/', views.signup, name='signup'),
path('sendMsg/', views.sendMsg, name='sendMsg'),
path('ms... | ROHIT318/secret-message | secMes/urls.py | urls.py | py | 684 | python | en | code | 0 | github-code | 50 |
16903369385 | import heapq
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
vals = [val for row in matrix for val in row]
heapq.heapify(vals)
for _ in range(k):
ans = heapq.heappop... | LYoung-Hub/Algorithm-Data-Structure | kthSmallestInMatrix.py | kthSmallestInMatrix.py | py | 346 | python | en | code | 0 | github-code | 50 |
73700328796 | '''
士兵许三多有一把AK47
士兵可以开火
枪能发射子弹
枪装填子弹
'''
# 枪类
class Gun:
def __init__(self, model):
self.model = model
self.bullte_count = 0
def add_bullte(self, count):
self.bullte_count += count
def shoot(self):
if self.bullte_count <= 0:
print('%s没有子弹了' %self.model)
... | zhaofangfang1991/algorithm | python_heima/code/面向对象4.py | 面向对象4.py | py | 990 | python | en | code | 0 | github-code | 50 |
941138109 | import matplotlib.pyplot as plt
import numpy as np
def main():
x = [-3,-2,-1,0,1,2,3,4]
y_jieyi = list(map(lambda a: jieyi(a, 0.5), x))
y_hinge = list(map(lambda a: hinge(a), x))
import pdb;pdb.set_trace()
plt.figure(1)
plt.plot(x,y_jieyi)
plt.plot(x,y_hinge)
plt.show()
def jie... | jiechenyi/elastic-svm | func_pic.py | func_pic.py | py | 529 | python | en | code | 0 | github-code | 50 |
8457312840 | import json
import sys
import time
from selenium import webdriver
from bs4 import BeautifulSoup as soup
import openpyxl
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
PATH = 'C:\Program Fil... | brose32/dfsprojections | MinutesScrape.py | MinutesScrape.py | py | 1,741 | python | en | code | 0 | github-code | 50 |
17913518180 | #!/usr/bin/python3
import functools
import pytest
from brownie.test import coverage
@pytest.fixture
def branch_results(coverage_mode, evmtester):
build = evmtester._build
yield functools.partial(_get_branch_results, build)
# organizes branch results based on if they evaluated True or False
def _get_branc... | eth-brownie/brownie | tests/test/coverage/conftest.py | conftest.py | py | 1,103 | python | en | code | 2,541 | github-code | 50 |
11600354569 | from flask import Flask, render_template, request, redirect, make_response
app = Flask(__name__)
@app.route('/')
def index():
if request.cookies.get("gamemode"):
resp = make_response(render_template('index.html'))
resp.set_cookie('gamemode', expires=0)
return resp
return render_templat... | evajanka/js-game | server.py | server.py | py | 709 | python | en | code | 0 | github-code | 50 |
28077871482 | # -*- coding: utf-8 -*-
"""
@Author 坦克手贝塔
@Date 2022/1/31 16:55
"""
"""
给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
输入:word1 = "... | TankManBeta/LeetCode-Python | problem72_hard.py | problem72_hard.py | py | 1,907 | python | zh | code | 0 | github-code | 50 |
22200119262 | """Helpers for writing rules under //pods."""
__all__ = [
'App',
'Mount',
'SystemdUnitGroup',
'Volume',
'define_pod',
'make_pod_journal_watcher_content',
'make_pod_oneshot_content',
'make_pod_service_content',
'make_timer_content',
]
import dataclasses
import itertools
import loggi... | clchiou/garage | shipyard2/shipyard2/rules/pods.py | pods.py | py | 8,964 | python | en | code | 3 | github-code | 50 |
43718505374 | # 定义函式
# 函式内部的程式码,若没有呼叫函式,就不会执行
def multiply(n1, n2):
# print (n1*n2)
return n1*n2
# 呼叫函式
value= multiply (3,4)+ multiply (10,12)
print (value)
# multiply (3,4)
# multiply (10,12)
# 程式的包装:同样的逻辑,可以重复利用
def calculate(max):
sum=0
for i in range(1, max+1):
sum = sum + i
print(sum)
calculate(10)... | jielingl11/PythonLearning | L9_FunctionBasic.py | L9_FunctionBasic.py | py | 432 | python | zh | code | 0 | github-code | 50 |
71231050075 | import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host,port))
while True:
print('Server : ', end='')
msg = s.recv(1024).decode('ascii')
print(msg)
if msg == 'bye':
print('The chat has ended')
s.send("bye".encode('ascii'))
break
... | azimsurani/Client-Server-Chat-Program | client.py | client.py | py | 435 | python | en | code | 1 | github-code | 50 |
36795515994 | #!/usr/bin/python3
import re
import sqlite3
import argparse
import queue
import time
import threading
from multiprocessing.pool import ThreadPool
import traceback
import sys
import math
# variable for collating the multi-line output of route planning commands
routeList = None
# our SQLite database
database = None
DB_... | dracode/tw2002-client | twparser.py | twparser.py | py | 18,984 | python | en | code | 1 | github-code | 50 |
14041830885 | # coding:utf-8
import re
iplist = []
portlist = []
isip=False;
datafile = file("ip.txt", "r")
for line in datafile.readlines():
line = line.strip('\n')
result=re.findall(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", line);
if not result:
if isip:... | cheerforthemaster/python | agentIP/Proxy_ip.py | Proxy_ip.py | py | 435 | python | en | code | 0 | github-code | 50 |
42568726628 | stringVal = "The quick Brow Fox"
countUpper = 0
countLower = 0
stringVal = stringVal.replace(" ", "")
for charVal in stringVal:
if str(charVal).islower():
countLower += 1
else:
countUpper += 1
print("No. of Upper case characters :", countUpper)
print("No. of Lower case characters :", count... | AshutoshPrograms/PythonTraining | CountUpperLower.py | CountUpperLower.py | py | 328 | python | en | code | 0 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.