seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
32102291979 | class Solution:
# 1. 暴力
def longestPalindrome1(self, s: str) -> str:
if len(s) <= 1:
return s
count = 0
res = ""
for i in range(len(s)):
for j in range(i + 1, len(s)):
if s[i:j + 1] == s[i:j + 1][::-1]:
if j - i > count:... | Eleanoryuyuyu/LeetCode | python/Dynamic Programming/5. Longest Palindromic Substring.py | 5. Longest Palindromic Substring.py | py | 1,759 | python | en | code | 3 | github-code | 6 |
19399859119 | # 目标和
# https://leetcode-cn.com/leetbook/read/queue-stack/ga4o2/
from typing import List
import common.arrayCommon as Array
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
print(nums)
s = sum(nums)
if s < S:
return 0
n = len(nums)
... | Yigang0622/LeetCode | findTargetSumWays.py | findTargetSumWays.py | py | 1,411 | python | en | code | 1 | github-code | 6 |
6176179693 | import os, time, sys
import matplotlib.pyplot as plt
import itertools
import pickle
import imageio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import torchv... | hqyu/DL_GAN | GAN.py | GAN.py | py | 4,169 | python | en | code | 0 | github-code | 6 |
33805613545 | from typing import Optional, Dict
from fastapi import WebSocket, APIRouter, Cookie, status, Depends
from ws_chat_py.engines.person_engine import PersonEngine
ws_router = APIRouter()
@ws_router.websocket("/ws")
async def ws_chat_handler(websocket: WebSocket):
await websocket.accept()
authorized = check_cha... | backcrawler/ws_chat_py | ws_chat_py/handlers/ws_handlers.py | ws_handlers.py | py | 925 | python | en | code | 0 | github-code | 6 |
39399750947 | import logging
import os
import argparse
import json
from itertools import chain
from typing import Dict, List, Tuple, Any
from functools import partial
import s3fs
from hydra import compose, initialize, core
from omegaconf import OmegaConf
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Nopep8
import... | YangWu1227/python-for-machine-learning | neural_network/projects/cnn_insect_classification_sagemaker/src/baseline_entry.py | baseline_entry.py | py | 12,600 | python | en | code | 0 | github-code | 6 |
39172128523 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import json, make_response
from flask_restplus import Api, Resource
from http import HTTPStatus
from .v1.api import api as api_v1
from .v2.api import api as api_v2
from .health import api as api_health
api = Api()
api.add_namespace(api_v1)
api.add_names... | shalomb/terrestrial | apis/__init__.py | __init__.py | py | 1,122 | python | en | code | 0 | github-code | 6 |
71923388669 | #!/usr/bin/env python
import os, argparse
parser = argparse.ArgumentParser()
parser.add_argument("-u", required=True, dest="usuario", help="Usuario de PostgreSQL")
parser.add_argument("-H", default="localhost", dest="host", help="IP del equipo remoto")
parser.add_argument("-p", default="5432", dest="puerto", h... | francisjgarcia/ASGBD-2018-19 | scripts/python/backup.py | backup.py | py | 761 | python | es | code | 0 | github-code | 6 |
15790344554 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 23:15:17 2020
@author: malrawi
"""
import dicttoxml
import ruamel.yaml # https://pypi.org/project/ruamel.yaml/
import json
def read_yaml_as_dict(fname):
"""
A function used to read the ddoif dictionary in yaml format and return it as a python dictio... | morawi/ddoif | ddoif_utils.py | ddoif_utils.py | py | 3,011 | python | en | code | 3 | github-code | 6 |
70485999229 | # Create a program which you will enter the amount of money you have, it will also ask for the price of an apple.
# Display the maximum number of apples that you can buy and the remaining money that you will have.
def getInput(dataIn):
"""takes an input and returns a value depending on the parameter requested
... | MagnoClarence/Assignment3 | Program3.py | Program3.py | py | 1,119 | python | en | code | 1 | github-code | 6 |
29778121292 | import requests, os, json
from bs4 import BeautifulSoup as BS
from random import choice
_BASE_PATH = os.path.dirname(__file__)
_DATA_FILE = os.path.join(_BASE_PATH,'data.txt')
_ACTORS_FILE = os.path.join(_BASE_PATH,'actors.txt')
_DIRECTORS_FILE = os.path.join(_BASE_PATH,'directors.txt')
_YEARS_FILE ... | asav13/PRLA-Verk5 | part2/y_u_so_stupid.py | y_u_so_stupid.py | py | 6,583 | python | en | code | 0 | github-code | 6 |
17689175212 | def read_measurements(filename):
f = open(filename, 'r')
return list(map(lambda s: int(s.strip()), f.readlines()))
def main():
measurements = read_measurements("01 - Depth Measurements.txt")
print("Increased measurements: " + str(num_increased(measurements)))
print("Increased sliding windows: " + s... | aacohn84/Advent_of_Code_2021 | 01 - Sonar Sweep.py | 01 - Sonar Sweep.py | py | 970 | python | en | code | 0 | github-code | 6 |
10233665355 | from __future__ import annotations
import datetime
from typing import Optional, Union, TYPE_CHECKING, List, Dict
from . import enums
from .utils import parse_timestamp
from .user import BitLeaderboardUser, PartialUser, User
if TYPE_CHECKING:
from .http import TwitchHTTP
__all__ = (
"BitsLeaderboard",
"Cli... | PythonistaGuild/TwitchIO | twitchio/models.py | models.py | py | 69,250 | python | en | code | 714 | github-code | 6 |
25441389301 | # -*- coding: utf-8 -*-
from PIL import Image,ImageFont,ImageDraw
import json
import cover
import time
from io import BytesIO
def paste_with_a(base_img_, img_, pos):
if 4 == len(img_.split()):
r,g,b,a = img_.split()
base_img_.paste(img_, pos,mask=a)
else:
base_img_.paste(img_, pos)
... | kakinumaCN/maimai_DX_rating_image | main.py | main.py | py | 9,086 | python | en | code | 0 | github-code | 6 |
7713955808 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask
myApp = Flask(__name__)
@myApp.route('/')
def bonjour():
message = 'Bonjour, je suis Ramy \n'
return message
if __name__ == '__main__':
myApp.run(host='0.0.0.0', port=8080)
| RMDHMN/pythonFlash_testing | app.py | app.py | py | 254 | python | en | code | 1 | github-code | 6 |
25009445303 | import datetime
import re
from random import shuffle
from collections import defaultdict
from django.utils.translation import (
activate,
get_language_info,
get_language,
)
from django import http
from django.shortcuts import render
from django.core.cache import cache
from django.conf import settings
from ... | peterbe/kl2 | kl/search/views.py | views.py | py | 24,492 | python | en | code | 0 | github-code | 6 |
8765296577 | """ Faça um script que leia dois números e retorne como resultado a soma deles. Faça um script que leia algo
pelo teclado e mostra na tela o seu tipo de dado.
"""
numero1 = int(input("Digite o Numero 1 : "))
numero2 = int(input("Digite o Numero 2 : "))
soma = numero1+numero2
print(f"A soma é {soma}")
x = in... | AndreDosSantosMaier/Liguagem_Programacao | Lista de Exercicios/Exer-1.py | Exer-1.py | py | 388 | python | pt | code | 0 | github-code | 6 |
16471277711 | """
A row measuring seven units in length has red blocks with a minimum length of
three units placed on it, such that any two red blocks (which are allowed to be
different lengths) are separated by at least one black square. There are
exactly seventeen ways of doing this.
How many ways can a row measuring fifty units ... | bsamseth/project-euler | 114/114.py | 114.py | py | 1,999 | python | en | code | 0 | github-code | 6 |
36065552368 |
# url to update the member in flight club datasheet:-- https://replit.com/@ShivamKumar28/Shivam-Flight-Club
#This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements.
from data_manager import DataManager
from flight_search import FlightSearc... | Shivam29k/Python_Projects | flight_deals_alert/main.py | main.py | py | 1,106 | python | en | code | 1 | github-code | 6 |
6589740252 | import pickle
from flask import Flask, request, render_template, jsonify, send_file
from elasticsearch import Elasticsearch
from transformers import pipeline, AutoTokenizer, AutoModelForQuestionAnswering, AutoModel
import spacy
import json
import time
from pymongo import MongoClient
import os
from sklearn.linear_model ... | szegedai/SHunQA | backend/flask_service.py | flask_service.py | py | 8,073 | python | en | code | 0 | github-code | 6 |
75066660668 | import scipy.io as sio
import numpy as np
class ReadFiles(object):
def __init__(self):
spamData = sio.loadmat('../data/spam_data.mat', struct_as_record=False)
self.header = spamData['__header__']
self.version = spamData['__version__']
self.names = spamData['names']
pTrain... | Skalwalker/SpamRecognition | scripts/readfiles.py | readfiles.py | py | 1,011 | python | en | code | 0 | github-code | 6 |
1307107485 | import functools
import os
import re
from importlib import import_module
from typing import Callable, Pattern
import yaml
from livelossplot.outputs import NeptuneLogger
def unpack_config(func: Callable) -> Callable:
"""Load parameters from a config file and inject it to function keyword arguments"""
@functoo... | Bartolo1024/RLCarRacing | utils.py | utils.py | py | 2,684 | python | en | code | 0 | github-code | 6 |
23518058201 | def rev(a):
a=str(a)
a=a[::-1]
return int(a)
def palin(p):
k=str(p)
if p== int(k[::-1]):
return True
a=int(input())
p=0
f= True
while f:
a=a+rev(a)
if palin(a):
break
print(a)
| jayavishnumadhiri/Python-Practised-programs | range.py | range.py | py | 252 | python | en | code | 2 | github-code | 6 |
43991242007 | l=[]
for i in range(10):
num=int(input("DIGITE UM VALOR"))
l.append(num)
valor=int(input("DIGITE O VALOR Q DESEJA PESQUISAR NA LISTA"))
for i in l:
if i==valor:
print("Elemento encontrado!")
break
else:
print("Elemento não encontrado.")
| marcoAureliosm/Lista-de-vetores-python | questão07.py | questão07.py | py | 283 | python | pt | code | 0 | github-code | 6 |
35917887576 | from os import confstr
from string import Template
ISL = " { data: { id: 'ISL', label: 'ISL', fedType: 'ISL', innerLevel: 3 }, group: 'nodes' },\n"
CARTEL_TEMPLATE = " { data: { id: '$id', label: '$label', fedType: '$fed_type', innerLevel: $inner_level }, group: 'nodes' },\n"
SYSTEM_TEMPLATE = " ... | lbelella/f2gm | python/GalaxyPresenter.py | GalaxyPresenter.py | py | 4,562 | python | en | code | 0 | github-code | 6 |
1512983994 | """
This file contains helper functions for the project
"""
# import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from math import atan2, degrees
import urllib.request
from PIL import Image
# functions
def get_tracking_data():
"""
Funct... | emekaamadi/Milestone-1-NFL-Project | src/functions.py | functions.py | py | 5,059 | python | en | code | 0 | github-code | 6 |
2739075186 | """Given the html files for each of the language families,
build language tree for each and write them in json object
"""
from bs4 import BeautifulSoup
from tqdm import tqdm
import json
import sys
import os
link = 'html/indo-european.html'
link = 'html/mongolic.html'
link = 'html/bororoan.html'
def get_list(html):... | ialsina/LangTree | parse_html.py | parse_html.py | py | 3,111 | python | en | code | 0 | github-code | 6 |
26111772381 | #practice for Intro ML - Gradient Descent : Feb 25th 2020
import numpy as np
y = np.zeros((2, 3, 4))
#print(y)
a = np.array([[1,2,3], [4,5,6]])
b = np.array([[2,3,4], [9,7,8]])
#print(np.hstack((a,b)))
c = np.array([[2,3,4], [5,6,7]])
d = np.array([[3,4,5], [4,5,3]])
#print(np.hstack((c,d)))
#print([i for i in range(... | kyrajeep/Practice | numpy_prac.py | numpy_prac.py | py | 851 | python | en | code | 0 | github-code | 6 |
5254327339 | # -*- coding: utf-8 -*-
"""
Utility functions
@authors: Álvaro Ramírez Cardona (alramirezca@unal.edu.co)
Vanessa Robledo Delgado (vanessa.robledo@udea.edu.co)
"""
from os import path
import xarray as xr
import numpy as np
import pandas as pd
from scipy import ndimage
import geopandas as gpd
from datetime im... | alramirezca/ATRACKCS | atrackcs/utils/funcs.py | funcs.py | py | 11,183 | python | en | code | 7 | github-code | 6 |
22400134597 | from PyQt5 import QtWidgets
from diz3_2 import * # импорт нашего сгенерированного файла
import sys
from BD import Orm
class Dialog2(QtWidgets.QDialog):
def __init__(self, id):
self.id = id
super(Dialog2, self).__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui... | Vorlogg/BD | dialog2.py | dialog2.py | py | 1,367 | python | en | code | 0 | github-code | 6 |
6932656070 |
import gc
import json
import numpy as np
import optuna
import pandas as pd
import sys
import warnings
import xgboost
from glob import glob
from sklearn.model_selection import KFold, StratifiedKFold
from tqdm import tqdm
from utils import FEATS_EXCLUDED, loadpkl, line_notify, to_json
#===============================... | MitsuruFujiwara/KDD-Cup-2019 | src/804_optimize_xgb_optuna.py | 804_optimize_xgb_optuna.py | py | 3,421 | python | en | code | 3 | github-code | 6 |
7796643764 | import numpy as np
import pickle
from engine.sim_functions import calc_local_zodiacal_minimum,Spectrograph
from engine.planet_retrieval import Planet,Star
from engine.main_computer import compute
from itertools import chain
from multiprocessing import Pool
import json
import sys
dR_scale = float(sys.argv[1]) #Reflecta... | JonahHansen/LifeTechSim | error_sim.py | error_sim.py | py | 5,550 | python | en | code | 0 | github-code | 6 |
2087116071 | from bson import ObjectId
import Usuario.search as buscarUsuario
import Produto.search as buscarProduto
from datetime import date
def inserir_compra(mydb):
compra = mydb.Compra
usuario = mydb.Usuario
lista_produtos = []
usuarios = buscarUsuario.userByID(mydb,ObjectId)
data_atual = date.today()
... | Raniel-Santos/Banco-NoSQL-Python_MongoDB | Compra/insertCompra.py | insertCompra.py | py | 1,170 | python | pt | code | 1 | github-code | 6 |
30217613419 | #!/usr/bin/python3
import os
import re
import string
import sys
import subprocess
import time
import traceback
from queue import Queue
from queue import Empty
import random
from threading import Thread
macro_var_regex = re.compile("%(?P<var>[-0-9]+)%")
macro_rand_uint_regex = re.compile("%RANDUINT\((?P<length>[-0-9A-Z... | WiscADSL/uFS | cfs/test/client/testCfsVersusVfs.py | testCfsVersusVfs.py | py | 11,058 | python | en | code | 26 | github-code | 6 |
10414874563 | import itertools
import operator
import types
from typing import Any, List, Optional, Tuple, Type
import torch
from executorch.exir.dialects.edge._ops import EdgeOpOverload
from executorch.exir.error import ExportError, ExportErrorType
from executorch.exir.lowered_backend_module import LoweredBackendModule
from execut... | pytorch/executorch | exir/verification/verifier.py | verifier.py | py | 7,890 | python | en | code | 479 | github-code | 6 |
36413248388 | # ---------------
# ParamCopy - Substance 3D Designer plugin
# (c) 2019-2022 Eyosido Software SARL
# ---------------
import os, weakref
from functools import partial
from PySide2.QtCore import QObject
from PySide2.QtWidgets import QToolBar
import sd
from sd.context import Context
from sd.api.sdapplication import SDA... | eyosido/ParamCopy | src/paramcopy/pcui/pctoolbar.py | pctoolbar.py | py | 2,317 | python | en | code | 9 | github-code | 6 |
7066069240 | import sys,os,subprocess,string,re
from threading import Timer
import time,socket,json
from os import path
base_dir = path.dirname(path.abspath(sys.path[0]))
print(base_dir)
sys.path.append(base_dir)
class HfsSetup():
def __init__(self,hver='',plants='',adict={}):
self._run_code = True
self._plan... | kRayvison/Pycharm_python36 | new_render_data/input/p/script/CG/Houdini/function/old/HoudiniMain/HoudiniAppSet.py | HoudiniAppSet.py | py | 5,487 | python | en | code | 1 | github-code | 6 |
195263286 | from django.db import models
from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, Subscriber
from core.models.plcorebase import StrippedCharField
import os
from django.db import models, transaction
from django.forms.models import model_to_dict
from django... | xmaruto/mcord | xos/services/ceilometer/models.py | models.py | py | 10,893 | python | en | code | 0 | github-code | 6 |
35212077312 | import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((TCP_IP,TCP_PORT))
message ="Player"
s.send(message.encode())
while 1:
data = s.recv(1024).decode()
print("received:",data)
s.send(input().encode())
| OleHalvor/HS | client.py | client.py | py | 294 | python | en | code | 0 | github-code | 6 |
11068770479 | from django.http import *
from forms import UploadForm
from django import template
from django.template.loader import get_template
from django.template import Context, RequestContext
from django.utils.decorators import method_decorator
from django.shortcuts import render_to_response
from django.contrib.auth import auth... | hughsons/saltwaterfish | admin/views.py | views.py | py | 28,274 | python | en | code | 1 | github-code | 6 |
7520101007 | """
Created on Wed Feb 24 12:34:17 2021
@author: Narmin Ghaffari Laleh
"""
##############################################################################
from dataGenerator.dataSetGenerator_ClamMil import Generic_MIL_Dataset
import utils.utils as utils
from extractFeatures import ExtractFeatures
from utils.core_util... | KatherLab/HIA | CLAM_MIL_Training.py | CLAM_MIL_Training.py | py | 12,138 | python | en | code | 76 | github-code | 6 |
34200144967 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm as cm
import matplotlib.lines as mlines
df= pd.read_csv('/home/nishchay/Documents/Arcon/Day7/winequality-red.csv')
X1=df.iloc[:,11].values
Y1=df.iloc[:,0].values
Y2=df.iloc[:,1].values
fig = plt.figure()
ax1 = fig.add_sub... | nagrawal63/Neural-Networks | Day7/plot.py | plot.py | py | 2,190 | python | en | code | 0 | github-code | 6 |
11353423523 | '''
https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3630/
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = righ... | jihoonyou/problem-solving | leetcode/binary-tree-right-side-view.py | binary-tree-right-side-view.py | py | 799 | python | en | code | 0 | github-code | 6 |
29929387988 | #!/bin/python
import xml.etree.ElementTree as ET
import sys
tree = ET.parse(sys.argv[1])
root = tree.getroot()
'''
print root.find('deckname').text
main = root.find('./zone')
for c in main.findall(path='card'):
print c.get('number')+c.get('name')
'''
for c in root[2]:
print(c.get('number') + ' ' + c.get('name'... | nikisix/dex | xml_parser.py | xml_parser.py | py | 398 | python | en | code | 0 | github-code | 6 |
57215059 | import pytest
import numpy as np
import os
from netZooPy import dragon
def test_dragon():
#1. test1
print('Start Dragon run ...')
n = 1000
p1 = 500
p2 = 100
X1, X2, Theta, _ = dragon.simulate_dragon_data(eta11=0.005, eta12=0.005, eta22=0.05,
p1=100, p... | netZoo/netZooPy | tests/test_dragon.py | test_dragon.py | py | 5,525 | python | en | code | 71 | github-code | 6 |
20338445920 | import numpy as np
def Poisson1D( v, L ):
# Solve 1-d Poisson equation:
# d^u / dx^2 = v for 0 <= x <= L
# using spectral method
J = len(v)
# Fourier transform source term
v_tilde = np.fft.fft(v)
# vector of wave numbers
k = (2*np.pi/L)*np.concatenate((np.linspace(0,J/2-1,J/2),np.... | snytav/Kaa | Poisson1D.py | Poisson1D.py | py | 615 | python | en | code | 0 | github-code | 6 |
8385121611 | from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import optparse
import collections
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)
import sumolib # noqa
else:
sys.exit("please declare environ... | ngctnnnn/DRL_Traffic-Signal-Control | sumo-rl/sumo/tools/tlsCycleAdaptation.py | tlsCycleAdaptation.py | py | 19,264 | python | en | code | 17 | github-code | 6 |
20793244215 | import numpy as np
from jax import numpy as jnp
from flax import struct
from flax.traverse_util import flatten_dict, unflatten_dict
from flax.core import Scope, lift, freeze, unfreeze
from commplax import comm, xcomm, xop, adaptive_filter as af
from commplax.util import wrapped_partial as wpartial
from typing import An... | remifan/commplax | commplax/module/core.py | core.py | py | 10,764 | python | en | code | 49 | github-code | 6 |
25786118251 | import select
import socket
EOL1 = b'\n\n'
EOL2 = b'\r\n'
response = b'HTTP/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:01:01 GMT\r\n'
response += b'Content-Type: text/plain\r\nContent-Length: 13\r\n\r\n'
response += b'Hello, world!'
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(... | gaufung/CodeBase | Python-Standard-Library/Network/epoll/example3.py | example3.py | py | 475 | python | en | code | 0 | github-code | 6 |
38736630905 | import datetime
import logging
import matplotlib.pyplot as plt
import numpy as np
import numpy.typing as npt
from backend.data.measurements import MeasurementArray, Measurements
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def xyz2blh(x, y, z):
"""_summary_
Angle returned will be in ra... | GeoscienceAustralia/ginan | scripts/GinanEDA/backend/data/position.py | position.py | py | 3,039 | python | en | code | 165 | github-code | 6 |
73933198267 | from .common import * # NOQA
import pytest
project_detail = {"project": None, "namespace": None, "cluster": None,
"project2": None, "namespace2": None, "cluster2": None}
user_token = {"user_c1_p1_owner": {"user": None, "token": None},
"user_c1_p1_member": {"user": None, "token": None},... | jim02468/rancher | tests/validation/tests/v3_api/test_app.py | test_app.py | py | 13,408 | python | en | code | 0 | github-code | 6 |
28339823949 | def secondElem(a):
return a[1]
def alphasort(a):
a.sort(key=secondElem,reverse=True)
for i in range(len(a)-1):
if a[i][1] == a[i+1][1] and a[i][0] > a[i+1][0]:
a[i],a[i+1] = a[i+1],a[i]
return a
from collections import Counter
name = list(Counter(input()).items())
name = al... | t3chcrazy/Hackerrank | company-logo.py | company-logo.py | py | 389 | python | en | code | 0 | github-code | 6 |
42636165267 |
import netCDF4
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
import cartopy.crs as ccrs
import matplotlib.colors as colors
# Land cover
lc = netCDF4.Dataset("../data/LandCover_half.nc")
lc.set_auto_mask(True)
lc.variables
land_cover = lc["Land Cover"][:]
# fix landco... | bikempastine/Isoprene_PModel | exploration/anomaly_mapping.py | anomaly_mapping.py | py | 7,350 | python | en | code | 0 | github-code | 6 |
4643605876 | import os
import shutil
import pickle
import glob
import cv2
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
from cam import create_dataset, Camera
def save_data(path, data):
with open(path, 'wb') as handle:
pickle.dump(data, handle)
print("Saved")
def... | EvilFis/MultiCamVision | test_method.py | test_method.py | py | 16,755 | python | en | code | 0 | github-code | 6 |
11370340934 | import torch
import torchvision
import random
import torch.nn as nn
import torch
from torch import tanh
import torch.nn.functional as F
# custom weights initialization
def weights_init_1st(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.15)
#... | ssainz/reinforcement_learning_algorithms | fleet_simulator/Models.py | Models.py | py | 3,261 | python | en | code | 0 | github-code | 6 |
6766919720 | from sys import exit
def get_hurt(message, severity):
"""
A simple function that determines damage of mc based on severity level.
Parameters:
(String) message: message explaining how the mc got hurt.
(int) severity: the severity level of how bad the damage inflicted is.
"""
if severity == 1... | ShawnT21/The_Box | dungeon_adventure.py | dungeon_adventure.py | py | 2,496 | python | en | code | 0 | github-code | 6 |
18405188691 | import numpy as np
from astropy import table
from glob import glob
import pandas as pd
from scipy.stats import binned_statistic
def get_outlier_fraction(tbl, suffix='', bins=20):
diff = np.array(np.abs(tbl['z_est'] - tbl['z']) > 0.15 * (1 + tbl['z']),
dtype=float)
stat = binned_statistic(t... | minzastro/semiphore_public | utils/stats.py | stats.py | py | 3,666 | python | en | code | 0 | github-code | 6 |
158477486 | import datetime as dt
from rest_framework import status
from rest_framework.exceptions import NotAuthenticated, PermissionDenied
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from bumblebee.core.exceptions import (
Miss... | sthasam2/bumblebee-backend | bumblebee/feeds/api/views/feed_views.py | feed_views.py | py | 4,226 | python | en | code | 0 | github-code | 6 |
25081332800 | # If this is the name of a readable file, the Python commands in that file are
# executed before the first prompt is displayed in interactive mode.
# https://docs.python.org/3/using/cmdline.html#envvar-PYTHONSTARTUP
#
# Sample code which supports concurrent interactive sessions, by only
# appending the new history is t... | mvshmakov/dotfiles | python/.config/python/pythonstartup.py | pythonstartup.py | py | 1,442 | python | en | code | 3 | github-code | 6 |
37822719553 | """Contains the MetaCurriculum class."""
import os
from unitytrainers.curriculum import Curriculum
from unitytrainers.exception import MetaCurriculumError
import logging
logger = logging.getLogger('unitytrainers')
class MetaCurriculum(object):
"""A MetaCurriculum holds curriculums. Each curriculum is associate... | Sohojoe/ActiveRagdollAssaultCourse | python/unitytrainers/meta_curriculum.py | meta_curriculum.py | py | 3,968 | python | en | code | 37 | github-code | 6 |
16635792661 | from pulp_2to3_migration.app.plugin.api import (
is_different_relative_url,
Pulp2to3Importer,
Pulp2to3Distributor,
)
from pulp_rpm.app.models import RpmRemote, RpmPublication, RpmDistribution
from pulp_rpm.app.tasks.publishing import publish
from urllib.parse import urlparse, urlunparse
class RpmImporte... | pulp/pulp-2to3-migration | pulp_2to3_migration/app/plugin/rpm/repository.py | repository.py | py | 6,151 | python | en | code | 3 | github-code | 6 |
71474225467 | import csv
positives = 0
negatives = 0
i = 1
tn = 0
tp = 0
fn = 0
fp = 0
flag = 0
flag2 = 0
totalRawCount = 0
flag5 = 0
linelist = []
#################################################################################################################
######################################################################... | ayandeephazra/Natural_Language_Processing_Research | open this for text file manipulation/manualClassifier.py | manualClassifier.py | py | 3,821 | python | en | code | 2 | github-code | 6 |
74632636347 | # -*- coding: utf-8 -*-
"""
Sihoo Celery Worker 模块
@author: AZLisme
@email: helloazl@icloud.com
"""
from celery import Celery
celery_app = Celery('SihooWorker')
def configure(app):
celery_app.config_from_object('sihoo.settings.celery-setting')
celery_app.config_from_envvar('SIHOO_CELERY_SETTINGS', silen... | AZLisme/sihoo | sihoo/tasks/__init__.py | __init__.py | py | 370 | python | en | code | 4 | github-code | 6 |
22758733002 | # (C) StackState 2020
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
@pytest.fixture(scope='session')
def sts_environment():
return {
'type': 'csv',
'health_file': '/home/static_health/health.csv',
'delimiter': ',',
'collection_inter... | StackVista/stackstate-agent-integrations | static_health/tests/conftest.py | conftest.py | py | 560 | python | en | code | 1 | github-code | 6 |
21142626845 | import numpy as np
import tensorflow as tf
from eventgen import CEvent
from nets.net import Net
from nets.utils import get_trainable_vars, prep_data_cells
class PPOSinghNet(Net):
def __init__(self, pre_conv=False, double_net=False, *args, **kwargs):
"""
Afterstate value net
"""
se... | tsoernes/dca | dca/nets/singh_ppo.py | singh_ppo.py | py | 8,129 | python | en | code | 14 | github-code | 6 |
41705912087 | import newspaper
# Declare the url
url = "https://ktechhub.com/tutorials/completely-deploy-your-laravel-application-on-ubuntu-linux-server-60a51098a8bf2"
#Extract web content
url = newspaper.Article(url="%s" % (url), language='en')
url.download()
url.parse()
# Display scraped data
print(url.text)
| Kalkulus1/python_codes | scrape_any_web_article.py | scrape_any_web_article.py | py | 302 | python | en | code | 0 | github-code | 6 |
19691344827 | """Define custom dataset class extending the Pytorch Dataset class"""
import os
from typing import Dict, List, Tuple
import numpy as np
import pandas as pd
from PIL import Image
import torch
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as tvt
from utils.utils import Params
class S... | karanrampal/sketches | src/model/data_loader.py | data_loader.py | py | 3,585 | python | en | code | 0 | github-code | 6 |
11898315364 | #!/usr/bin/env python3
""" basic Flask app """
from flask import Flask, render_template, request, g
from flask_babel import Babel
import pytz
app = Flask(__name__)
babel = Babel(app)
users = {
1: {"name": "Balou", "locale": "fr", "timezone": "Europe/Paris"},
2: {"name": "Beyonce", "locale": "en", "timezone":... | jeanpierreba/holbertonschool-web_back_end | 0x0A-i18n/7-app.py | 7-app.py | py | 2,161 | python | en | code | 0 | github-code | 6 |
19399695029 | from typing import List
import copy
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = {}
s = set()
for i, each in enumerate(equations):
nominator = each[0]
denominator = each[1]
... | Yigang0622/LeetCode | calcEquation.py | calcEquation.py | py | 2,160 | python | en | code | 1 | github-code | 6 |
19981905247 | import json
import os
from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher.filters import Text
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext
from aiogram.utils.markdown impor... | Baradys/scrappers | scrappers/sbermarket/sbermarket_bot.py | sbermarket_bot.py | py | 4,624 | python | en | code | 0 | github-code | 6 |
5414745490 | #!flask/bin/python
"""Alternative version of the ToDo RESTful server implemented using the
Flask-RESTful extension."""
from flask import Flask, jsonify, abort, make_response, make_response, request, current_app
from flask.ext.restful import Api, Resource, reqparse, fields, marshal
from flask.ext.httpauth import HTTPB... | Spanarchie/BaseAPI | BaseAPI.py | BaseAPI.py | py | 6,714 | python | en | code | 0 | github-code | 6 |
44685313114 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 20:18:24 2019
@author: YAO
"""
import pandas as pd
r = pd.read_csv("data_test.csv")
r1=pd.DataFrame(r)
#delete other columns
r2=r1.drop(['trajectory_id', 'time_entry', 'time_exit','vmax','vmin','vmean','x_entry','y_entry','x_exit','y_exit'], axi... | zy-yao/EY-NextWave-Data-Science-Challenge-2019 | Data_Preparation_1.py | Data_Preparation_1.py | py | 778 | python | en | code | 0 | github-code | 6 |
19501436322 | """
This file (test_youbit.py) contains unit tests for the encode.py and decode.py files.
"""
from pathlib import Path
import os
import time
from yt_dlp.utils import DownloadError
from tests.conftest import uploads
from youbit import Encoder, download_and_decode
from youbit.settings import Settings, Browser
from youb... | mevimo/youbit | tests/unit/test_youbit.py | test_youbit.py | py | 1,245 | python | en | code | 651 | github-code | 6 |
74800916026 | import openai
import uvicorn
from fastapi import FastAPI, Request, Form
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import CSVLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain.vec... | carson-edmonds/AAI-520-Chatbot-Project | openai_fastapi/llm.py | llm.py | py | 7,658 | python | en | code | 0 | github-code | 6 |
17651609361 | from builtins import print, input, int
import mariadb
import sqlite3
import psycopg2
print("Indique en que base de datos quiere realizar las gestiones:")
print("1. PostgreSQL\n2. MariaDB\n3. SQLite3")
lectura = input()
lectura = int(lectura)
while True:
if lectura == 1:
# Creamos la conexi... | PedroPuertasR/2DAM | 2 Trimestre/SGE/ConexionBD/main.py | main.py | py | 6,179 | python | es | code | 0 | github-code | 6 |
21321917983 | #! /usr/bin/env python3
import datetime
import AutoPrimer as ntp
import os
class Worker(object):
def __init__(self, name, command, options, channel, poster):
# date time stamp from scheduler
self.name = name
self.status = 'init' # init, running, done, expired
# which comm... | jcooper036/autoprimer | AutoPrimer/autobot/Worker.py | Worker.py | py | 3,361 | python | en | code | 0 | github-code | 6 |
72498342269 |
from nltk.corpus import wordnet as wn
from nltk.corpus.reader.wordnet import WordNetError
from numpy import dot
from numpy.linalg import norm
import numpy as np
import pdb
class BaseModel:
def __init__(self, subject, predicate, _object):
#subjectFamily.getBaseRanking()[0], predicateFamily.getBaseRanking()... | asuprem/imag-s | utils/baseModel.py | baseModel.py | py | 3,739 | python | en | code | 1 | github-code | 6 |
21521911350 | import os
def read_file(name_file):
cook_book = {}
ingredient = []
file_path = os.getcwd()
path_to_file = os.path.join(file_path, name_file)
with open(path_to_file, 'rt', encoding='utf-8') as recipes:
for line in recipes:
meals = line.strip()
count = int(re... | SergeyDolgushin/homework_2_1 | cook_book.py | cook_book.py | py | 2,424 | python | en | code | 0 | github-code | 6 |
28634572744 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import math
from torch.autograd import Variable
pi = 0.01
class Recommend(nn.Module):
"""A model to build Recommendation system
"""
def __init__(self, past_observations, n_factors, output_dim):
super().... | prakashjayy/av_mckinesy_recommendation_challenge | func.py | func.py | py | 2,764 | python | en | code | 6 | github-code | 6 |
10418282793 | from __future__ import annotations
import platform
import dolphin_memory_engine
import pid
from randovania.game_connection.executor.memory_operation import (
MemoryOperation,
MemoryOperationException,
MemoryOperationExecutor,
)
MEM1_START = 0x80000000
MEM1_END = 0x81800000
def _validate_range(address:... | randovania/randovania | randovania/game_connection/executor/dolphin_executor.py | dolphin_executor.py | py | 4,135 | python | en | code | 165 | github-code | 6 |
16166651344 | import os
USER_HOME = os.path.expanduser('~')
PROJECT_NAME = 'modbus'
PROJECT_HOME = os.path.join(USER_HOME, 'projects', PROJECT_NAME)
DEVICE_INFO_PATH = os.path.join(PROJECT_HOME, 'device_info')
DRIVER_PATH = 'drivers' # dev_info/drivers 등 폴더를 이용해도 됨
DRIVER... | freemancho1/modbus | slave/slave_config.py | slave_config.py | py | 449 | python | en | code | 0 | github-code | 6 |
5479394327 | import numpy as np, base64
from .dict_array import GDict
from .array_ops import encode_np, decode_np
from .converter import as_dtype
from .type_utils import is_np_arr, get_dtype, is_dict, is_not_null, is_null, is_seq_of
from maniskill2_learn.utils.meta import Config, merge_a_to_b
def float_to_int(data, vrange=[0.0, 1... | haosulab/ManiSkill2-Learn | maniskill2_learn/utils/data/compression.py | compression.py | py | 12,857 | python | en | code | 53 | github-code | 6 |
21836861999 | import sys
sys.stdin = open("../inputdata/swea_5202.txt", "r")
for test in range(int(input())):
n = int(input())
trucks = [list(map(int, input().split())) for _ in range(n)]
limit, res = 24, 0
while limit > 0:
tmp = []
for truck in trucks:
if truck[1] <= limit:
... | liza0525/algorithm-study | SWEA/swea_5202.py | swea_5202.py | py | 524 | python | en | code | 0 | github-code | 6 |
30509139595 | """Add sessions
Revision ID: 821a722fb6c5
Revises: 371a1b269d3f
Create Date: 2017-05-04 14:38:19.372886
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '821a722fb6c5'
down_revision = '371a1b269d3f'
branch_labels = None
depends_on = None
def upgrade():
# #... | UltrosBot/Ultros-site | migrations/versions/821a722fb6c5_add_sessions.py | 821a722fb6c5_add_sessions.py | py | 1,008 | python | en | code | 2 | github-code | 6 |
40225040255 | import tkinter as tk
from .Dialog import Dialog
from ..internals.Machine import MachineBuilder
from ..internals.MachineExceptions import *
class InitDialog(Dialog):
def __init__(self, master):
self._builder = MachineBuilder()
Dialog.__init__(self, master, "Initialize machine")
def create_widge... | rodentrabies/TMCode | src/gui/InitDialog.py | InitDialog.py | py | 2,522 | python | en | code | 0 | github-code | 6 |
10205108247 | from bson.objectid import ObjectId
from pyramid.httpexceptions import HTTPFound
from pyramid.security import remember, forget
from pyramid.url import route_url
from pyramid.view import view_config
from .forms import TaskForm, TaskUpdateForm
@view_config(route_name='home', renderer='templates/home.jinja2')
def task_l... | albertosdneto/tutorial_pyramid_mongo | task_manager/views.py | views.py | py | 2,297 | python | en | code | 0 | github-code | 6 |
33008999633 | '''
Script to process nbn coverage map csv files, transform and load into a MongoDB
Author: Rommel Poggenberg (29860571)
Date created: 19th April 2021 (FIT5147 TP2 2021)
'''
import csv
import pymongo
import pprint
import sys
import datetime
pp = pprint.PrettyPrinter(indent=4)
state_lookup={2:'New South Wales',3:'Vi... | rommjp/NBN_Rollout_Visualisation | write_nbn_data_to_mongodb.py | write_nbn_data_to_mongodb.py | py | 5,360 | python | en | code | 0 | github-code | 6 |
31974764531 | # -*- coding: utf-8 -*-
import json
import scrapy
from club_activity_friends_details.items import ClubActivityFriendsDetailsItem
from lib.GetCurrentTime import get_current_date
from models.club import StructureStartUrl
class AutoHomeClubActivityFriendsDetailsSpider(scrapy.Spider):
name = 'auto_home_club_activity... | CY113/Cars | club_activity_friends_details/club_activity_friends_details/spiders/auto_home_club_activity_friends_details.py | auto_home_club_activity_friends_details.py | py | 2,113 | python | en | code | 10 | github-code | 6 |
12989554153 | from PIL import Image, ImageDraw, ImageFont
import calendar, datetime, holidays
def get_image_calendar(dates, year, month):
width, height = 500, 500
img = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('arial.ttf', size=30)
dict_for_month = {"... | michaelgershov/Calendar | calendar_image.py | calendar_image.py | py | 3,088 | python | en | code | 0 | github-code | 6 |
34832286900 | import cv2
vid = cv2.VideoCapture("my_video.mp4")
while(1):
ret, frame = vid.read()
if ret:
frame = cv2.resize(frame, (0, 0), fx = 1.2, fy = 1.2)
cv2.imshow("video", frame)
else:
break
if cv2.waitKey(10000) == ord("q"):
break | jim2832/Image-Recognition | video2.py | video2.py | py | 277 | python | en | code | 0 | github-code | 6 |
19114657314 | import pandas as pd
import torch
import torch.nn as nn
import math
import download
import pickle
import random
max_seq_len=34
pd.set_option('display.max_colwidth', None)
print("here")
# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from ... | razerspeed/Image-Caption-Generation | server2.py | server2.py | py | 6,750 | python | en | code | 1 | github-code | 6 |
7126327995 | from django.urls import path
from . import views
# какие url какой view обрабатывается
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_... | x2wing/django_l2 | blog/urls.py | urls.py | py | 424 | python | en | code | 0 | github-code | 6 |
75131926908 | """
在python中,只有函数才是Callable(可Call的对象才是Callable)。但是tuple是一个数据类型,当然是不能Call(翻译成:使唤,hhh可能会比较容易理解)
"""
import cv2 as cv
import numpy as np
def negation_pixels(image):
print(image.shape)
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
print("width: %s height: %s channels:... | hahahei957/NewProject_Opencv2 | 04_像素取反.py | 04_像素取反.py | py | 1,037 | python | en | code | 0 | github-code | 6 |
6606098136 | from math import floor
def solution(numbers):
answer = []
for number in numbers:
for idx, elm in enumerate(bin(number)[::-1]):
if elm == '0' or elm == 'b':
target = floor(2**(idx-1)) ^ number | 2**idx
answer.append(target)
break
return a... | JeongGod/Algo-study | hyeonjun/16week/p77885.py | p77885.py | py | 326 | python | en | code | 7 | github-code | 6 |
26040960706 | from __future__ import annotations
from textwrap import dedent
from typing import Callable
import pytest
from pants.backend.python.goals.publish import (
PublishPythonPackageFieldSet,
PublishPythonPackageRequest,
rules,
)
from pants.backend.python.macros.python_artifact import PythonArtifact
from pants.b... | pantsbuild/pants | src/python/pants/backend/python/goals/publish_test.py | publish_test.py | py | 6,774 | python | en | code | 2,896 | github-code | 6 |
31872746206 | from lxml import html
import requests
import re
MainPage = requests.get("https://www.carvezine.com/stories/")
tree = html.fromstring(MainPage.content)
links = tree.xpath('//a[@class="summary-title-link"]/@href')
text = ""
text.encode('utf-8').strip()
for link in links:
testURL = "https://www.carvezine.com" + link
s... | RichardWen/python-practice | webscraping/storyscraper.py | storyscraper.py | py | 631 | python | en | code | 0 | github-code | 6 |
31108318218 | '''
Created on 2021年1月30日
@author: Administrator
'''
def signalMaParaList(maShort=range(10,200,10),maLong=range(10,300,10)):
"""
产生简单移动平均线策略的参数范围
:param ma_short:
:param ma_long:
:return:
"""
paraList=[]
for short in maShort:
for long in maLong:
if short>=long:
... | geekzhp/zhpLiangHua | timingStrategy/singals.py | singals.py | py | 1,841 | python | zh | code | 0 | github-code | 6 |
21699610056 | import cv2
# Method: getFrames
# Purpose: Extract a predefined number of frames from a provided video
# Parameters: video_capture: provided video
# frame_num: the desired number of frames
# frame_start: optional value to input for start of frame
def get_frames(video_capture, frame_num, frame_s... | ccranson27/ccr_playground | frame_gathering.py | frame_gathering.py | py | 2,033 | python | en | code | 0 | github-code | 6 |
72699109627 | # -*- coding: UTF-8 –*-
import random
from datetime import datetime
"""This is a random address function"""
def address():
# 小区名,可自行添加
area_address_name = ['蓝湾上林院', '绿城金华御园(别墅)', '紫金湾', '玫瑰星城', '绿城兰园',
'龙庭一品', '江山风华', '中梁首府', '中梁首府', '都市豪园',
'光明湖海城市花园', '金色海塘... | zzyy8678/stady_python | create_address.py | create_address.py | py | 17,836 | python | zh | code | 0 | github-code | 6 |
23630080600 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 19 18:41:54 2022
@author: Vikki
"""
class Node:
def __init__(self, data, next = None, prev=None):
self.data = data
self.next = next
self.prev = prev
class Linkedlist:
def __init__(self,header = None, tail = None):
self.head... | kambojrakesh/Python_DSA | algo-cb/3_doubly_linked_list.py | 3_doubly_linked_list.py | py | 2,575 | python | en | code | 0 | github-code | 6 |
585614447 | from pathlib import Path
ROOT_FOLDER = Path("STOCK_VOLATILITY_NEW").resolve().parent
DATASET_DIR = ROOT_FOLDER / "data"
ALL_DATA_DIR = DATASET_DIR / "all_data.csv"
ALL_DATA_NEW_DIR = DATASET_DIR / "all_data_new.csv"
UNPROCESSED_DATA = DATASET_DIR / "index_funds_data.csv"
FORMATTED_DATA = DATASET_DIR / "formatted_dat... | vladkramarov/index_fund_volatility | core.py | core.py | py | 1,412 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.