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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
38546263572 | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
class Neck(nn.Module):
def __init__(self, in_channels, out_channels, mid_channels=None, conv_bias=True):
super().__init__()
if not mid_channels:
mid_channels = out_channels
se... | nttcom/WASB-SBDT | src/models/monotrack.py | monotrack.py | py | 4,496 | python | en | code | 0 | github-code | 13 |
31797857983 |
from django.test import TestCase, RequestFactory
import os
import sys
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path.append('/home/sany/the_test/the_test/the_test')
django.setup()
from product.models import Product, Category
from datetime import datetime, timedelta
from django.urls import rev... | ripiuk/the_test | product/tests.py | tests.py | py | 1,980 | python | en | code | 0 | github-code | 13 |
42588817193 | #!/usr/bin/python3
from socket import *
import json
import threading
import sys
import os
ip_user={}
user_ip={}
class ServerService(object):
def __init__(self):
self.next_serial_number = 1
def HandleTCP(self, sockfd, saddr):
try:
sermsg="Hello, please... | axde954e6/NCTU-Intro.2_NP | NP/mid/0712534/P2/server.py | server.py | py | 3,506 | python | en | code | 0 | github-code | 13 |
70182864977 | import uwsgi
def application(env, start_response):
if env['REQUEST_METHOD'] == 'OPTIONS':
content = b'Ok'
else:
uwsgi.async_sleep(1)
content = b"Hello World"
start_response('200 OK', [('Content-Type', 'text/plain'),
('Content-Length', str(len(content))... | baverman/services | haproxy/app.py | app.py | py | 345 | python | en | code | 0 | github-code | 13 |
36308689394 | import requests
import tkinter as tk
from tkinter import messagebox
class SportsApp:
def __init__(self, root):
self.root = root
self.root.title("Sports App")
self.search_label = tk.Label(root, text="Enter Player/Event:")
self.search_label.pack()
self.search_entry = tk.Entr... | debsicat22/AdvanceProgramming | Assessment2/assessment2API.py | assessment2API.py | py | 2,264 | python | en | code | 0 | github-code | 13 |
16007536360 | def main():
import gym
import os
import argparse
from solver.networks import PointnetBackbone
from solver.goal_env import make_env
from rl.vec_envs import SubprocVectorEnv, DummyVectorEnv
from rl.sac_agent import SACAgent
from tools.utils import logger
from torch.multiprocessing imp... | haosulab/RPG | solver/trainer/train_sac.py | train_sac.py | py | 1,304 | python | en | code | 18 | github-code | 13 |
21061223413 | continuer = 'o'
# On créé une liste de films vide qui va contenir les films ajoutés
liste_de_films = []
# Boucle principale
while continuer == 'o':
# On récupère le nom du film à ajouter
film_a_ajouter = raw_input('Entrez un titre de film a ajouter: ')
# On créé une liste qui contient tous les films ajoutés... | yogisen/python | BasesUdemy/list/Mini-projet-Cr-er-une-liste-de-films.py | Mini-projet-Cr-er-une-liste-de-films.py | py | 954 | python | fr | code | 1 | github-code | 13 |
17196207203 | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 12})
import multiprocessing as mp
import numpy as np
import os
from algorithms.gradient_descent import GradientDescent
from algorithms.iterative_threshold_methods import IterativeThresholdMethods
import utils.cons... | Ruola/Sparse-Linear-Regression | support_recovery.py | support_recovery.py | py | 5,465 | python | en | code | 0 | github-code | 13 |
18187983306 | from analysis import HolisticAnalyis, reset_wcrt
from vector.vholistic import VectorHolisticAnalysis
from mast.mast_wrapper import MastHolisticAnalysis
import time
import numpy as np
from examples import get_medium_system, get_big_system
from assignment import PDAssignment
from random import Random
import pandas as pd
... | rivasjm/gdpa | paper/vector_times/vector_time.py | vector_time.py | py | 3,085 | python | en | code | 0 | github-code | 13 |
41467103235 | """User preference modeling interface.
Preferences are stored for (1) items in the collection and (2) slot-value pairs
(for slots defined in the domain). Preferences are represented as real values
in [-1,1], where zero corresponds to neutral.
"""
import random
import string
from abc import ABC, abstractmethod
from t... | iai-group/UserSimCRS | usersimcrs/user_modeling/preference_model.py | preference_model.py | py | 6,028 | python | en | code | 8 | github-code | 13 |
11628571445 | #!/usr/bin/env python
import time
import numpy as np
from olympus.objects import ParameterVector
from olympus.planners.abstract_planner import AbstractPlanner
from olympus.planners.utils_planner import get_bounds, get_init_guess
from olympus.utils import daemon
# ====================================================... | aspuru-guzik-group/olympus | src/olympus/planners/planner_steepest_descent/wrapper_steepest_descent.py | wrapper_steepest_descent.py | py | 3,545 | python | en | code | 70 | github-code | 13 |
17588156152 | import sys
sys.stdin = open('input.txt')
def dfs(x,y):
global re
dx = [-1,1,0,0]
dy = [0,0,-1,1]
visited[x][y] = 1
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= nx < n:
if mazz[nx][ny] == 3:
re += 1
ret... | hyejiny/Algo_selfstudy | SWEA/미로.py | 미로.py | py | 843 | python | en | code | 0 | github-code | 13 |
27174038406 | from league.models import Champion, ChampionMastery
class TestSummoner:
def test_champion_mastery_list(self, summoner):
top_champion = summoner.get_top_champion_mastery()
all_champion = summoner.get_all_champion_mastery()
assert isinstance(top_champion[0], ChampionMastery)
assert i... | ah00ee/python-league | tests/test_models.py | test_models.py | py | 920 | python | en | code | 0 | github-code | 13 |
14412221290 | # This file is part of Korman.
#
# Korman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Korman is distributed i... | H-uru/korman | korman/properties/modifiers/game_gui.py | game_gui.py | py | 20,323 | python | en | code | 31 | github-code | 13 |
73515665936 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options # オプションを使うために必要
option = Options() # オプションを用意
option.add_argument('--headless') # ヘッドレスモードの設定を付与
driver = webdriver.Chrome("/home/fumihachi/ws/lib/chromedriver_linux64/chromedriver", options=option)
... | fumihachi94/algo_basics | 030_code/code.py | code.py | py | 956 | python | ja | code | 0 | github-code | 13 |
15335410372 | start = '''
You wake up one morning and find that you aren't in your bed; you aren't even in your room.
You're in the middle of a giant labrynth.
A sign is hanging from the slimy wall: "You have one hour. Don't touch the walls."
There is a hallway to your right and to your left. Also just so you know your current total... | espickermann/2016_GWC_Class_Pojects | python/text_adventure.py | text_adventure.py | py | 4,112 | python | en | code | 0 | github-code | 13 |
41124927354 | import os
import pygame
from pygame import *
from constants import *
def load_image(
name,
sizex=-1,
sizey=-1,
colorkey=None,
):
fullname = os.path.join('sprites', name)
image = pygame.image.load(fullname)
image = image.convert()
if colorkey is not None:
if colorkey is -1:
... | shivamshekhar/LittleFighter | data/functions.py | functions.py | py | 1,572 | python | en | code | 9 | github-code | 13 |
26461691621 | from sales_mania.zoho.get_session import get_session
from collections import defaultdict
import os, copy, datetime, json
import urllib.parse
class inv_document( get_session ):
def __init__(self, login_store, cache_store, user_id, password, data_center, org_id) -> None:
self.service = 'inventory'
s... | shivamswims456/sales_mania | inv_consolidated/inv_document.py | inv_document.py | py | 12,489 | python | en | code | 0 | github-code | 13 |
73534483856 | import datetime
import time
import json
import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from azure.eventhub import EventHubProducerClient, EventData
from configurations import EventHubSettings, TwitterSettings
# Twitter settings
CONSU... | DaveCheema/Optum | Big Data Platform & ML Architectures/Lambda Architecture/Python Projects/WIP/TwitterReader.py | TwitterReader.py | py | 1,645 | python | en | code | 0 | github-code | 13 |
5986414801 | import click
from pulsecalc import core
from rich import print as rprint
from rich.table import Table
@click.group(help="NMR pulse calculator")
def main():
"""Just a placeholder for the main entrypoint."""
pass
@main.command()
def init():
"""Create a table containing the reference pulse definitions"""
... | miguelarbesu/pulsecalc | src/pulsecalc/__main__.py | __main__.py | py | 7,218 | python | en | code | 1 | github-code | 13 |
17768905325 | # import sys
# import random
# f = sys.argv[1]
# l = sys.argv[2]
# def check(no):
# # print('here def')
# if (no<int(f) or no>int(l)):
# print('not valid no')
# return True
# while True:
# try:
# no = int(input(f'Between {f} to {l} Guess no: '))
# # print(f'here1{type(no)}')
# if(check(no)):
# #... | Tushhh71/PythonTraining | v-test.py | v-test.py | py | 1,517 | python | en | code | 0 | github-code | 13 |
43756067276 | import sys, multiprocessing
from top2vec import Top2Vec
import logging
logger = logging.getLogger('gensim')
logger.setLevel(logging.INFO)
sh = logging.StreamHandler(sys.stderr)
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(sh)
def parser(file):
docs ... | kongyq/project_IRDL | topics/main.py | main.py | py | 1,049 | python | en | code | 1 | github-code | 13 |
23619305622 | # 백준 1991
tree = {}
n = int(input())
for _ in range(n):
a, b, c = input().split()
tree[a] = [b, c]
# 전위, 중위, 후위 순회
def pre_order(a):
global ans
if a == ".":
return
ans += a
if tree[a]:
left, right = tree[a]
pre_order(left)
pre_order(right)
def post_order(a):
... | yoooyeon/Algorithm | Tree, Graph/트리 순회.py | 트리 순회.py | py | 769 | python | en | code | 0 | github-code | 13 |
7608113580 | class Music:
def __init__(self, title, interpreter, composer, year):
self.title = title
self.interpreter = interpreter
self.composer = composer
self.year = year
class Search:
def search_by_title(self, playlist, title):
for i in range(len(playlist)):
if playl... | devjavaedu/coursera | python II/sequential_search.py | sequential_search.py | py | 1,069 | python | en | code | 0 | github-code | 13 |
37997350238 | #
## @file TrackD3PDMaker/share/VertexLumiD3PD_prodjobOFragment.py
## @brief Setup D3PD Maker algorithm for luminosity measurement/debug
## @author Simone Pagan Griso
## @date Mar, 2012
##
## Notes:
## - To include non beam-constrained, use as preExec:
## InDetFlags.doVertexFindingForMonitoring.set_Value_and_Lock(Tru... | rushioda/PIXELVALID_athena | athena/PhysicsAnalysis/D3PDMaker/TrackD3PDMaker/share/VertexLumiD3PD_prodJobOFragment.py | VertexLumiD3PD_prodJobOFragment.py | py | 2,580 | python | en | code | 1 | github-code | 13 |
28391352174 | """
Support for Wolf heating via ISM8 adapter
"""
import logging
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.components.binary_sensor import BinarySensorEntity
from wolf_ism8 import Ism8
from .const import (
DOMAIN,
WOLF,
WOLF_ISM8,
SensorType,
)
from ho... | marcschmiedchen/home-assistant-wolf_ism8 | custom_components/wolf/binary_sensor.py | binary_sensor.py | py | 3,495 | python | en | code | 18 | github-code | 13 |
43559767216 | import urlparse
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from isbullshit.items import IsBullshitItem
class IsBullshitSpider(CrawlSpider):
""" General configuration of the Crawl Spider """
... | brouberol/isbullshit-crawler | isbullshit/spiders/isbullshit_spiders.py | isbullshit_spiders.py | py | 1,992 | python | en | code | 31 | github-code | 13 |
16038807807 | import logging, traceback, sys, os, inspect
logging.basicConfig(filename=__file__[:-3] +'.log', filemode='w', level=logging.DEBUG)
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
#Checks for neutral planet
... | rabhatna/CM146 | P4/behavior_tree_bot/checks.py | checks.py | py | 1,730 | python | en | code | 0 | github-code | 13 |
19913298003 | import pygad.kerasga
import pygad
import numpy as np
from kapibara_audio import BUFFER_SIZE
from emotions import EmotionTuple
import tensorflow as tf
import time
from tensorflow.keras import layers
from tensorflow.keras import models
import math
import os.path
from timeit import default_timer as timer
from tflite... | ProjectRobal/Kapibara-Decision-Center | mind.py | mind.py | py | 9,030 | python | en | code | 0 | github-code | 13 |
35000101131 | while True:
try:
age = int(input("What is your age? "))
if age <= 0:
raise ValueError("Hey cut it out")
10 / age
except ValueError as err:
print(f"ValueError exception is raised: {err}")
else:
break
finally:
print("Thank you")
| tmohod10/PythonBasics | 06_error_handling/03_error_handling_iii.py | 03_error_handling_iii.py | py | 304 | python | en | code | 0 | github-code | 13 |
38910382166 | from typing import Dict
from fastapi import APIRouter
from ..schema.status import StatusResponse
router = APIRouter()
@router.get(
path='',
response_model=StatusResponse,
summary='Server status',
description='Returns server status information',
response_description='Status information',
)
asyn... | stefan2811/port-16 | port_16/api/status/handlers/status.py | status.py | py | 573 | python | en | code | 0 | github-code | 13 |
5756290684 | import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from std_msgs.msg import Float32
from cv_bridge import CvBridge, CvBridgeError
import cv2
import numpy as np
from collections import deque
from wcrc_ctrl.BEV import BEV
from wcrc_ctrl.Logger import Logger
# from wcrc_ctrl.Sensor import Sensor
... | ggh-png/wcrc | wcrc_ctrl/wcrc_ctrl/LaneDetector.py | LaneDetector.py | py | 9,624 | python | en | code | 1 | github-code | 13 |
15468527720 |
import numpy as np
import sys
import math
import time
import socket
from util import quaternion_to_euler_angle_vectorized1
from NatNetClient import NatNetClient
import networkx as nx
import matplotlib.pyplot as plt
import random
import matplotlib.path as mpath
import networkx as nx
import matplotlib.pyplot as plt
from... | gerardohmacoto/CSE360 | final/final.py | final.py | py | 17,340 | python | en | code | 0 | github-code | 13 |
29861351197 | import os
import tempfile
import unittest
import intelmq.lib.test as test
from intelmq.bots.outputs.file.output import FileOutputBot
class TestFileOutputBot(test.BotTestCase, unittest.TestCase):
@classmethod
def set_bot(cls):
cls.bot_reference = FileOutputBot
cls.os_fp, cls.filename = tempfi... | certtools/intelmq | intelmq/tests/bots/outputs/file/test_output.py | test_output.py | py | 791 | python | en | code | 856 | github-code | 13 |
4036552271 | import os
import time
import pandas as pd
class History:
def __init__(self, path: str, header=None):
self.path = path
if header is None:
header = ['time', 'bundleid', 'success']
if not os.path.exists(self.path):
os.system(f"echo '{','.join(header)}' >> {self.path}")... | u36318/IPADownie | src/History.py | History.py | py | 1,326 | python | en | code | 0 | github-code | 13 |
2097344713 | from typing import Optional, Any
class BNode:
def __init__(self,
val: Any = None,
l_node: Optional['BNode'] = None,
r_node: Optional['BNode'] = None) -> None:
self.val = val
self.l_node = l_node
self.r_node = r_node
class BTree:
def __init__(self, root_val: An... | atlanmatrix/Algorithm-Py3 | tree.py | tree.py | py | 1,327 | python | en | code | 0 | github-code | 13 |
32846428139 | from asyncio import run
from asyncio.exceptions import CancelledError
from argparse import ArgumentParser
from pyhtools.attackers.web.spider import Spider
from pyhtools.UI.colors import BRIGHT_RED
parser = ArgumentParser(prog='pyspider')
parser.add_argument('-t', '--target', dest='target_url', required=True,
... | dmdhrumilmistry/pyhtools | examples/Web/pyspider.py | pyspider.py | py | 724 | python | en | code | 297 | github-code | 13 |
5904929514 | from .common import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'project',
}
}
PUBLIC_ROOT = os.path.join(os.sep, 'var', 'www', 'project', 'public')
STATIC_ROOT = os.path.join(PUBLIC_ROOT, 'static')
MEDIA_ROOT = os.path.join(PUBLIC_ROOT, 'media')
T... | DjangoLover/djangodash2013-1 | project/settings/production.py | production.py | py | 483 | python | en | code | 0 | github-code | 13 |
31003178186 | # -*- coding: utf-8 -*-
#http://leda.univ-lyon1.fr/fullsql.html
#http://leda.univ-lyon1.fr/leda/meandata.html
#http://leda.univ-lyon1.fr/fG.cgi?n=meandata&c=o&of=1,leda,simbad&nra=l&nakd=1&d=v3k%2C%20mod0&sql=(objtype%3D%27G%27)%20AND%20(v3k>3000)%20AND%20(v3k<30000)%20AND%20(mod0%20IS%20NOT%20NULL)%20AND%20(v3k%2... | AlessandroPTSN/Como-calcular-a-idade-do-UNIVERSO | Universo_Anos.py | Universo_Anos.py | py | 3,847 | python | pt | code | 2 | github-code | 13 |
36180403196 | import string
import os
import json
import random
import hashlib
from collections import namedtuple
import glob
import boto3
AudioFormat = namedtuple( "AudioFormat", ["OutputFormat","file_extension"] )
format_ogg = AudioFormat(
OutputFormat = "ogg_vorbis",
file_extension = "ogg"
)
format_mp3 = AudioFormat(... | prehensile/phone-algos | polly_handler.py | polly_handler.py | py | 2,670 | python | en | code | 0 | github-code | 13 |
36727124276 | import cv2
import numpy as np
import sqlite3
import os
conn = sqlite3.connect('database.db')
if not os.path.exists('./dataset'):
os.makedirs('./dataset')
c = conn.cursor()
face_cascade = cv2.CascadeClassifier('C:/Users/Qweku/Desktop/NEW_CODE/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
Fu... | AsieduAmos/intruder_detection | record_face.py | record_face.py | py | 1,082 | python | en | code | 0 | github-code | 13 |
5517964945 | from src.jobs import read
def get_unique_job_types(path):
jobs_list = read(path)
jobs_types = []
for job in jobs_list:
if job["job_type"] != "" and job["job_type"] not in jobs_types:
jobs_types.append(job["job_type"])
return jobs_types
def filter_by_job_type(jobs, job_type):
... | ScriptCamilo/trybe-job-Insights | src/insights.py | insights.py | py | 2,794 | python | en | code | 0 | github-code | 13 |
41161855674 | number_of_rooms = int(input())
all_rooms = []
free_chairs = 0
number_of_room = 1
has_space = True
for i in range(number_of_rooms):
all_rooms.append(input().split())
for room in all_rooms:
chairs = len(room[0])
people = int(room[1])
if chairs >= people:
free_chairs += chairs - peop... | lefcho/SoftUni | Python/SoftUni - Python Fundamentals/Lists_Advanced/Office Chairs.py | Office Chairs.py | py | 577 | python | en | code | 0 | github-code | 13 |
351798233 | class SLLNode:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return "SLLNode object: data={}".format(self.data)
def get_data(self):
"""
Return the self.data attribute
"""
return self.data
def set_data(self, new... | moseswong74/pythonPractice | Must_Know/Data_Structure/SLLNode.py | SLLNode.py | py | 3,990 | python | en | code | 0 | github-code | 13 |
3860048000 | #This script follows a user's Twitter stream and messages them when they tweet.
#The interval between tweets can be adjusted using the sleep() function
from twython import TwythonStreamer, Twython
from datetime import date
import random
import time
#auth.py is the second file, containing your dev.twitter.com credenti... | circumlocutory/pytwybot | cleanStream.py | cleanStream.py | py | 3,745 | python | en | code | 0 | github-code | 13 |
365740693 | import logging
import math
import skia
from fontTools.misc.transform import Transform
from fontTools.pens.basePen import BasePen
from fontTools.pens.pointPen import PointToSegmentPen, SegmentToPointPen
from .gstate import TextStyle
# TODO:
# - textBox
# MAYBE:
# - contours
# - expandStroke
# - intersectionPoints
# - ... | alexnathanson/solar-protocol | backend/createHTML/venv-bk/lib/python3.7/site-packages/drawbot_skia/path.py | path.py | py | 11,161 | python | en | code | 207 | github-code | 13 |
7797217994 | def best_features_fre(x_train, y_train, qtd_var = 20, valor_se_missing = -999, tipo_de_modelo = 'LogisticRegression'):
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTr... | Guilherme-maia/projeto_ml_publico | best_features_fre.py | best_features_fre.py | py | 1,719 | python | en | code | 0 | github-code | 13 |
35901420793 | # -*- coding:utf-8 -*-
# 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... | sandyhouse/dlbenchmark | models/cnn/model.py | model.py | py | 2,265 | python | en | code | 0 | github-code | 13 |
38639682081 | #!/usr/bin/python3
"""
This module is responsible for printing a square using the character '#'.
"""
def print_square(size):
"""
Prints a square with the character '#' of the specified size.
Args:
size (int): The length of one side of the square.
Raises:
TypeError: If the 'size' param... | DoxaNtow/alx-higher_level_programming | 0x07-python-test_driven_development/4-print_square.py | 4-print_square.py | py | 811 | python | en | code | 0 | github-code | 13 |
42241543661 | import torch
import torch.nn as nn
from collections import OrderedDict
class Bottleneck(nn.Module):
def __init__(self, inchannel, growthrate, bn_size):
super(Bottleneck, self).__init__()
self.innerchannel = growthrate*bn_size
self.bn = nn.BatchNorm2d(inchannel)
self.relu = nn.ReLU(i... | HugoAhoy/RADN-Region-Adaptive-Dense-Network-for-Efficient-Motion-Deblurring-PyTorch-Implementation | network/densemodule.py | densemodule.py | py | 2,702 | python | en | code | 6 | github-code | 13 |
30801581413 | import os
import requests as r
def getArticles(topic='bitcoin', limit=5):
'''
Creates a API request to get articles on a certain
topic provided by URL.
Params:
@topic string (required): The topic you would like news on
@limit integer : The number of articles you would like to receive
'''... | meads2/tableau-newsfeed | endpoints/getNews.py | getNews.py | py | 652 | python | en | code | 1 | github-code | 13 |
12532696584 | from __future__ import absolute_import, division, print_function
import json
from collections import defaultdict
import six
from flask import current_app
from inspirehep.modules.disambiguation.core.db.readers import (
get_all_curated_signatures,
get_all_publications,
)
from inspirehep.modules.disambiguation.... | miguelgrc/inspire-next | inspirehep/modules/disambiguation/api.py | api.py | py | 4,490 | python | en | code | null | github-code | 13 |
26334801440 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0016_piggyuser_profile_image'),
]
operations = [
migrations.AddField(
model_name='piggyproject',
... | wavesoft/creditpiggy | creditpiggy-server/creditpiggy/core/migrations/0017_auto_20150624_1257.py | 0017_auto_20150624_1257.py | py | 961 | python | en | code | 0 | github-code | 13 |
72935947538 | import pprint
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
vocab_size = 100 # 단어 idx 1-100
pad_id = 0
data = [
[85,14,80,34,99,20,31,65,53,86,3,58,30,4,11,6,50,71,74,13],
[62,76,79,66,32],
[93,77,16,67,46,74,24,70],
[19,83,88,22,57,40,75,82,4,46... | zeus0007/til | code/rnn.py | rnn.py | py | 3,889 | python | en | code | 1 | github-code | 13 |
14140536482 | import socket
import os
import time
import random
import logging
from _thread import start_new_thread
from threading import Lock
import pickle
import copy
import utils
from collections import deque
from heapq import heappush, heappop
import json
import sys
class Server:
CHANNEL_PORT = 10000
SERVER_PORTS = {
... | zexihuang/raft-blockchain | server.py | server.py | py | 65,440 | python | en | code | 4 | github-code | 13 |
25375789729 | #!/usr/bin/env python
# coding: utf-8
import os
import sys
import numpy as np
class Target:
def __init__(self,pathToTargetFile):
self.targetStateData = np.loadtxt(pathToTargetFile)
(self.numberOfPoints,self.sizeOfState) = np.shape(self.targetStateData)
self.time = s... | bishopaudrey/radar-modeling | target_model.py | target_model.py | py | 3,028 | python | en | code | 0 | github-code | 13 |
34908727216 | # -*- coding:utf-8 -*-
# @Time : 2019/8/22 13:18
# @Author : Junwu Yu
'''
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
'''
class Solution:
def longestConsecutive(self, nums) -> int:
# 位图法,memorry error
if len(nums) == 0:
... | Yujunw/leetcode_python | 128_最长连续序列.py | 128_最长连续序列.py | py | 1,798 | python | en | code | 0 | github-code | 13 |
16610723237 |
from .dataset import load_xview_metadata, read_labels_file
import json
train_data, val_data, _ = load_xview_metadata("/home/c3-0/rohitg/xviewdata/xview/", data_version="v2/", use_tier3=True)
# print(val_data.keys())
val_loc_split = open("loc_val.txt", "w")
train_loc_split = open("loc_train.txt", "w")
val_cls_spli... | rohit-gupta/building-damage-assessment | utils/baseline.py | baseline.py | py | 1,869 | python | en | code | 0 | github-code | 13 |
28955367165 | from .test_base import TestBase
from b2.parse_args import parse_arg_list
class TestParseArgs(TestBase):
NO_ARGS = {
'option_flags': [],
'option_args': [],
'list_args': [],
'optional_before': [],
'required': [],
'optional': [],
'arg_parser': {}
}
EV... | jhill69/Hello-World | test/test_parse_args.py | test_parse_args.py | py | 2,896 | python | en | code | 0 | github-code | 13 |
14800654413 | import pygame
from pygame.locals import *
import random
class Comida:
'Clase para comida'
x = 0 # Posicion x, y
y = 0
i = 0
frutas = {}
def __init__(self, x, y):
# Se cargan las imagenes de las distinas comidas
self.imgManzana = pygame.image.load("imagenes/comida/manzana.png"... | anakloss/snake_game | Snake/clases/Comida.py | Comida.py | py | 1,353 | python | es | code | 2 | github-code | 13 |
23248973322 | from typing import final
from flask import Flask, render_template, Markup
from flask_table import Table, Col
import os
# Kevin's files
from Kevin import *
from Kevin.backtest import *
# Wenlei's files
from Wenlei.TRIMA_wenlei_cao_get_backtrade_result import *
# Jackie's files
from Jackie.Turner_TradingSystemWithBack... | kmart8/Trading-System | app.py | app.py | py | 3,557 | python | en | code | 0 | github-code | 13 |
2244791689 | """
Overview
========
This plugin implements the basic cursor movements.
Key-Commands
============
Namespace: main-jumps
Mode: NORMAL
Event: <Key-j>
Description: Move the cursor one line down.
Mode: NORMAL
Event: <Key-k>
Description: Move the cursor one line up.
Mode: NORMAL
Event: <Key-h>
Description: Move ... | vyapp/vy | vyapp/plugins/main_jumps.py | main_jumps.py | py | 779 | python | en | code | 1,145 | github-code | 13 |
29118297963 | import cv2
import numpy as np
from utils import FileController
def main():
has_capture = input('Capture from camera? [y/n]: ') == 'y'
device_id = 0
selected_video = None if has_capture else FileController.get_file(['mp4'], './video_in')[0]
capture_from = device_id if has_capture else selected_video
... | mktia/plant_reservoir | detect_corners_by_gftt.py | detect_corners_by_gftt.py | py | 1,330 | python | en | code | 0 | github-code | 13 |
10896840331 | def min_keystrokes(S):
# Initialize the displayed number and the keystroke count to 0
num = 0
count = 0
# Iterate through the digits of S
while S > 0:
# Get the most significant digit
digit = S // 10
# Check if the digit is 0 or 00
if digit == 0:
# Check i... | Yeansovanvathana/Vathana_Python | own project/vathana.py | vathana.py | py | 1,008 | python | en | code | 0 | github-code | 13 |
5328634672 | # -*- coding:utf8 -*-
"""
Created on 2020/3/12 17:43
@author: minc
# 接口
"""
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.externals import joblib
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Lo... | wminc/Machine_Learning | scikit-learn/api.py | api.py | py | 10,177 | python | en | code | 0 | github-code | 13 |
21059517764 | import pandas as pd
from reed_solomon_code.ReedSolomonCode import ReedSolomonCode
def rs_stat_test(solomon, poly_errors, parity_errors):
arr = []
"""
:type solomon: ReedSolomonCode
"""
correct_probes = 0
decoded_but_good = 0
count = 1000
i = 0
while i < count:
rand_messag... | Mazako/NIDUC_projekt | tests/mochnacki.py | mochnacki.py | py | 1,736 | python | en | code | 0 | github-code | 13 |
25756279389 | import pathlib
import lib
data_path = pathlib.Path('data')
db = data_path.joinpath('db.sqlite')
cn = lib.get_sqlite_conn(db)
holder = lib.get_holder(cn)[0]
print('{} has the token for {}'.format(holder[0], holder[2]))
| sesquivel312/tos | tos/experiment.py | experiment.py | py | 239 | python | en | code | 0 | github-code | 13 |
18234816113 | import pandas as pd
import numpy as np
import plotly.express as px
import streamlit as st
def get_overview(df):
info_name = ["Total Number of Projects", "Total Transaction Amount(current usd)"]
info_value = [df.shape[0], df["usd_current"].sum()]
df_overview = pd.DataFrame({"name": info_name, "value": info... | wpan03/tdf_app | country_profile.py | country_profile.py | py | 6,337 | python | en | code | 0 | github-code | 13 |
13030276745 | def solution():
n = int(input())
day = [[0,0] for _ in range(n)]
dp = [0 for _ in range(n+1)]
for i in range(n):
time, money = [int(v) for v in input().split(' ')]
day[i][0] = time
day[i][1] = money
for i in range(n):
dp[i + 1] = max(dp[i + 1], dp[i])
if i ... | chaeheejo/algorithm | baekjun/silver/leave_company.py | leave_company.py | py | 500 | python | en | code | 0 | github-code | 13 |
22467466643 | """
Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год».
В рамках класса реализовать два метода. Первый, с декоратором @classmethod,
должен извлекать число, месяц, год и преобразовывать их тип к типу «Число».
Второй, с декоратором @staticmethod, должен про... | slavaprotogor/python_base | homeworks/lesson8/task1.py | task1.py | py | 2,153 | python | ru | code | 0 | github-code | 13 |
6204966732 | from fmc.resources.base import ResourceBase
from fmc.decorators import (
RequiredArguments,
RequiredProperties
)
class UserToGroupAddition(ResourceBase):
Type = "AWS::IAM::UserToGroupAddition"
@RequiredArguments([
"LogicalID"
])
@RequiredProperties([
"GroupN... | logikone/form_my_cloud | fmc/resources/iam/user_to_group_addition.py | user_to_group_addition.py | py | 487 | python | en | code | 0 | github-code | 13 |
10041154126 | from telnetlib import EC
import psycopg2 as pg
import pytest
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import B... | Manjuurs1234/DynoWebTesting | Testcases/logout_page_03.py | logout_page_03.py | py | 2,765 | python | en | code | 0 | github-code | 13 |
42658291719 | import numpy as np
from main import perform_operation
def chain(img: np.ndarray, operations: list[str]) -> np.ndarray:
"""Apply multiple operations to the image in sequence
Args:
img (np.ndarray): The image to apply the operations to
operations (list[str]): The operations to apply to the ima... | CullenStClair/img-editor | operations/chain.py | chain.py | py | 672 | python | en | code | 1 | github-code | 13 |
42617449643 | import math
import torch
import torch.nn as nn
from vidar.utils.distributed import print0, rank, dist_mode
from vidar.utils.logging import pcolor
from vidar.utils.tensor import same_shape
from vidar.utils.types import is_list
def freeze_layers(network, layers=('ALL',), flag_freeze=True):
"""
Freeze layers o... | bingai/vidar | vidar/utils/networks.py | networks.py | py | 6,314 | python | en | code | 1 | github-code | 13 |
40179604773 | import sys
sys.path.extend([".", "../../code"])
from PyQt5.QtWidgets import QTabWidget, QFileDialog
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QAction, QMessageBox
from input_output.sbml_saver import SbmlSaver
from simulation.ode_simulator import OdeSimula... | ilkutkutlar/gene-grn-simulator | src/ui/gui.py | gui.py | py | 6,263 | python | en | code | 0 | github-code | 13 |
26588861282 | from datetime import datetime, date
print("date_today=", date.today())
# создадим даты как строки
ds1 = 'Friday, November 17, 2020'
ds2 = '11/17/20'
ds3 = '11-17-2020'
# Конвертируем строки в объекты datetime и сохраним
dt1 = datetime.strptime(ds1, '%A, %B %d, %Y')
dt2 = datetime.strptime(ds2, '%m/%d/%y')
dt3 = date... | a6m2zerot/Planner_v.1.0 | unnamed.py | unnamed.py | py | 1,090 | python | ru | code | 0 | github-code | 13 |
42720984970 | #!/bin/env python
import boto3
import logging
import os
from modules.RegionInfo import RegionInfo as RegionInfo
def show_identity():
# boto3.session.Session(region_name=None, profile_name=None)
aws = boto3.session.Session()
sts = aws.client('sts')
identity = sts.get_caller_identity()
l... | yosefrow/bizzabo | python/src/main.py | main.py | py | 1,287 | python | en | code | 0 | github-code | 13 |
26590149696 | import json
import xmltodict
import pafy
from youtube_search import YoutubeSearch
from genericpath import exists
from requests import request
def get_textfile(filepath, textstring=''):
if exists(filepath):
with open(filepath, 'r') as f:
return f.read()
elif textstring:
with open(f... | webavant/seekseek | server/project/server/search_functions.py | search_functions.py | py | 2,107 | python | en | code | 0 | github-code | 13 |
4565215170 | import numpy as np
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
class cleaner(object):
def __init__(self, data):
self.data = data
@staticmethod
def append_string(append_type, row):
if append_type == 'hospital':
... | minh5/cpsc | reports/neiss.py | neiss.py | py | 5,904 | python | en | code | 0 | github-code | 13 |
23552322040 | import json
import os
import numpy as np
from PIL import Image
def rotate_xy(x, y, deg, rot_center_x=0, rot_center_y=0):
'''
Args:
x, y: int
回転前の点の座標
deg: int, float
回転させる角度
rot_center_x, rot_center_y: int, float
回転中心
Returns:
rotated_c... | ktoyod/rotatedpose | src/utils/rotate.py | rotate.py | py | 3,906 | python | ja | code | 2 | github-code | 13 |
33782623378 | from huggingface_hub import HfApi, hf_hub_download, snapshot_download, upload_folder
repo_id = "vermouthdky/SimTeG"
snapshot_download(
repo_id=repo_id,
repo_type="dataset",
local_dir="../lambda_out",
local_dir_use_symlinks=False,
allow_patterns=[
"ogbn-products/e5-large/optuna_peft/best/ca... | vermouthdky/SimTeG | download_embs.py | download_embs.py | py | 345 | python | en | code | 10 | github-code | 13 |
26978106874 | from django.contrib import admin
from django.urls import path
from .import views
from django.contrib.auth.views import LoginView,LogoutView
from .import views
# urls for admin
urlpatterns= [
path('',views.home_view,name='home'),
path('signup',views.signup_view,name="signup"),
path('adminsignup', views.adm... | Sanjay-272002/hms | mediapp/urls.py | urls.py | py | 6,218 | python | en | code | 0 | github-code | 13 |
5040156385 | ###### Enums ######
DECODING_SOURCE = {
"DecodingSourceXMLFile": 0,
"DecodingSourceWbem": 1,
"DecodingSourceWPP": 2,
}
DECODING_SOURCE_INV = {
0: "DecodingSourceXMLFile",
1: "DecodingSourceWbem",
2: "DecodingSourceWPP",
}
TDH_IN_TYPE = {
"TDH_INTYPE_NULL": 0,
"TDH_INTYPE_UNICODESTRING": ... | commial/temp | api_miasm/tdh.dll.py | tdh.dll.py | py | 19,244 | python | en | code | 4 | github-code | 13 |
2486816259 |
import random
y = (random.randint(0,9))
x = int(input("Enter a number between 0 to 9 \n"))
if y == x:
print("Exactly right answer")
elif abs(y - x) >= 3:
print("Not close ")
elif abs(y - x) < 3:
print("Too Close ")
print("Computer selected {} ".format(y))
| shivanksaxena93/Python | Solutions-of-practisepython.org/GuessingGame-1.py | GuessingGame-1.py | py | 270 | python | en | code | 0 | github-code | 13 |
21632097815 | """ For a file, plots the eigenfunctions """
import numpy as np
import matplotlib.pyplot as plt
import sys
def density(rho,func):
return func**2
infilename=sys.argv[1]
infile=open(infilename)
n=int(infile.readline().split()[-1])
print(n)
rhomax=float(infile.readline().split()[-1])
rhomin=float(infile.readline().spl... | adrian2208/FYS3150_collab | Project2/plot_solutions.py | plot_solutions.py | py | 1,132 | python | en | code | 0 | github-code | 13 |
4834279732 | from django.urls import path, include
from rest_framework import routers
from job.api.views import JobCategoryViewSet, SkillViewSet, JobViewSet
router = routers.SimpleRouter()
router.register('skill', SkillViewSet)
router.register('job-category', JobCategoryViewSet)
router.register('', JobViewSet)
urlpatterns = [
... | jamedadi/jobnet | job/api/urls.py | urls.py | py | 356 | python | en | code | 14 | github-code | 13 |
17027231969 | from CGRtools.files import RDFread, RDFwrite
from enumeration_reaction import enumeration_cgr
from new_cycl import cycl
from constructor import constructor
import pickle
det = False
with RDFread():
fg_fg = {}
for n, reaction in enumerate(reaction_file, start = 1):
print(n)
# if n != 58925:
... | neon-monster/retrosintetic_rules | trules.py | trules.py | py | 1,403 | python | en | code | 0 | github-code | 13 |
25085487533 | import os
from dotenv import load_dotenv
# This helper function will check if a user is an admin or not
def get_admins(email):
load_dotenv(verbose=True)
# get all possible admin emails
admin_emails = os.getenv("ADMIN_EMAILS")
for emailOf in admin_emails.split(' '):
if email == emailOf:
... | CSchairez/ParMe | server/routes/helpers.py | helpers.py | py | 356 | python | en | code | 0 | github-code | 13 |
17083248727 | import random
import json
from vk_api.keyboard import VkKeyboardColor as color
BLUE = color.PRIMARY # Синяя
WHITE = color.SECONDARY # Белая
RED = color.NEGATIVE # Красная
GREEN = color.POSITIVE # Зелёная
"""
KeyBoardDoc --> https://dev.vk.com/api/bots/development/keyboard
"""
a = {'label': '___', 'color': None, '... | SHkipperX/Mge_Bot | button.py | button.py | py | 4,739 | python | ru | code | 1 | github-code | 13 |
8616422528 | from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'channel/(?P<title>.+)/$', views.channel, name='channel'),
url(r'^api/', include('api.urls')),
url(r'^api-auth/', include(
'rest_framework.urls',... | Windsooon/youtube-channels | django_base/django_base/urls.py | urls.py | py | 380 | python | en | code | 0 | github-code | 13 |
32023481820 | from aiolava.misc import HTTPMethod
from aiolava.endpoints.base import LavaEndpoint
from aiolava.types.wallet.create_invoice import CreateInvoiceResponse
class CreateInvoice(LavaEndpoint):
__http_method__ = HTTPMethod.POST
__endpoint__ = "/invoice/create"
__returns__ = CreateInvoiceResponse
wallet_t... | TheArcherST/aiolava | aiolava/endpoints/wallet/create_invoice.py | create_invoice.py | py | 605 | python | en | code | 1 | github-code | 13 |
7329228026 | from copy import deepcopy
import cv2
import os
import numpy as np
class MMImage:
def __init__(self, method='blur'):
self.method = method
self.img = None
def process(self, save_path='', para=[]):
if save_path != '':
save_path = save_path
img_out = getattr(self, "_"+... | OpenXLab-Edu/OpenBaseLab-Edu | tools/mmImage.py | mmImage.py | py | 5,796 | python | en | code | 5 | github-code | 13 |
74920632978 |
import argparse
import csv
import logging
import multiprocessing
import os
import pickle
import pprint
from ruffus.proxy_logger import *
from scipy.stats import kendalltau, pearsonr, spearmanr
from predict_regulons import *
def parseCommandLineArguments():
parser = argparse.ArgumentParser(prog="predict_regulo... | priyanka8590/ReguloPred | calculate_correlations.py | calculate_correlations.py | py | 11,281 | python | en | code | 0 | github-code | 13 |
13251203845 | import networkx as nx
import numpy as np
import pymetis
import copy
import pandas as pd
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("netname")
args = parser.parse_args()
netname = str(args.netname)
year = "2023"
CANDIDATES_INFORMATION = 1
class SocialNetwork():
def __init__(self, name... | alesalloum/political-polarization | enrich_network.py | enrich_network.py | py | 6,715 | python | en | code | 0 | github-code | 13 |
19067855406 | from django.db import models
from django.contrib.auth.models import User
class Problem(models.Model):
difficulty_choices = [("Easy", "Easy"), ("Medium", "Medium"), ("Difficult", "Difficult")]
problem_id = models.CharField(max_length=120)
problem_title = models.CharField(max_length=200)
problem_stateme... | Surya-Varman/OnlineJudge | code_execution/models.py | models.py | py | 1,752 | python | en | code | 0 | github-code | 13 |
10011884236 | import psycopg2
import numpy as np
import psycopg2.extras as extras
import pandas as pd
import time
import threading
import requests
import json
def get_weather_data(api_key, city_id,id_number):
api_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"id": city_id,
"u... | Barissdal/ETL_From_API_With_Python_To_PostgreSQL_And_Schedule | etl_api_data_with_python_into_postgress.py | etl_api_data_with_python_into_postgress.py | py | 2,575 | python | en | code | 0 | github-code | 13 |
27691941513 | from torch.nn import functional as F, ModuleList, Module, Dropout
from torch_geometric.nn import GCNConv, GATConv
class GCN(Module):
def __init__(self, convs):
super(GCN, self).__init__()
self.convs = ModuleList()
self.dropouts = ModuleList()
for key, (inputDim, outputDim,... | MengBaofh/GModel | GNNs/Models.py | Models.py | py | 1,344 | python | en | code | 1 | github-code | 13 |
10387042396 | from controller.appReglas import AppReglas
from util import enumerations as enu
from openpyxl import Workbook
#Estaciones selecionadas
listEstation=['M1219','M1221','M1230','M1231','M1233','M1238','M1239','M1240','M1243','M1244','M1246','M1248',
'M1249','M1250','M1256','M1257','M1257','M1259','M1260','M1261','M12... | meteorodev/rev3horas | View/impReglas.py | impReglas.py | py | 2,054 | python | es | code | 0 | github-code | 13 |
4035172296 | from django.urls import path
from . import views
urlpatterns = [
path('add/<int:product_id>/', views.add_review, name='add_review'),
path(
'delete/<int:product_id>/<int:review_id>/',
views.delete_review, name='delete_review'),
]
| WisamTa/Supplement-Store | reviews/urls.py | urls.py | py | 255 | python | en | code | 1 | github-code | 13 |
40217525703 | """All that this class should do is putting the setup, execution and saving all together."""
import numpy as np
import time
from one_ray_solver.utility import screen_COM_converter, redshift
from one_ray_solver.ode import solver
from one_ray_solver.collision import collider
from one_ray_solver.save import saver_cfg, s... | uhrwecker/Spin | one_ray_solver/solve.py | solve.py | py | 7,259 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.