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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
25248509640 | class Solution:
def largestNumber(self, nums: List[int]) -> str:
res = list(map(str, nums))
def compare(a, b):
if a + b > b + a:
return -1
else:
return 1
res.sort(key = functools.cmp_to_key(compare))
if res[0][0] == '0':
return '0'
return ''.join(res) | weitecklee/LeetCode | 0179-largest-number/0179-largest-number.py | 0179-largest-number.py | py | 307 | python | en | code | 0 | github-code | 1 |
43316919534 | # --------------------------------------------------------------
# File: Week-13-1/gui-10.py
# Project: Python-Class-Demo
# Author: Adrian Gould <Adrian.Gould@nmtafe.wa.edu.au>
# Created: 11/05/2021
# Purpose: Panels and layouts
# --------------------------------------------------------------
from breezypyth... | AdyGCode/Python-Basics-2021S1 | Week-13-1/gui-10.py | gui-10.py | py | 2,143 | python | en | code | 0 | github-code | 1 |
72178040354 | import os
import sys
from django.contrib.auth.models import User
from django.core.management import call_command
from django.test import Client, TestCase, TransactionTestCase, tag
from django.urls import reverse
from unicodex.models import *
client = Client()
emoji_data = {"name": "Unicorn", "codepoint": "1F984", "... | GoogleCloudPlatform/django-demo-app-unicodex | unicodex/tests.py | tests.py | py | 2,774 | python | en | code | 88 | github-code | 1 |
10640948750 | import os
import csv
# Set a CSV file path
csvpath = os.path.join( "Resources_PyPoll", "election_data.csv")
# Reading in the CSV file
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
next(csvreader, None) # Excludes headers
# Declaration of lists and variables
votes_ca... | skylar17/python--financial-and-election-result-analysis | PyPoll/main_PyPoll.py | main_PyPoll.py | py | 2,340 | python | en | code | 0 | github-code | 1 |
43208324315 | import dash
import plotly.express as px
import pandas as pd
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input
#Eksplorasi data dengan python
#________________________________________________
df = pd.read_csv("vgsales.csv")
#print(df[:5])
#... | takdirzd/Dash-Python | dashcoba.py | dashcoba.py | py | 2,002 | python | ms | code | 0 | github-code | 1 |
20517999286 | # import libraries
import sys; sys.path.append('/usr/local/python'); sys.path.append('/usr/local/python')
import numpy as np
import cv2
import os
import yaml
from openpose import pyopenpose as op
import time # for measuring elapsted time in YOLO computation
import argparse # check if image path is provided
#setup and... | westpoint-robotics/threat_detection | pose_detection/threat_pipeline_single_image.py | threat_pipeline_single_image.py | py | 12,802 | python | en | code | 4 | github-code | 1 |
74496271713 | # ================================
# Image Object Detection with YOLO
# ================================
# RUN WITH EXAMPLE COMMAND BELOW:
# python YOLO_img.py -i img_IO/work_table.jpg -o img_IO/work_table_processed.jpg -y yolov3 -d 10" into command prompt
import numpy as np
import argparse
import time
import cv2
im... | Jacklu0831/Real-Time-Object-Detection | 1_YOLO/YOLO_img.py | YOLO_img.py | py | 4,904 | python | en | code | 1 | github-code | 1 |
15128089502 | # O(nm) time | O(nm) space - where n and m are lengths of str1 and str2
def levenshteinDistance(str1, str2):
board = [[None for c in range(len(str2) + 1)] for r in range(len(str1) + 1)]
for r in range(len(str1) + 1):
for c in range(len(str2) + 1):
if r == 0:
board[r][c] = c
... | mmichalak-swe/Algo_Expert_Python | Levenshtein_Distance/attempt_1.py | attempt_1.py | py | 607 | python | en | code | 3 | github-code | 1 |
9162874628 | # 1. Planting Grapevines
# A vineyard owner is planting several new rows of grapevines, and needs to know how many grapevines to plant in each row.
# She has determined that after measuring the length of a future row,
# she can use the following formula to calculate the number of vines that will fit in the row,
# a... | superleggera-21/BI-Class | PythonAssignment1.py | PythonAssignment1.py | py | 4,485 | python | en | code | 0 | github-code | 1 |
26631833978 | # Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: 'Node') -> 'Node':
head = ... | RafaelHuang87/Leet-Code-Practice | 117.py | 117.py | py | 759 | python | en | code | 0 | github-code | 1 |
32655890013 | """User can have multiple SSH keys
Revision ID: 8eeae2cf5e84
Revises: 4fdf4258598e
Create Date: 2021-06-25 11:33:42.648848
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy import text
# revision identifiers, used by Alembic.
revision = '8eeae2cf5e84'
down_revision = '4fdf4258598e'
branch_labels = N... | SURFscz/SBS | server/migrations/versions/8eeae2cf5e84_user_can_have_multiple_ssh_keys.py | 8eeae2cf5e84_user_can_have_multiple_ssh_keys.py | py | 1,582 | python | en | code | 4 | github-code | 1 |
39430835150 | #Here we import all the necessary libraries, pandas, sklearn and numpy for data pre-processing, keras for neural networks
# and matplotlib in order to plot the obtained data
import pandas as pd
pd.set_option('display.float_format', lambda x: '%.4f' % x)
from keras.models import Sequential
from keras.layers import *
fr... | reinisirmejs/LVGMC | RNNAllInputs.py | RNNAllInputs.py | py | 7,988 | python | en | code | 0 | github-code | 1 |
25883535336 | import pdb
import pyasn1.codec.der.encoder
import pyasn1.type.univ
import base64
def pempriv(n, e, d, p, q):
dP = d % p
dQ = d % q
qInv = pow(q, p - 2, p)
template = '-----BEGIN RSA PRIVATE KEY-----\n{}-----END RSA PRIVATE KEY-----\n'
seq = pyasn1.type.univ.Sequence()
for x in [0, n, e, d, p... | team41434142/cctf-16 | mining-p-q/mining_p_q.py | mining_p_q.py | py | 2,018 | python | en | code | 1 | github-code | 1 |
20897765419 | # -*- coding: utf-8 -*-
import sys, collections, threading, os
from engineio import async_threading
#sys.path.append("/home/lakewik/PycharmProjects/storjguibeta/4/storj_gui_client")
print(os.path.dirname(os.path.realpath(__file__)))
import requests.packages.urllib3.packages.ordered_dict
from PyQt4 import QtCore, QtG... | lakewik/EasyStorj | main.py | main.py | py | 3,548 | python | en | code | 74 | github-code | 1 |
36261614433 | from setuptools import setup
with open("README.md") as file:
long_description = file.read()
setup(
include_package_data=True,
name='ginz',
version='1.1',
license="MIT",
description='Ginz is a command-line utility that simplifies the process of cloning multiple repositories from GitHub by allow... | happer64bit/ginz-cli | setup.py | setup.py | py | 726 | python | en | code | 0 | github-code | 1 |
8362739333 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#importing libraries
import requests
import pandas as pd
import numpy as np
import random
get_ipython().system('conda install -c conda-forge geopy --yes ')
from geopy.geocoders import Nominatim
from IPython.display import Image
from IPython.core.display import HTM... | Georgiakon/Assignments | Assignment4.py | Assignment4.py | py | 4,930 | python | en | code | 0 | github-code | 1 |
38132471774 | #!/usr/bin/python3
"""This module manages all the products of provisionspall"""
from api.v1.views import app_views
from flask import jsonify, request, make_response
from models.model import User, Store, Store_Address
from api.v1 import db
from provisionspall_web import UPLOAD_FOLDER, allowed_file
import os
from werkze... | dominic-source/ProvisionsPall | api/v1/views/store.py | store.py | py | 5,720 | python | en | code | 0 | github-code | 1 |
22379118825 | import pandas as pd
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
def constroi_url(url, query, url_pagina, tema):
url = url
query = query
url_pagina = url_pagina
tema_buscado = tema
link = url+url_pagina+query+tema_buscado
return link
def beatiful_s... | Insper-Data/Data_BCG_News | Scraping/aux_funcs/funcoes_scrap.py | funcoes_scrap.py | py | 2,501 | python | pt | code | 0 | github-code | 1 |
25427881611 | #!/usr/bin/env python
import os, sys
import pprint
from cgi import parse_qs, escape, FieldStorage
from stat import *
def application(env, start_response):
status_code = "500 ERROR"
output = ["Chart upload request received"]
# descerialize the post
post = FieldStorage(
fp=env['wsg... | hickey/helm_container | upload.py | upload.py | py | 1,562 | python | en | code | 0 | github-code | 1 |
33721331842 | import os, signal, sys
if __name__ == '__main__':
print("Père %d" % os.getpid())
p = os.fork()
if p == 0: # Fils
print("Fils %d" % os.getpid())
os.kill(os.getppid(), signal.SIGUSR1)
sys.exit(0)
# Suite père
print("Père: attente fin fils")
os.wait()
sys.exit(0)
| gando537/L2-Systeme-Python | TD/TD5/src_corr/Q1.1.py | Q1.1.py | py | 322 | python | fr | code | 0 | github-code | 1 |
16967247888 | from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pyflann import FLANN
from scipy.stats import gaussian_kde
from sklearn.neighbors import KernelDensity
import tool
class Coverage:
def __init__(self, model, layer_size_dict, hyper=None... | Yuanyuan-Yuan/NeuraL-Coverage | coverage.py | coverage.py | py | 34,661 | python | en | code | 243 | github-code | 1 |
40553740855 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import, print_function, unicode_literals
"""Utility functions to handle test chunking."... | spider055/browser | mozilla-release/taskcluster/taskgraph/util/chunking.py | chunking.py | py | 8,784 | python | en | code | 2 | github-code | 1 |
8139415628 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
strLength = len(s)
maxStr = ''
for i in range(strLength):
currentStr = ''
for j in range(i, strLength):
if currentStr.find(s[j]) >= 0:
break
... | MinecraftDawn/LeetCode | Medium/3. Longest Substring Without Repeating Characters .py | 3. Longest Substring Without Repeating Characters .py | py | 509 | python | en | code | 1 | github-code | 1 |
21925614419 | # @Author: Manuel Rodriguez <valle>
# @Date: 27-Jun-2018
# @Email: valle.mrv@gmail.com
# @Last modified by: valle
# @Last modified time: 29-Jun-2018
# @License: Apache license vesion 2.0
import websocket
import json
from datetime import datetime
from django.db.models import Q, Count, Sum, F
from django.db.models.... | vallemrv/tpv-php-to-django | django-valletpv/ventas/views/controlimpresion.py | controlimpresion.py | py | 8,703 | python | es | code | 0 | github-code | 1 |
16957308335 |
from openerp import models, fields, api
from datetime import datetime
from openerp.exceptions import Warning
class HrEmployeeCapacity(models.Model):
_name = "hr.employee.capacity"
_description = "hr_employee_capacity"
_order = "starting_date DESC, employee_id DESC"
_rec_name = 'employee_id'
@ap... | TinPlusIT05/tms | project/tms_modules/model/hr/hr_employee_capacity.py | hr_employee_capacity.py | py | 4,879 | python | en | code | 0 | github-code | 1 |
41100585495 | #
# 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 agreed to in writing, software
# distribut... | albertozeni/gemx | gemx/MLsuite_MLP/python/keras_rt.py | keras_rt.py | py | 2,431 | python | en | code | null | github-code | 1 |
21841207695 | import sys
input = sys.stdin.readline
def recur(cur, cnt):
global ans
if cur == N:
if sum(selected) == S and len(selected) != 0:
ans += 1
return
else:
selected.append(ls[cur])
recur(cur + 1, cnt + 1)
selected.pop()
recur(cur + 1, ... | pearl313/BOJ | 백준/Silver/1182. 부분수열의 합/부분수열의 합.py | 부분수열의 합.py | py | 447 | python | en | code | 0 | github-code | 1 |
6907742539 | import pyb
from pyb import Pin
from staccel import STAccel
import math
accel = STAccel()
click_threshold = 1.5
right_threshold = 0.4
left_threshold = -right_threshold
up_threshold = 0.4
down_threshold = -up_threshold
reverse_threshold = -0.4
def isReversed(z):
if z <= reverse_threshold:
return True
e... | mura-cin/mouse | main.py | main.py | py | 1,482 | python | en | code | 0 | github-code | 1 |
2590905862 | import FWCore.ParameterSet.Config as cms
# helper fuctions
from HLTrigger.Configuration.common import *
# add one customisation function per PR
# - put the PR number into the name of the function
# - add a short comment
# for example:
# CCCTF tuning
# def customiseFor12718(process):
# for pset in process._Proces... | palazz94/cmssw | HLTrigger/Configuration/python/customizeHLTforCMSSW.py | customizeHLTforCMSSW.py | py | 3,867 | python | en | code | null | github-code | 1 |
20644437454 | import numpy as np
import open3d as o3d
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOR_DIR = os.path.dirname(BASE_DIR)
sys.path.append(ROOR_DIR)
from utils import batch_transform, angle
from models import gather_points... | zhulf0804/ROPNet | src/models/TFMR.py | TFMR.py | py | 10,333 | python | en | code | 51 | github-code | 1 |
35938873518 | import numpy as np
import csv
import os
from my_kmeans import kmeans
from my_kmeans_script import ground_truth_plot
from my_kmeans_script import clustering_output_scatter
from my_kmeans_script import ObjectiveFunction_VS_Cost
#######################################################################
# File to be scanned... | deepak0004/Assignments | 2014036_HW_1/main.py | main.py | py | 2,675 | python | en | code | 0 | github-code | 1 |
36658639685 | import tensorflow as tf
from naivenmt.decoders.basic_decoder import BasicDecoder
class AttentionDecoder(BasicDecoder):
"""Standard attention decoder."""
def __init__(self,
params,
embedding,
sos_id,
eos_id,
scope="attention_decoder",
... | naivenlp/naivenmt-legacy | naivenmt/decoders/attention_decoder.py | attention_decoder.py | py | 3,662 | python | en | code | 9 | github-code | 1 |
71109526434 | import numbers
import datetime as dt
def get_sample_count(profileDict):
"""
Gets the number of samples taken from a dictionary representing data from an
Arm MAP file
Args:
profileDict (dict): Dictionary from which to obtain the count of samples
Returns:
The number of samples taken... | arm-hpc/allinea_json_analysis | MAP_JSON_Scripts/map_json_common.py | map_json_common.py | py | 19,968 | python | en | code | 3 | github-code | 1 |
33519038462 | import copy
from robotide.lib.robot.utils import SetterAwareType, py2to3, with_metaclass
@py2to3
class ModelObject(with_metaclass(SetterAwareType, object)):
__slots__ = []
def copy(self, **attributes):
"""Return shallow copy of this object.
:param attributes: Attributes to be set for the re... | robotframework/RIDE | src/robotide/lib/robot/model/modelobject.py | modelobject.py | py | 2,602 | python | en | code | 910 | github-code | 1 |
16163316998 | """ This file implements the pendulum system with two muscles attached """
from SystemParameters import PendulumParameters, MuscleParameters
from Muscle import Muscle
import numpy as np
import biolog
import pdb
from copy import deepcopy
from matplotlib import pyplot as plt
from biopack import integrate
from scipy.inte... | ffreundl/CoMoCo | Lab5/Python/System.py | System.py | py | 2,775 | python | en | code | 1 | github-code | 1 |
73507009634 |
class Solution:
def sol(self, x, y):
merged = x+y
sorted_array = self.quciksort(merged)
if len(sorted_array) % 2 == 0:
median = len(sorted_array) // 2
sum_val = (sorted_array[median] + sorted_array[median -1]) /2
return sum_val
else:
... | dipghoshraj/Algos | lrn/lrn/merge_median.py | merge_median.py | py | 829 | python | en | code | 0 | github-code | 1 |
14238769949 | import re
import os
import json
import boto3
def limpieza(ticket):
ticket = re.sub(r'[^A-Za-z0-9]+',' ',ticket)
tokens = ticket.split()
tokens = [token for token in tokens if token.isalpha()]
lista_nombres=[]
lista_apellidos=[]
for token in tokens:
if token in lista_nombres:... | sMendezMejia/proyecto_integrador | AWS/Lambdas/lambda_limpieza.py | lambda_limpieza.py | py | 1,039 | python | es | code | 0 | github-code | 1 |
27588376460 | import pandas as pd
df = pd.read_excel('C:/Users/taoma/Documents/行研/echarts/test1.xlsx')
print(df)
columns = df.columns
index = df.index
columns_count = len(columns)
index_count = len(index)
# print(columns_count, columns, index_count, index)
array = []
array_origin = []
for i in range(index_count):
for j in ... | myx99/Chart1 | echarts_DataPretreat.py | echarts_DataPretreat.py | py | 760 | python | en | code | 0 | github-code | 1 |
4490898762 | # Variational AutoEncoder
from tensorflow.keras.layers import Input, Dense, Lambda
from tensorflow.keras.models import Model
from tensorflow.keras import backend as K
from tensorflow.keras import metrics
from tensorflow.keras.datasets import mnist
import numpy as np
# Hyperparameter 설정
batch_size = 100
original_dim =... | Taerimmm/ML | project/team/GAN/00_vae.py | 00_vae.py | py | 2,879 | python | en | code | 3 | github-code | 1 |
26741822791 | # A library for streamlining ML processes
# by Matthew Mauer
# last editted 2020-05-10
'''
EDITS TO COME:
- more exception handling!!!
- more Grid Parameters in SupervisedLearner
- an UnsupervervisedLearner...
'''
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyp... | mrmauer/pipelines | Python/supervised_pipeline.py | supervised_pipeline.py | py | 13,284 | python | en | code | 0 | github-code | 1 |
10054278675 | # -*- coding: utf-8 -*-
# import sqlite3
# conn = sqlite3.connect("./test.db", check_same_thread=False)
# print(dir(conn))
# cur = conn.cursor() # db ni boshqarish uchun kursor
# sql = """CREATE TABLE students( \
# id INTEGER,
# name TEXT,
# age INTEGER,
# country TEXT
# );"""
# sql = """INSERT I... | Rashidov21/python-basic-tutorial | work_with_sql.py | work_with_sql.py | py | 1,315 | python | en | code | 31 | github-code | 1 |
14498320156 | fs = open('2020/day5/input.txt', 'r')
hId = 0
ids = []
while True:
line = fs.readline().strip('\n')
if not line:
break
row = line[:-3]
col = line[-3:]
bRow = row.replace('F', '0').replace('B', '1')
bCol = col.replace('L', '0').replace('R', '1')
r = int(bRow, 2)
c = int(bCol... | kwfk/advent-of-code | 2020/day5/sol.py | sol.py | py | 816 | python | en | code | 0 | github-code | 1 |
40003945126 | """ Entwickle ein Kino-System
Der Nutzer hat folgende Optionen:
1) Den ersten freien Einzelplatz ermitteln
- Gebe die Position des ersten freien Platzes aus
2) Den ersten freien Doppelplatz ermitteln
- Gebe die Position des ersten freien Doppelplatzes aus
3) Kino verlassen
"""
import os
# 0, 1,... | fiaeb23/Islamovic | Python/Aufgaben - Ubung/16_kino_Lösung.py | 16_kino_Lösung.py | py | 1,831 | python | de | code | 0 | github-code | 1 |
20513469419 | import sympy as sym
from sympy import symbols
from sympy.plotting import plot
f1 = "10-x" #x2 + x1 <= 10
f2 = "1+x" #x1 - x2 <= 1
f3 = "4" #x2 <= 4
Z1 = "16-x"
Z2 = "14-x"
Z3 = "13-x"
x = symbols('x')
plot(f1, f2, f3, Z1, Z2, Z3, (x, -1, 15))
# Sol: Z=9 x1=5 x2=4 Solución única
#La suma tiene que ser máximo 10, pero si... | AnaLopezP/InvestigacionOperativa | Ejercicio2/ejercicio2v1.py | ejercicio2v1.py | py | 374 | python | pt | code | 0 | github-code | 1 |
39510725458 | from collections import deque
# 방향 배열
direction = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
def BFS(start):
global max_value
# 덱생성
q = deque([start])
while q:
check = q.popleft()
# 방향배열 순회
for k in range(8):
ny = check[0] + direction[k][0]
... | choikeunyoung/algorithm | 백준/Silver 2/17086.py | 17086.py | py | 1,722 | python | ko | code | 1 | github-code | 1 |
6126633967 | # -*- coding: utf-8 -*-
# @Author: Yan_Daojiang
# @Date: 2019-09-21 22:26:43
# @Last Modified by: Yan_Daojiang
# @Last Modified time: 2019-09-21 22:27:03
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def ... | ChuckieWill/CodingPractice | CodingPractice-master/leetcode/algorithms/python/0083_RemoveDuplicatesfromSortedList.py | 0083_RemoveDuplicatesfromSortedList.py | py | 633 | python | en | code | 0 | github-code | 1 |
24845698363 | #!/usr/bin/env python
# WS server that sends messages at random intervals
import asyncio
import datetime
import random
import websockets
async def time(websocket, path):
print('Start... Loop előtt')
while True:
now = datetime.datetime.utcnow().isoformat() + 'Z'
print(now)
await websock... | cogitoergoread/em-simul | minta/ws_server_tine.py | ws_server_tine.py | py | 665 | python | en | code | 0 | github-code | 1 |
15654363718 | import gzip
import pickle
import tensorflow as tf
import numpy as np
# Translate a list of labels into an array of 0's and one 1.
# i.e.: 4 -> [0,0,0,0,1,0,0,0,0,0]
def one_hot(x, n):
"""
:param x: label (int)
:param n: number of bits
:return: one hot code
"""
if type(x) == list:
x = ... | adrianmesa93/practica2-fsi | nn_mnist.py | nn_mnist.py | py | 3,885 | python | en | code | 0 | github-code | 1 |
18187480219 | import unittest
import forest.drivers.unified_model
from forest import data
import forest.db.control
import forest.db.database
import forest.db.locate
def test_cut():
lines = [[[0, 4, 6], [20, 30, 40]]]
result = list(data.cut(lines, x=5))
assert list(result[0][0]) == [0, 4]
assert list(result[0][1]) =... | MetOffice/forest | test/test_data.py | test_data.py | py | 2,987 | python | en | code | 38 | github-code | 1 |
23212182418 | #!/usr/bin/env python3
"""
Smart wrapper around pmstat
Usage:
smart-pmstat JOBID [ADDITIONAL ARGUMENTS]
Where JOBID is the SLURM id of a running job.
The script will first recover the corresponding nodes using `squeue`, and will
then start a continuous monitoring of the corresponding nodes with `pmstat`.
Additional... | bwvdnbro/documentation | ScalingTests/smart_pmstat.py | smart_pmstat.py | py | 1,566 | python | en | code | 0 | github-code | 1 |
5007510575 | import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
import functions
# scope = ["https://spreadsheets.google.com/feeds",'https://https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
s... | mayankdaruka/Omelia | server/sheets.py | sheets.py | py | 1,345 | python | en | code | 2 | github-code | 1 |
19688355041 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node =... | naufalha/Praktikum-algoritma-dan-struktur-data | modul4/tugas5.py | tugas5.py | py | 1,005 | python | en | code | 0 | github-code | 1 |
75094103072 | import sys
input = sys.stdin.readline
def find(value):
if value == nodes[value]:
return value
parent = find(nodes[value])
nodes[value] = parent
return parent
def union(a, b):
a = find(a)
b = find(b)
if a == b:
return
if a < b:
nodes[b] = a
else:
... | Cardroid/AlgorithmStudy | AlgorithmStudy-vscode/Python/2202/10775.py | 10775.py | py | 605 | python | en | code | 0 | github-code | 1 |
23167920981 | import os
import tensorflow as tf
from scipy import misc
import numpy as np
import random
import sys
import io
def to_rgb(img):
if img.ndim < 3:
h, w = img.shape
ret = np.empty((h, w, 3), dtype=np.uint8)
ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img
return ret
else:
... | luckycallor/InsightFace-tensorflow | data/classificationDataTool.py | classificationDataTool.py | py | 4,902 | python | en | code | 246 | github-code | 1 |
29243912753 | def longestSubstringWithoutDuplication(string):
# Write your code here.
dic = {}
answer = [0,1]
start = 0
for i, char in enumerate(string):
if char in dic:
start = max(start,dic[char]+1)
if answer[1]-answer[0] < i+1-start:
answer = [start,i+1]
dic[char] = i
return string[answer[0] : answer[1]]
... | jinlee487/Algorithm | src/algoexpert/hard/LongestSubstringWithoutDuplication/solution.py | solution.py | py | 321 | python | en | code | 0 | github-code | 1 |
20597467269 | #!/usr/bin/env python3
#
# Project homepage: https://github.com/mwoolweaver
# Licence: <http://unlicense.org/>
# Created by Michael Woolweaver <m.woolweaver@icloud.com>
# ================================================================================
import os
from inspect import getframeinfo, stack
from sqlite3 impo... | mwoolweaver/listManager.py | lib/debug.py | debug.py | py | 3,700 | python | en | code | 1 | github-code | 1 |
6494429417 | def solution(s):
answer = []
s = s.replace('{', '')
tmp = s[:-1].split('}')
tu = []
for i in tmp:
r = i.replace(',', ' ')
r = r.lstrip()
arr = list(map(int, r.split()))
if arr:
tu.append(arr)
tu.sort(key = lambda x: len(x))
for i... | JoonseoKang/coding_test | 프로그래머스/lv2/64065. 튜플/튜플.py | 튜플.py | py | 428 | python | en | code | 0 | github-code | 1 |
959248874 | '''LiteMobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
from torch.nn import init
import torch.nn as nn
import math
import torch
import collections
import torch.nn.functional as F
class Block(nn.Module):
'''Depthwise co... | AlexanderParkin/CASIA-SURF_CeFA | rgb_track/models/architectures/lite_mobilenet.py | lite_mobilenet.py | py | 3,585 | python | en | code | 149 | github-code | 1 |
1090418482 | #Given a binary array, find the maximum number of consecutive 1s in this array.
class Solution:
def findMaxConsecutiveOnes(self,nums):
max_sum=nums[0]
counter=0
for i in range(len(nums)):
counter+=nums[i]
if(counter>max_sum):
max_sum=counter
... | m26unkwn/LeetcodeSolution | Array/MaxConsecutiveOnes.py | MaxConsecutiveOnes.py | py | 388 | python | en | code | 0 | github-code | 1 |
37845755339 | from customtkinter import *
import customtkinter
from tkPDFViewer import tkPDFViewer as pdf
app = customtkinter.CTk()
app.geometry('1360x720')
app.title("PDF Viewer")
customtkinter.set_default_color_theme("dark-blue")
customtkinter.set_appearance_mode('dark')
def newwin(s):
variable1 = pdf.ShowPdf()
... | bishalregmi105B/pdfviewer2 | main.py | main.py | py | 1,039 | python | en | code | 0 | github-code | 1 |
74363230754 | import base64
import json
import requests
class VisionUtils:
def __init__(self):
self.endpoint_url = 'https://vision.googleapis.com/v1/images:annotate'
self.api_key = 'AIzaSyCSqfhtZXwEy8JxJRtUYm31YWLC1aACUMg'
def __make_request(self, img_path, feature_type):
request_list = []
... | drimyus/GoogleCloudAPI | vision_utils.py | vision_utils.py | py | 2,022 | python | en | code | 1 | github-code | 1 |
31560817992 | """
Utility functions for RLE coding.
"""
import numpy as np
import pandas as pd
from utils.path import *
def rle_encode(mask):
""" Ref. https://www.kaggle.com/paulorzp/run-length-encode-and-decode
"""
pixels = mask.flatten('F')
pixels[0] = 0
pixels[-1] = 0
runs = np.where(pixels[1:] != pixel... | MengTianjian/MaskRCNN | dataset/rle.py | rle.py | py | 1,629 | python | en | code | 29 | github-code | 1 |
20041132401 | import sys
import matplotlib.pyplot as plt
import pickle
from scapy.all import rdpcap
from math import log
import numpy as np
broadcast_address = 'ff:ff:ff:ff:ff:ff'
def dict_add(dic, key):
if key in dic:
dic[key] += 1
else:
dic[key] = 1
def tipo(n):
if str(n) in types:
return typ... | alejandroFerrante/TP_Redes_Wiretapping | plot_entropia_s1.py | plot_entropia_s1.py | py | 1,461 | python | en | code | 0 | github-code | 1 |
32396192117 | import asyncio
from websockets import server
from threading import Thread
import logging
from datetime import datetime
import numpy as np
logging.basicConfig(filename='controlador.log',
# w -> sobrescreve o arquivo a cada log
# a -> não sobrescreve o arquivo
... | felipe-junior/ExclusaoMutuaDistribuida | app.py | app.py | py | 3,536 | python | pt | code | 1 | github-code | 1 |
20179427993 | import codecs
import atexit
from flask import Flask,render_template
import urllib3
import requests
import csv
from flask_crontab import Crontab
import pandas as pd
app = Flask(__name__)
cron=Crontab(app)
class LocationsData:
def __init__(self,state='NA',country='NA',latestCount=0,prevDayCount=0):
self.s... | ayush0407/Corona-Stats | app.py | app.py | py | 1,661 | python | en | code | 0 | github-code | 1 |
73872794272 | import json
import pandas as pd
import requests
from common.utils import *
from tushare_client.base import AbstractDataRetriever
from tushare_client.stock_calendar import StockCalendar
stock_index_map = {
's50': ('stock_index_s50', '000016'),
'h300': ('stock_index_h300', '000300'),
'z500': ('stock_index_... | xiekeng/tushare-client | tushare_client/stock_index.py | stock_index.py | py | 2,526 | python | en | code | 6 | github-code | 1 |
74152330592 | import praw
import sys
import pickle
import operator
import json
from datetime import datetime
AGENT='windows:blood_bender.reddit-data:v1.0.1 (by /u/blood_bender)'
reddit = praw.Reddit(user_agent=AGENT)
def main():
print("Warning: this takes a tooonnnnn of time, sorry")
if (len(sys.argv) != 2):
print("Must p... | jgr3go/reddit_ar | artopcommenters.py | artopcommenters.py | py | 2,168 | python | en | code | 3 | github-code | 1 |
4484391480 | import requests
import os
config_path = os.path.join(os.getcwd() + '\Config\\token.md')
def getHeaders():
'''获取headers'''
return { 'Parkingwang-Client-Source': 'ParkingWangAPIClientWeb',
'Authorization': getToken()}
def login(url,params):
try:
url = "http://dykttest.zsyky.cn:9999" +... | wfamzing/Test_API | config/gettoken.py | gettoken.py | py | 1,404 | python | en | code | 1 | github-code | 1 |
1829980180 | import ROOT
ROOT.gStyle.SetOptStat(1)
ROOT.gStyle.SetOptFit(1)
ROOT.gROOT.SetBatch(ROOT.kTRUE)
ROOT.gStyle.SetLabelFont(42,"xyz")
ROOT.gStyle.SetLabelSize(0.05,"xyz")
#ROOT.gStyle.SetTitleFont(42)
ROOT.gStyle.SetTitleFont(42,"xyz")
ROOT.gStyle.SetTitleFont(42,"t")
#ROOT.gStyle.SetTitleSize(0.05)
ROOT.gStyle.SetTitleSiz... | kdipetri/BNL_AC_LGADs | util/time_delay.py | time_delay.py | py | 5,753 | python | en | code | 0 | github-code | 1 |
19448146036 | from string import Template
import smtplib
import os
from os.path import basename
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 465
EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
EMAIL_PAS... | jakobOB/Automate-Email | main.py | main.py | py | 2,430 | python | en | code | 0 | github-code | 1 |
5928117169 | import math
from typing import Dict, Union
import numpy as np
import torch
from scipy.special import binom
from ocpmodels.common.typing import assert_is_instance
from ocpmodels.modules.scaling import ScaleFactor
class PolynomialEnvelope(torch.nn.Module):
"""
Polynomial envelope function that ensures a smoot... | Open-Catalyst-Project/ocp | ocpmodels/models/gemnet_oc/layers/radial_basis.py | radial_basis.py | py | 7,484 | python | en | code | 518 | github-code | 1 |
16779028414 | import numpy as np
import cv2
import math
def calculate_hs_histogram(img, bin_size):
height, width, _ = img.shape
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
max_h = 179
max_s = 255
hs_hist = np.zeros((math.ceil((max_h+1)/bin_size), math.ceil((max_s+1)/bin_size)))
for i in range(he... | Tano-Coppoletta/Computer_vision | color_segmentation/main.py | main.py | py | 1,453 | python | en | code | 0 | github-code | 1 |
32198374896 | from django.urls import path
from response.slack import views
urlpatterns = [
path("slash_command", views.slash_command, name="slash_command"),
path("action", views.action, name="action"),
path("event", views.event, name="event"),
path("cron_minute", views.cron_minute, name="cron_minute"),
path("c... | monzo/response | response/slack/urls.py | urls.py | py | 372 | python | en | code | 1,487 | github-code | 1 |
33715367939 | import argparse
import datetime
import random
import sys
from pathlib import Path
from pprint import pprint
from typing import Dict
from tqdm import tqdm
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from cal_angle import *
base_dir = str(Path(__file__).resolve().parent.parent)
sys.p... | w4ngzI/MARL-olympic-running | olympic_running_algo&reward/rl_trainer/main_reward.py | main_reward.py | py | 11,843 | python | en | code | 0 | github-code | 1 |
26208484646 | from defconAppKit.windows.baseWindow import BaseWindowController
from vanilla import EditText, FloatingWindow, CheckBox, Button, HelpButton, RadioGroup, HorizontalLine
from mojo.UI import MultiLineView, SelectGlyph, Message, setScriptingMenuNamingShortKeyForPath, createModifier, HelpWindow
import pathManager.pathSettin... | louis-cho/StemFont-Plugin | rbWindow/editWindow.py | editWindow.py | py | 9,483 | python | en | code | 0 | github-code | 1 |
37775263983 | import string
def solution():
data = input()
result = []
sum = 0;
for x in data:
if x.isalpha():
result.append(x)
else:
sum += int(x)
result.sort()
if sum != 0:
result.append(str(sum))
return ''.join(result)
print(solution())
# 생각 못... | sangeon-ahn/thisiscodingtest | 구현/문자열 재정렬/문자열 재정렬-연습.py | 문자열 재정렬-연습.py | py | 448 | python | ko | code | 0 | github-code | 1 |
28933061902 | import os
import random
import user_statistic
def show_location(u_stat):
is_busy = True
u_bet = 0
u_score = 0
while is_busy:
os.system("cls")
user_statistic.show_stat(u_stat)
print("А вот и казино - место где проигрывают жизнь, зато вкусная еда).")
print("1 — Сделать ставку")
print("2 — Уй... | Anonymkus/T_RPG-rus- | casino.py | casino.py | py | 1,894 | python | ru | code | 0 | github-code | 1 |
28097719889 | import logging
import pathlib
from unittest.mock import patch
from rest_framework.test import APITestCase
logger = logging.getLogger(__name__)
class TestTemplates(APITestCase):
def test_when_get_then_response(self):
ret_value = pathlib.Path(
"src/human_lambdas/templates_handler/tests/t.json"... | Human-Lambdas/human-lambdas | src/human_lambdas/templates_handler/tests/test_templates.py | test_templates.py | py | 1,465 | python | en | code | 32 | github-code | 1 |
15657667031 | def menor_numero(x, y):
"""
Função calcula o menor número entre os informados pelo usuário
:param x: primeiro número informado pelo usuário
:param y: segundo número informado pelo usuário
:return: o menor entre os dois números informados pelo usuário
"""
if x > y:
menor = f'O menor n... | PlinioCE/infinitypythononline | aula05_python_ativ01_menor_num.py | aula05_python_ativ01_menor_num.py | py | 638 | python | pt | code | 0 | github-code | 1 |
7594669007 | from keras.models import load_model
from keras.preprocessing.image import img_to_array
import cv2
import numpy as np
import webbrowser
from tkinter import *
face_classifier = cv2.CascadeClassifier(
r'D:\EMOTION BASED MUSIC PLAYER\haarcascade_frontalface_default.xml')
classifier = load_model(r'D:\EMOTION... | anuragx18/EMOTION-BASED-MUSIC-PLAYER | main(1).py | main(1).py | py | 2,631 | python | en | code | 0 | github-code | 1 |
18253543936 | from django.core.cache import cache
from config.settings import CACHE_ENABLED
from blog.models import Post
def get_cached_posts():
"""Получить список постов из кеша, если необходимо, то из БД."""
if CACHE_ENABLED:
key = 'blog_posts_list'
queryset = cache.get(key)
if queryset is None:... | RomanBogdanov5111/Coursework_6 | blog/services.py | services.py | py | 540 | python | ru | code | 0 | github-code | 1 |
32958159929 | import sys
import signal
import socket
import gym
import json
import numpy as np
import cv2
import tqdm
from itertools import product
from time import sleep
from utils.virtual_controller import VirtualKeyboard
from utils.img import ImageCapture
from utils.utils import changeWindowName, kill_process, kill_steam, run_ga... | Seladus/The-RL-of-Isaac | isaac_env.py | isaac_env.py | py | 10,300 | python | en | code | 0 | github-code | 1 |
13857045676 | import asyncio
from discord.ext import commands
from utils.moduleloader import get_module_loader
class MemeBot:
bot: commands.Bot
command_prefix: str
async def loadModules(self, bot):
#def __ainit__(self, config: dict, bot: commands.Bot):
print( await self.moduleLoader.reload_all_cogs())
... | JeppeLovstad/Discord-Meme-Delivery-Bot | memebot.py | memebot.py | py | 1,980 | python | en | code | 0 | github-code | 1 |
12990749826 | import os
import sys
import unittest
_PARENT_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
_PYLINT_PATH = os.path.join(_PARENT_DIR, 'oppia_tools', 'pylint-1.7.1')
sys.path.insert(0, _PYLINT_PATH)
# Since these module needs to be imported after adding Pylint path,
# we need to disable isort for the below... | shouri007/oppia | scripts/custom_lint_checks_test.py | custom_lint_checks_test.py | py | 2,269 | python | en | code | null | github-code | 1 |
31055770316 | '''Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar
descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou não.'''
from random import randint
from time import sleep
computador = randint(0,5) # Faz o... | milenamoraes/CEV-Python | Exercícios/ex028.py | ex028.py | py | 1,014 | python | pt | code | 0 | github-code | 1 |
39329629280 | def bubblesort(a):
n=len(a)
for x in range(0,n):
swap=False
for y in range(0,n-1-x):
if a[y]>a[y+1]:
a[y],a[y+1]=a[y+1],a[y]
swap=True
if swap==False:
break
return a
l=[]
b=int(i... | barkhaaroraa/python-codes | bubbleloop.py | bubbleloop.py | py | 420 | python | en | code | 1 | github-code | 1 |
33300825490 | #!/usr/bin/python2
import time
import BaseHTTPServer
import os
import random
import string
import requests
from urlparse import parse_qs, urlparse
HOST_NAME = '0.0.0.0'
PORT_NUMBER = 9999
# A variável MP3_DIR será construida tendo como base o diretório HOME do usuário + Music/Campainha
# (e.g: /home/usuario/Music/C... | EstevesDouglas/UNICAMP-FEEC-IA369Z | scr/servidor.py | servidor.py | py | 2,434 | python | en | code | 0 | github-code | 1 |
8410126543 | import matplotlib.pyplot as plt
def f(x):
return (7*x) % 1729
x = []
y = []
for i in range(0, 2000):
x.append(i)
y.append(f(i))
plt.plot(x, y)
plt.show()
| hermanholmoy/TDT4109 | Oppgaver/plotmod.py | plotmod.py | py | 173 | python | en | code | 0 | github-code | 1 |
39122442888 | import frappe
from frappe.model.document import Document
class CropSampling(Document):
def on_trash(self):
doc = frappe.db.get_list("Cane Master") #fields=["plantation_status", "name","form_number"
for a in doc:
eachdoc= frappe.get_doc("Cane Master",a.name)
if self.id == eachdoc.name:
eachdoc.plantatio... | Pradip2113/sugar_mill-29-04-23 | sugar_mill/sugar_mill/doctype/crop_sampling/crop_sampling.py | crop_sampling.py | py | 365 | python | en | code | 0 | github-code | 1 |
26064580319 | import argparse
import os
import random
import shutil
import time
import warnings
from tqdm import tqdm
from typing import Callable, Optional
import faiss
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from torch.utils.data im... | UCDvision/low-budget-al | sampler.py | sampler.py | py | 15,075 | python | en | code | 13 | github-code | 1 |
74419552994 | import os
import pickle
import argparse
import numpy as np
import torch
import utils
import attacks
class TargetedIndexedDataset():
def __init__(self, dataset, classes):
self.dataset = dataset
self.classes = classes
def __getitem__(self, idx):
x, y, ii = self.dataset[idx]
y +... | fshp971/robust-unlearnable-examples | generate_tap.py | generate_tap.py | py | 5,798 | python | en | code | 35 | github-code | 1 |
6189652417 | # -*- coding: utf-8 -*-
### Import libraries
import numpy as np
"""### Env Setup"""
# env variables
environment = [
[-10, 1, 0],
[0, -10, 10]
]
grid_rows = len(environment)
grid_cols = len(environment[0])
num_actions = 4
# Define the reward matrix
rewards = np.full((grid_rows, grid_cols), environment)
# D... | j3rryl/q_learning | main.py | main.py | py | 3,269 | python | en | code | 0 | github-code | 1 |
36850304791 | """ 此文件用于解析rsl.out.0000文件 """
from datetime import datetime
# import matplotlib.pyplot as plt
class rslOutParser:
""" 此类用于解析rsl.out.0000文件 """
def __init__(self, rslFilePath):
self.rslFilePath = rslFilePath
self.dataLines = []
def tryParse(self):
""" a """
print('aaaaa')
... | the-1000th-summer/wrfViewerDjango | wrfViewer/app1/parser.py | parser.py | py | 3,362 | python | en | code | 1 | github-code | 1 |
70199258594 | # -*- coding: utf-8 -*-
import json
import logging
import traceback
from datetime import datetime, timedelta
import odoo
from odoo import _, models, fields, api
from odoo.api import Environment
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT as DATETIME_FORMAT
from ..api import AsyncDB
_logger = logging.getLo... | oejia/task_queue | models/task_task.py | task_task.py | py | 3,503 | python | en | code | 15 | github-code | 1 |
40517490417 | import bpy, mathutils
class RenderManager():
files = None
camera = None
dummyObject = None
zAxis = (0,0,1)
blenderFilesDir = "."
radius = 6378137
def __init__(self, **kwargs):
for k in kwargs:
setattr(self, k, kwargs[k])
def getBoundingBox(self):
# perform context.scene.update(), otherwise o.mat... | vvoovv/blender-2.5dmaps | render_manager.py | render_manager.py | py | 808 | python | en | code | 10 | github-code | 1 |
16557727585 | # 10 그래프 이론 - 커리큘럼
# Solved Date: 22.07.17.
import sys
from collections import deque
import heapq
read = sys.stdin.readline
# 위상정렬하고, 더 오래 걸리는 값을 항상 저장해줌
def book_topological_sort(indegrees, graph, costs):
answer = [cost for cost in costs]
queue = deque()
for node, indegree in enumerate(indegrees):
... | imn00133/algorithm | ItIsCodingTest/chap10/04.curriculum.py | 04.curriculum.py | py | 2,018 | python | en | code | 0 | github-code | 1 |
30731289244 | import numpy as np
import math
from numpy.linalg import multi_dot
from numpy import linalg
def EKF(Pos_inp,Acc_inp,x_hat_inp,P_inp,dt_inp):
A = np.zeros([2,2])
A[0][1] = 1.0
B = np.zeros([2,1])
B[1][0] = 1.0
C = np.zeros([1,2])
C[0][0] = 1.0
q = 10.0
r = 10.0
Q = multi_dot([q,np.eye(2)])
R = r #multi_dot... | alzizou/Quad_UWB | Files_On_RPi/Archive/EKF.py | EKF.py | py | 1,133 | python | en | code | 1 | github-code | 1 |
12616729540 | saldo_disponivel = 0
total_sacado = 0
saques_efetuados = 0
total_depositado = 0
while True:
operacao = input("""Bem vindo ao LuizBank, as operações disponíveis estão listadas abaixo:
1 - Depósito
2 - Saque
3 - Extrato
4 - Sair do programa\n""")
if operacao == '1':
valor_deposito = floa... | Luizifpb/Lab-Sistema-Bancario-Dio | sistema-bancario.py | sistema-bancario.py | py | 1,763 | python | pt | code | 0 | github-code | 1 |
41595865599 | import sys
import hashlib
import re
def remove_last_line_from_string(s):
return s[:s.rfind('\n')]
# Function to calculate the SHA-256 hash of a string
def calculate_sha256(data):
return hashlib.sha256(data.encode()).hexdigest()
# Function to calculate the SHA-256 hash of a file
def calculate_sha256_file(file... | itsNko/SGSSI23-Lab06-HashCriptografico2 | SGSSI23_Lab05_A3_Functions.py | SGSSI23_Lab05_A3_Functions.py | py | 1,805 | python | en | code | 0 | github-code | 1 |
4719615839 | """Building a ReLU with two hidden layer Model for MNIST in TensorFlow."""
from datetime import datetime
import tensorflow as tf
from neologger import Logger
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
PROJ_NAME = f"MNIST-CNN"
LOG_PATH = "/tmp/tf" + f"/{PROJ_NAME}"
# Init logger
lo... | jneo8/tf_sample | mnist/cnn.py | cnn.py | py | 6,388 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.