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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
6882747948 | # Строка содержит набор чисел. Показать большее и меньшее число. Символ-разделитель - пробел
def String_Min_and_Max(str):
list1 = str.split(' ')
min = int(list1[0])
max = int(list1[0])
for i in range(len(list1)):
list1[i] = int(list1[i])
if list1[i] < min:
min = list1[i]
... | AlbertKhismatullin/Python_HomeWork | Task27.py | Task27.py | py | 681 | python | ru | code | 0 | github-code | 36 |
75312911145 | import matplotlib.pyplot as plt
from moisture_tracers import plotdir
from moisture_tracers.plot.figures.fig2_satellite_comparison import make_plot
def main():
start_time = "20200201"
grid = "lagrangian_grid"
resolutions = ["km1p1", "km2p2", "km4p4"]
lead_times = [30, 36, 42, 48]
make_plot(start_t... | leosaffin/moisture_tracers | moisture_tracers/plot/figures/fig4_satellite_comparison_lagrangian_grid.py | fig4_satellite_comparison_lagrangian_grid.py | py | 560 | python | en | code | 0 | github-code | 36 |
27140115657 | # -*- coding: utf-8 -*-
#######################
# deploy.urls
#######################
"""
1. 部署服务
2. add DNS
3. nginx设置
4. config check
5. 诊断
"""
from django.urls import path
from deploy import views
urlpatterns = [
path('health/', views.health,name="health"),
path('start/',views.deploy,name="deploy"... | yuzhenduan/envDeploy | deploy/urls.py | urls.py | py | 691 | python | en | code | 0 | github-code | 36 |
14076203382 | import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
# SETUP SCREEN
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.tracer(0)
# SETUP CARS, TURTLE, SCOREBORAD AND STREET BACKGROUND
car = CarManager()
t... | rivelez65/turtle-crossing-arcade_OOP-Turtle | main.py | main.py | py | 1,803 | python | en | code | 1 | github-code | 36 |
2153986094 | from django.shortcuts import render
# Create your views here.
def func(request, num1, num2):
if num2 != 0:
div = num1 / num2
else:
div = '계산할 수 없습니다.'
context = {
'num1' : num1,
'num2' : num2,
'sub' : num1 - num2,
'mul' : num1 * num2,
'div' : div
... | ji-hyon/Web_study | Django/practice/part2_Django/django_2_2/project2/calculators/views.py | views.py | py | 406 | python | en | code | 0 | github-code | 36 |
14128946048 | #!/usr/local/bin/ python3
# -*- coding:utf-8 -*-
# __author__ = "zenmeder"
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inorderTraversal(self, root):
res, stack = [], []
while True:
while ... | zenmeder/leetcode | 94.py | 94.py | py | 579 | python | en | code | 0 | github-code | 36 |
10197349809 | # nosetests --nocapture tests/test_record.py
import unittest
from fit_tool.definition_message import DefinitionMessage
from fit_tool.profile.messages.workout_step_message import WorkoutStepMessage
from fit_tool.record import RecordHeader, Record
class TestRecord(unittest.TestCase):
def shortDescription(self):... | soh55/python_fit_tool | fit_tool/tests/test_record.py | test_record.py | py | 2,080 | python | en | code | 0 | github-code | 36 |
71355007785 | import dotenv
import openai
import os
dotenv.load_dotenv('../.env')
openai.api_key = os.environ["OPENAI_API_KEY"]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "tell me about gpt for social good"}
]
)
print(response["choices"][0]["message"]["... | aiformankind/gpt-for-social-good | gpt/demo.py | demo.py | py | 330 | python | en | code | 0 | github-code | 36 |
71249335464 | """
NSynth classification using PyTorch
Authors: Japheth Adhavan, Jason St. George
Reference: Sasank Chilamkurthy <https://chsasank.github.io>
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import utils
import models
import data
import visuali... | ifrit98/NSynth_Classification_CNN | src/main.py | main.py | py | 9,785 | python | en | code | 1 | github-code | 36 |
5547407739 | """
Tests for voting 31/01/2023.
"""
from scripts.vote_2023_01_31 import start_vote
from brownie import chain, accounts
from brownie.network.transaction import TransactionReceipt
from eth_abi.abi import encode_single
from utils.config import network_name
from utils.test.tx_tracing_helpers import *
from utils.test.e... | lidofinance/scripts | archive/tests/test_2023_01_31.py | test_2023_01_31.py | py | 12,625 | python | en | code | 14 | github-code | 36 |
21886050699 | # %% [markdown]
# Perl map functions
# %%
def solution(A,B):
lengthA = len(A)
hashA = {}
hashB = {}
j=0
k=0
sumA = 0
sumB = 0
for i in A:
sumA+=i
hashA[j]=sumA
j+=1
for i in B:
sumB+=i
hashB[k]=sumB
k+=1
allValues = []
for i in... | ashwanijha/pythonCodes | FAIRNumber.PY | FAIRNumber.PY | py | 518 | python | en | code | 0 | github-code | 36 |
31803136505 | import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("127.0.0.1", 5050))
print ("Server started")
registered=[]
def new_client(message, caddr):
print("Connection from: " + str(caddr[0]+":"+str(caddr[1])))
data = message
if str(data).startswith('Signin'):
... | root-dm/python-socket | udp/server.py | server.py | py | 2,343 | python | en | code | 0 | github-code | 36 |
6415147937 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 18:08:59 2021
@author: Chris
"""
#%% Imports
from PIL import ImageGrab
import win32gui
import numpy as np
import time
import cv2
#%% Get the ID of the Emulator window
# List to hold window information
window = []
# Name of the window to find
window_name = "Super St... | qchrisd/StreetFighterBot | ScreenGrabProof.py | ScreenGrabProof.py | py | 2,115 | python | en | code | 0 | github-code | 36 |
39627512703 | import sys
import argparse
from lettuce.bin import main as lettuce_main
from lettuce import world
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from salad.steps.everything import *
from salad.terrains.everything import *
BROWSER_CHOICES = [browser.lower()
for browse... | salad/salad | salad/cli.py | cli.py | py | 3,130 | python | en | code | 122 | github-code | 36 |
39671693100 | import discord
from discord.ext import commands
import time
import json
import os
if not os.path.isfile('config.json'):
exit
f = open('config.json')
data = json.load(f)
TOKEN = data['token']
servers = data['servers']
message = data['message']
delay = int(data['delay'])
for i in range(len(servers)):
servers... | skiteskopes/discord_channel_create_auto_messager | discord_bot.py | discord_bot.py | py | 593 | python | en | code | 0 | github-code | 36 |
2962922987 | #! /usr/bin/env python
from sensor_msgs.msg import CompressedImage
from cv_bridge import CvBridge, CvBridgeError
import cv2
import rospy
import subprocess
#from PIL import Image # PIL
from __init__ import *
from rgiro_spco2_slam.srv import spco_data_image,spco_data_imageResponse
import spco2_placescnn as places365
cl... | Shoichi-Hasegawa0628/spco2_boo | rgiro_spco2_slam/src/spco2_image_features.py | spco2_image_features.py | py | 3,939 | python | en | code | 2 | github-code | 36 |
70345443943 | import numpy as np
import math
import torch
import torch.nn as nn
class Upper(nn.Module): # Upper: Mutual Information Contrastive Learning Upper Bound
'''
This class provides the Upper bound estimation to I(X,Y)
Method:
forward() : provides the estimation with input samples
... | joey-wang123/Semi-meta | mi_estimators.py | mi_estimators.py | py | 3,452 | python | en | code | 0 | github-code | 36 |
20504076743 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Filename : kalao_pump_switch.sh
# @Date : 2023-01-12-14-12
# @Project: KalAO-ICS
# @AUTHOR : Janis Hagelberg
"""
kalao_pump_switch.py is part of the KalAO Instrument Control Software it is a maintenance script used to switch
the water cooling pump from on to off and opp... | janis-hag/kalao-ics | scripts/kalao_pump_switch.py | kalao_pump_switch.py | py | 907 | python | en | code | 0 | github-code | 36 |
26166182256 | from State import State
class Parser:
@staticmethod
def parse_state_space_file(file_path):
'''Parses state space file
Args:
file_path (string): String to state space file.
Returns:
tuple: (start_state, final_state, transition)
'''
state_sp... | dinogrgic1/fer-artificial-intelligence-labs | lab1py/Parser.py | Parser.py | py | 2,926 | python | en | code | 0 | github-code | 36 |
73387258343 | from datetime import datetime
from __init__ import db
from flask_login import UserMixin
from sqlalchemy.sql import func
class OrganizerEvent(db.Model):
id = db.Column(db.Integer, primary_key=True)
organizer_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
event_id = db.Column(db.Integ... | ntoghrul/Evento | models.py | models.py | py | 1,496 | python | en | code | 0 | github-code | 36 |
23420924440 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ventas', '0048_auto_20160928_0742'),
]
operations = [
migrations.AlterField(
model_name='comanda',
n... | pmmrpy/SIGB | ventas/migrations/0049_auto_20160930_1114.py | 0049_auto_20160930_1114.py | py | 2,096 | python | es | code | 0 | github-code | 36 |
6035944019 | import matplotlib.pyplot as plt
import pdb
import numpy as np
import csv
import time
def PlotDemo1(a, b):
a1 = []
b1 = []
a1 = a
b1 = b
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(a,b)
plt.show()
def PlotDemo(a,zero):
a1 = []
b1 = []
a1 = a
fig = plt.fi... | 2017wxyzwxyz/PythonStock | 获取当日数据并画分时图/画出走势图.py | 画出走势图.py | py | 1,976 | python | en | code | 0 | github-code | 36 |
9587889867 | import os
import csv
from decimal import Decimal
from forex_python.bitcoin import BtcConverter
from forex_python.converter import CurrencyRates
from plugin import plugin, require
FILE_PATH = os.path.abspath(os.path.dirname(__file__))
@require(network=True)
@plugin('currencyconv')
class Currencyconv():
"""
Co... | sukeesh/Jarvis | jarviscli/plugins/currency_conv.py | currency_conv.py | py | 2,657 | python | en | code | 2,765 | github-code | 36 |
11341872181 | with open('2022/3/input.txt') as file:
sacks = [sack.strip() for sack in file.readlines()]
priority = 'abcdefghijklmnopqrstuvwxyz'
priority += priority.upper()
priorities = []
for i in range(len(sacks) // 3):
group_sacks = sacks[3*i:3*i+3]
sack1 = group_sacks[0]
for item in sack1:
if item in g... | jimenezj8/advent_of_code | 2022/3/part2.py | part2.py | py | 460 | python | en | code | 0 | github-code | 36 |
16486666559 | # -*- coding: utf-8 -*-
from plone.app.contenttypes.testing import PLONE_APP_CONTENTTYPES_FIXTURE
from plone.app.robotframework.testing import REMOTE_LIBRARY_BUNDLE_FIXTURE
from plone.app.testing import applyProfile
from plone.app.testing import FunctionalTesting
from plone.app.testing import IntegrationTesting
from pl... | polklibrary/polklibrary.linkchecker | polklibrary.linkchecker/src/polklibrary/linkchecker/testing.py | testing.py | py | 1,639 | python | en | code | 0 | github-code | 36 |
37001010150 | def merge(s,e):
global cnt
if s == e:
return
mid = (s+e-1)//2
merge(s, mid)
merge(mid+1, e)
if arr[mid] > arr[e]:
cnt += 1
i, j, k = s, mid+1, s
while i <= mid and j <= e:
if arr[i] <= arr[j]:
temp[k] = arr[i]
i, k = i + 1, k + 1
... | ejuun/SWEA | swea0329_11891(분할정복_병합정렬).py | swea0329_11891(분할정복_병합정렬).py | py | 776 | python | en | code | 0 | github-code | 36 |
30526696470 | from __future__ import print_function, division
import os
import logging
import math
import numpy as np
import pandas as pd
import torch
from torch.utils.tensorboard import SummaryWriter
IS_ON_SERVER = False if os.getcwd().startswith('/home/SENSETIME/yuanjing1') else True
axis_name2np_dim = {
"x": 2,
"y": 1... | eugeneyuan/test_rep | src/utils/miscs.py | miscs.py | py | 6,820 | python | en | code | 0 | github-code | 36 |
19680151162 | import unittest
import tonal
import mingus.core.notes
from scales import SCALE_NAMES, TonalScale
import mingus.core.scales as scales
notes = mingus.core.notes
to = tonal.Tonal()
ts = TonalScale()
class TestTonal(unittest.TestCase):
def test_scale_octave(self):
self.assertEqual(12, to.add_octave(0, 1))
... | gabelev/machine_music | tonal_test.py | tonal_test.py | py | 964 | python | en | code | 28 | github-code | 36 |
8733726032 | import pygame
pygame.init()
__screen_info = pygame.display.Info()
__height = __screen_info.current_h
# Screen constants
SCREEN_SIZE = (__height / 7 * 6, __height - 64)
ICON_SIZE = (64, 64)
LEFT_BOUND = 0
RIGHT_BOUND = SCREEN_SIZE[0] - ICON_SIZE[0]
TOP_BOUND = 0
BOTTOM_BOUND = SCREEN_SIZE[1]
ALIEN_INVASION_BOUND = SC... | SimonValentino/SpaceInvaders | constants.py | constants.py | py | 3,409 | python | en | code | 0 | github-code | 36 |
70536840424 | '''
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the array words.
'''
class Solution(object):
def countConsistentStrings(self, allowed, ... | ChrisStewart132/LeetCode | 1684. Count the Number of Consistent Strings.py | 1684. Count the Number of Consistent Strings.py | py | 591 | python | en | code | 0 | github-code | 36 |
21213459172 | import csv
from django.db.models import Q
from django.http import HttpResponse
from data.models import (
List,
Pairing,
AOS,
BCP,
)
def raw_list(request, list_id):
list = List.objects.get(id=list_id)
return HttpResponse(list.raw_list.replace("\n", "<br>"))
def export_pairings_as_csv(reques... | Puciek/aos_tools | data/views.py | views.py | py | 4,349 | python | en | code | 0 | github-code | 36 |
6084393611 | # Check Permutation: Given two strings, write a method
# to decide if one is a permutation of the other
# we can sort both strings then compare if they are equal
# merge sort
def merge_sort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr) // 2
# Dividing the array ele... | phuclinh9802/data_structures_algorithms | chapter 1/1_2.py | 1_2.py | py | 1,834 | python | en | code | 0 | github-code | 36 |
70874370025 | import logging
from datetime import datetime
from typing import Generic, Text, Type, TypeVar
from uuid import UUID, uuid4
from injector import (
Injector,
UnknownProvider,
UnsatisfiedRequirement,
inject,
singleton,
)
from pydantic import BaseModel, Field
log = logging.getLogger(__name__)
class C... | lzukowski/workflow | src/application/bus.py | bus.py | py | 2,137 | python | en | code | 5 | github-code | 36 |
20407333579 | def kmp(pattern, text):
lps = [0] * len(pattern)
i, j = 0, 0
count = 0
lps = lpsarr(pattern, lps)
print(lps)
while i < len(text):
if text[i] == pattern[j]:
i += 1
j += 1
else:
if j!= 0 :
j = lps[j-1]
else:
... | Bishtman12/DSA---Python | String/KMP ALGO.py | KMP ALGO.py | py | 950 | python | en | code | 0 | github-code | 36 |
39395995067 | from aiogram.types import (
ReplyKeyboardMarkup,
InlineKeyboardMarkup,
InlineKeyboardButton,
)
main_buttons = {
"ask": "Спросить 🤖",
}
class Keyboard:
def __init__(self):
self.main = self.make_main_buttons()
def make_main_buttons(self):
_keyboard_main = ReplyKeyboardMarkup(r... | Devil666face/ChatGPTosBot | bot/keyboard.py | keyboard.py | py | 856 | python | en | code | 0 | github-code | 36 |
23012638929 | """
Script for labeling purposes
Usage :
python label_processing.py -d [PATH TO IMAGES FOLDER] [PARAMS]
Parameters:
-d : Path to the folder where the images is stored
-l : Lower all labels in xml files.
-c : Count each label of all the xml files
-s : Find images with specific label
-lm : Creat... | Hyuto/rangrang-ML | scripts/label_processing.py | label_processing.py | py | 5,474 | python | en | code | 0 | github-code | 36 |
74286571624 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# PYTHON_ARGCOMPLETE_OK
# Pass --help flag for help on command-line interface
import sympy as sp
import numpy as np
from pyneqsys.symbolic import SymbolicSys
def solve(guess_a, guess_b, power, solver='scipy'):
""" Constructs a pyneqsys.symbolic.SymbolicSys instanc... | bjodah/pyneqsys | examples/bi_dimensional.py | bi_dimensional.py | py | 2,055 | python | en | code | 38 | github-code | 36 |
10746701513 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/10/15 10:19 PM
# @Author: Zechen Li
# @File : aug.py.py
from glue.tasks import get_task
import pandas as pd
import numpy as np
import os
from augment.eda import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--alpha', default=0.... | UCSD-AI4H/SSReg | SSL-Reg-SATP/aug.py | aug.py | py | 2,685 | python | en | code | 8 | github-code | 36 |
14858436454 |
def get_input_lines():
return [line.strip() for line in open(0).readlines()]
def get_req():
# 12 red cubes, 13 green cubes, and 14 blue cubes
return {
'red':12,
'green':13,
'blue':14,
}
def main():
input_lines = get_input_lines()
req = get_req()
total = 0
for l... | balker0322/advent_of_code | 2023_day_02/part1.py | part1.py | py | 812 | python | en | code | 0 | github-code | 36 |
74646034024 |
from tkinter import *
from tkinter import messagebox
from tkColorPicker import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from tkinter import filedialog
from tkinter import scrolledtext
import fileinput
import os
class menuBar(object):
def __init__(self):
self.bgcol... | iospeng/python | pycharm_demo/demo/python/demo1/menuBar_text.py | menuBar_text.py | py | 5,132 | python | zh | code | 0 | github-code | 36 |
4767724527 | import os
#os.environ['GLOG_minloglevel'] = '2'
from tqdm import trange
import caffe
import argparse
import pandas as pd
def main(solver_proto, out_dir):
caffe.set_mode_gpu()
solver = caffe.SGDSolver(solver_proto)
train_loss, test_loss = [], []
test_loss.append(solver.test_nets[0].blobs['loss'].data.c... | alexkreimer/monocular-odometry | tools/solve.py | solve.py | py | 1,237 | python | en | code | 1 | github-code | 36 |
14145244822 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 22:29:57 2020
@author: b
https://www.kaggle.com/kanncaa1/data-sciencetutorial-for-beginners#1.-INTRODUCTION-TO-PYTHON
3.CLEANING DATA
DIAGNOSE DATA for CLEANING
We need to diagnose and clean data before exploring.
Unclean data:
Column name ... | b846/Data | 3a Python Melt Assert.py | 3a Python Melt Assert.py | py | 5,454 | python | en | code | 0 | github-code | 36 |
5547122437 | #!/local/cluster/bin/python
#biopython take three regions, invert middle, then put together
import sys
from Bio import SeqIO
strain=sys.argv[1]
#include 50 bp margin so as not to interrupt att site in rotated genome
largestart=int(sys.argv[2]) + 50
largeend=int(sys.argv[3]) - 50
infile="../" + strain + ".gbk"
outfile=... | osuchanglab/BradyrhizobiumGenomeArchitecture | remove_monopartite.py | remove_monopartite.py | py | 547 | python | en | code | 0 | github-code | 36 |
21723031249 | from simbolo import Simbolo, TOKENS, ZONA_DE_CODIGO, TIPO_DATO
from error import Error
import json
palabras_reservadas = [
'bool',
'call',
'char',
'do',
'else',
'float',
'for',
'function',
'if',
'int',
'main',
'read',
'return',
'string',
'then',
'to',
'void',
'while',
'write',
'... | AbrahamupSky/Compilador | lexico/lexico.py | lexico.py | py | 12,471 | python | es | code | 1 | github-code | 36 |
17887984325 | from PySide2.QtCore import QUrl, QObject, Slot
from PySide2.QtGui import QGuiApplication
from PySide2.QtQuick import QQuickView
class MyClass(QObject):
@Slot(int, result=str) # 声明为槽,输入参数为int类型,返回值为str类型
def returnValue(self, value):
return str(value + 10)
if __name__ == '__main__':
path = 's... | pyminer/pyminer | pyminer/widgets/widgets/basic/quick/demo1.py | demo1.py | py | 635 | python | en | code | 77 | github-code | 36 |
2153945744 | from django.shortcuts import render
product_price = {"라면":980,"홈런볼":1500,"칙촉":2300, "식빵":1800}
# Create your views here.
def price(request, thing, cnt):
if thing in product_price:
y_n = 'y'
price = product_price[thing]
else:
y_n = 'n'
price = 0
context = {
'y_n' : y... | ji-hyon/Web_study | Django/practice/part2_Django/django_2_1/project1/prices/views.py | views.py | py | 505 | python | en | code | 0 | github-code | 36 |
28536518861 | """project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | mechtron/coreys-image-classifier | api/project/urls.py | urls.py | py | 1,341 | python | en | code | 3 | github-code | 36 |
4308544287 | #!/usr/bin/env python3
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import rospy
from std_msgs.msg import UInt16
import os
from tensorflow.keras.models import load_model
def process_image(img_path):
img = load_img(img_path, target_size=(30, 30))
img = img_to_arra... | FitAdam/Package-TSR-Robot-Ros | script/signs_pub.py | signs_pub.py | py | 2,438 | python | en | code | 0 | github-code | 36 |
36955296199 | import wiredtiger, wttest, string, random, time
from wtbound import *
from enum import Enum
from wtscenario import make_scenarios
class operations(Enum):
UPSERT = 1
REMOVE = 2
TRUNCATE = 3
class key_states(Enum):
UPSERTED = 1
DELETED = 2
NONE = 3
class bound_scenarios(Enum):
NEXT = 1
... | mongodb/mongo | src/third_party/wiredtiger/test/suite/test_cursor_bound_fuzz.py | test_cursor_bound_fuzz.py | py | 27,014 | python | en | code | 24,670 | github-code | 36 |
6789488341 | from django.contrib import auth
from django.core.exceptions import ObjectDoesNotExist
from .models import Member
class EcosystemActivityMiddleware:
EXTENSIONS_EXCLUDED = ['js', 'map', 'css']
PATHS_EXCLUDED = ['/api/graphql-jwt']
def __init__(self, get_response):
self.get_response = get_response
... | tomasgarzon/exo-services | service-exo-core/ecosystem/middleware.py | middleware.py | py | 888 | python | en | code | 0 | github-code | 36 |
72743077225 | # ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# comment_magics: true
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# n... | nestauk/afs_neighbourhood_analysis | afs_neighbourhood_analysis/analysis/cluster_eda.py | cluster_eda.py | py | 14,185 | python | en | code | 0 | github-code | 36 |
42494180975 | """
WRITE ME
Tests for the R operator / L operator
For the list of op with r op defined, with or without missing test
see this file: doc/library/tensor/basic.txt
For function to automatically test your Rop implementation, look at
the docstring of the functions: check_mat_rop_lop, check_rop_lop,
check_nondiff_rop,
""... | Theano/Theano | theano/tests/test_rop.py | test_rop.py | py | 17,055 | python | en | code | 9,807 | github-code | 36 |
19406242010 | #
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# @lc code=start
# Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: Opt... | Matthewow/Leetcode | vscode_extension/24.swap-nodes-in-pairs.py | 24.swap-nodes-in-pairs.py | py | 772 | python | en | code | 2 | github-code | 36 |
26884869558 | import torch
from torch.utils.data import Dataset
import torch.utils.data.dataloader as dataloader
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from numpy.matlib import repmat
import math
MAX_LEN = 300
AUDIO_TYPE_ID = {'vowel-u': 0,'vowel-i': 1,'vowel-a': 2,'alph... | KalibrateBlockchain/VFO2 | version_1/models_def.py | models_def.py | py | 8,707 | python | en | code | 0 | github-code | 36 |
30180224626 | from flask import Flask, render_template, request, redirect
import datetime
app=Flask(__name__)
messages=[]
@app.route('/')
def index():
return render_template("index.html.jinja2", messages=messages)
@app.route('/post/add/', methods=['POST'])
def add_message():
text = request.form.get('message')
timesta... | haishengbao/website | app.py | app.py | py | 490 | python | en | code | 0 | github-code | 36 |
29277732322 | # QUESTION:
# In Hogwarts the currency is made up of galleon (G) and Sickle (s),
# and there are seven coins in general circulation:
# 1s, 5s, 10s, 25s, 50s, G1(100s), and G2(200s)
# It's possible to make G3.5 in the following way:
# 1xG2 +1xG1 + 4x10s +1x5s + 5x1s
# How many different ways can G3.5 be made using any ... | krissukoco/hogwarts-coins | main.py | main.py | py | 1,525 | python | en | code | 0 | github-code | 36 |
25114962700 | from flask import Flask
from flask_restful import Resource, Api
from flask_jwt_extended import JWTManager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from controler import *
app = Flask(__name__)
api = Api(app)
app.config['JWT_SECRET_KEY'] = 'qwejhfloimslvuywdkkvuhssss'
jwt = JWTMan... | VolodymyrVoloshyn02/PP | app.py | app.py | py | 1,882 | python | en | code | 0 | github-code | 36 |
1742330108 | import requests
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView
from .models import *
# Create your clas... | cysong12/COMP-2800-Team-DTC-14-Cominder | Apps/fridge/views.py | views.py | py | 3,201 | python | en | code | 0 | github-code | 36 |
23407025114 | # -*- coding: utf-8 -*-
"""
Department to Employee is One to Many.
解决方案:
有的时候 One to Many 对应的 Many 可能数量太多, 无法作为冗余跟 One 一起储存.
这时可以以 One.id 建立 Global Index.
问题:
由于 GSI 本质是另一个 DynamoDB Table, 只不过系统帮你自动维护了. 同样的 GSI 也会根据
hash key 做 partition 分散流量. 如果 One 这边的 entity 的数量不够多. 那么会导致 GSI
的流量不均衡.
"""
import os
import random... | MacHu-GWU/Dev-Exp-Share | docs/source/01-AWS/01-All-AWS-Services-Root/21-Database/01-DynamoDB-Root/04-Dynamodb-Data-Modeling/principal/one-to-many/strategy2.py | strategy2.py | py | 4,760 | python | en | code | 3 | github-code | 36 |
70064841385 | import sqlite3
from database.API import db_actions
import json
class AllChannels():
def __init__(self):
self.DBActions = db_actions.DBOtherActions()
def GetAllChannels(self):
self.DBActions.cursor.execute('''
SELECT * from channels;
''')
return self.objectify_channe... | OStillman/ODACShows | database/API/channels.py | channels.py | py | 1,812 | python | en | code | 0 | github-code | 36 |
72485218024 | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
from .apis import listings, users
from knox import views as knox_views
router = DefaultRouter()
router.register(r"users", users.UserViewSet, basename="users_api")
router.register(r"listings", listings.AuctionView... | pecodeliar/BayleeWeb | api/urls.py | urls.py | py | 1,160 | python | en | code | 0 | github-code | 36 |
42327126667 | """ There are many different ways of getting variables into your strings.
But the new f"" string beats them all (most of the time anyway).
"""
# Variables
age = 7
name = "Dean"
# All of the following strings will yield the same text - 'My name is Dean and I'm 7 years old.'
# They're just different ways of getting... | Honza-m/python-training | #python snippets/010 - New string formatting.py | 010 - New string formatting.py | py | 731 | python | en | code | 1 | github-code | 36 |
38221121523 | from itertools import permutations
def solution(k, dungeons):
answer = 0
per = list(permutations(dungeons, len(dungeons)))
for i in range(len(per)):
cnt = 0
copy_k = k
for j in range(len(per[i])):
if per[i][j][0] <= copy_k:
copy_k -= per[i][j][1]
... | kh-min7/Programmers | 87946(피로도).py | 87946(피로도).py | py | 411 | python | en | code | 0 | github-code | 36 |
25650877857 | import sqlite3
from sqlite3 import Error
def create_connection(path):
connection = None
try:
connection = sqlite3.connect(path)
print("Connection to SQLite DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
def connect_to_db():
return crea... | rezzco/portfo | shit.py | shit.py | py | 1,772 | python | en | code | 0 | github-code | 36 |
3853619553 | from Logger import Logger
from HTTPRequest import HTTPRequest
import urllib.request
class HTTPProxyRequest(HTTPRequest):
retry_limit = 5
_response = None
_proxy_manager = None
@staticmethod
def set_proxy_manager(proxy_manager):
HTTPProxyRequest._proxy_manager = proxy_manager
def read... | dsypniewski/allegro-profile-crawler | HTTPProxyRequest.py | HTTPProxyRequest.py | py | 1,359 | python | en | code | 0 | github-code | 36 |
36627705399 | import numpy as np
import random
from snake_no_visual import LearnSnake
import pickle
class SnakeQAgent():
def __init__(self):
# define initial parameters
self.discount_rate = 0.95
self.learning_rate = 0.01
self.eps = 1.0
self.eps_discount = 0.9992
self.min_eps = 0.0... | techtribeyt/snake-q-learning | snakeql.py | snakeql.py | py | 2,780 | python | en | code | 1 | github-code | 36 |
3896815670 | from datetime import timedelta
from pathlib import Path
import pytest
import htmap
from htmap.utils import timeout_to_seconds, wait_for_path_to_exist
def test_returns_when_path_does_exist():
path = Path(__file__)
wait_for_path_to_exist(path)
@pytest.mark.parametrize("timeout", [0, -1])
def test_timeout_o... | htcondor/htmap | tests/unit/test_wait_for_path_to_exist.py | test_wait_for_path_to_exist.py | py | 706 | python | en | code | 29 | github-code | 36 |
19795245501 | import json
import sys
from django.conf import settings
from django.utils import translation
from adapter.utils import build_auth_args
# from adapter.utils.local import get_request
from blueapps.utils import get_request
def _clean_auth_info_uin(auth_info):
if "uin" in auth_info:
# 混合云uin去掉第一位
if... | robert871126/bk-chatbot | adapter/api/modules/utils.py | utils.py | py | 3,445 | python | en | code | null | github-code | 36 |
4430013923 | '''Given a generic tree, find and return the height of given tree.
Sample Input 1:
10 3 20 30 40 2 40 50 0 0 0 0
Sample Output 1:
3
'''
import sys
import queue
class TreeNode :
def __init__(self, data) :
self.data = data
self.children = list()
def inputLevelWise(li) :
i = 0
data = li[... | Riyachauhan11/Python-learning-Concepts | Generic Trees/Height Of Tree.py | Height Of Tree.py | py | 1,184 | python | en | code | 0 | github-code | 36 |
304836991 | import tkinter as tk
import os.path
#ERROR MESSAGES
ERROR_NO_GAME_NAME = "Please enter a game name"
ERROR_ENTER_SOMETHING = "Please enter something"
ERROR_GAME_NAME_NOT_CHANGED = "Game name not changed"
#STANDARD MESSAGES
GAME_SELECTED = "Game selected"
SCORE_SEPARATOR = "/"
SCORE_RESET = "Score reset"
GAME_WON_VICTO... | LeSingeAffame/GameScoreCounter | counter.py | counter.py | py | 8,855 | python | en | code | 0 | github-code | 36 |
19031613616 | class Data:
dict={}
counter=0
counter2=0
counter3=0
index_dic=0
name_str=""
def __init__(self):
pass
def enter(self,key,value,flag):
for i in range(len(value)):
if value[i] not in 'ACTGactg':
if not flag:
retu... | RivkiZolti/DNA | Data.py | Data.py | py | 2,511 | python | en | code | 3 | github-code | 36 |
28924212361 | from typing import List
"""
method 1 : iterative call without for loop
"""
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
results = []
length = len(nums)
def make_dfs_subset(subset, cur_idx):
if cur_idx == length :
print("list:", subset... | GuSangmo/BOJ_practice | Leetcode/78.subsets.py | 78.subsets.py | py | 766 | python | en | code | 0 | github-code | 36 |
25293683614 | from django.shortcuts import render, redirect, reverse
from . import forms, models
from django.db.models import Sum
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.conf import settings
from ... | LiborSehnal/RichInsure | customer/views.py | views.py | py | 5,259 | python | en | code | 0 | github-code | 36 |
34097359425 | '''6. Calcular el máximo de números positivos introducidos por
teclado, sabiendo que metemos números hasta que
introduzcamos uno negativo. El negativo no cuenta.'''
number=int(input('Ingrese un numero positivo y 0 para terminar: '))
cont=0
while number!=0:
if number>0:
cont+=1
number=int(inp... | NOXDION/ADSO | 2T/3 Ciclos M3/6.CalcularMaximosPositivos.py | 6.CalcularMaximosPositivos.py | py | 420 | python | es | code | 0 | github-code | 36 |
30314652001 | # -*- coding: utf-8 -*-
"""
Created by Vincenzo Sammartano
email: v.sammartano@gmail.com
Last Update: Added the formulation section
"""
import numpy as num
import tkinter as tk
from tkinter import messagebox
from tkinter import font
import webbrowser
##########################################
#Constants
Rf = 287.05... | vicio1975/SkinFriction-HeadLoss | SkinFriction_Loss_4.pyw | SkinFriction_Loss_4.pyw | pyw | 23,967 | python | en | code | 5 | github-code | 36 |
21407967690 | import requests
'''
r = requests.get("http://www.google.com")
r.encoding = 'utf-8'
s = r.text
print(s)
'''
def getText(url):
try:
r = requests.get(url, timeout = 500)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "Erroroccur!"
if _... | zIDAedgen/crawlerAirbnb | venv/include/spider.py | spider.py | py | 402 | python | en | code | 0 | github-code | 36 |
178011559 | class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
def helper(A, l, h):
m = (l + h) // 2
if A[m] > max(A[m + 1], A[m - 1]):
return m
elif A[m] < A[m + 1]:
r... | iguy0/Data-Science-Toolbox | algorithm/binary_search/852_Peak_Index_in_a_Mountain_Array.py | 852_Peak_Index_in_a_Mountain_Array.py | py | 1,296 | python | en | code | null | github-code | 36 |
32657811309 | lista = []
for j in range(0, 10):
lista.append(input(f'Insira o numero {j + 1 } da lista: '))
i = 0
i2 = len(lista)
while True:
print(f'{lista[i]} -- {lista[i2 - 1]}')
i += 1
i2 -= 1
if (i2 == 0):
break
| caiovale1921/Estrutura-de-Dados | Lista-Exercicios-11-03-2022/Vetor/ex01.py | ex01.py | py | 243 | python | it | code | 0 | github-code | 36 |
2649303866 | import time
import scapy.all as scapy
from scapy.layers.l2 import ARP as ARP
from scapy.layers.l2 import Ether as Ether
def get_mac(ip):
arp_request = ARP(pdst=ip)
broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast / arp_request
answered_list = scapy.srp(arp_request_broadcast... | CrashNBurn1337/ArpSpoofer | arp_spoofing.py | arp_spoofing.py | py | 1,297 | python | en | code | 0 | github-code | 36 |
23243623755 | import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog
def load_correspondences(file_name):
try:
f = open(file_name, "r")
lines = f.readlines()
lines = [l.rstrip() for l in lines]
f.close()
points1 = []
points2 = []
for line in li... | marwansalem/image-stitching | correspondences.py | correspondences.py | py | 3,583 | python | en | code | 0 | github-code | 36 |
34160025736 |
from re import findall;
with open('Day_22_Input.txt') as file:
pattern = 'x\d+|y\d+|\d+T|\d+%';
grid = [[0 for j in range(33)] for i in range(30)];
for line in file:
data = findall(pattern, line.strip());
if len(data) != 0:
x = int(data[0][1:]);
y... | segloff23/Advent-of-Code-2016-Challenge | Day_022/Day_22_Part_2.py | Day_22_Part_2.py | py | 1,250 | python | en | code | 0 | github-code | 36 |
7625551099 | from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Edge(executable_path = r'Path of msedgedriver here')
url = "YOUTUBE URL HERE"
driver.get(url)
elem = driver.find_element_by_tag_name('html')
elem.send_keys(Keys.E... | Hiperultimate/Youtube-Playlist-Save-Title | youtubeListMaker.py | youtubeListMaker.py | py | 824 | python | en | code | 0 | github-code | 36 |
3147265908 | """
Common Flitter initialisation
"""
import logging
import sys
from loguru import logger
try:
import pyximport
pyximport.install()
except ImportError:
pass
LOGGING_LEVEL = "SUCCESS"
LOGGING_FORMAT = "{time:HH:mm:ss.SSS} {process}:{extra[shortname]:16s} | <level>{level}: {message}</level>"
class Logu... | jonathanhogg/flitter | src/flitter/__init__.py | __init__.py | py | 1,653 | python | en | code | 8 | github-code | 36 |
13712488384 | import os
from os.path import join
from os.path import dirname
import shutil
import sys
from threading import Thread
import time
import zmq
import yaml
def get_pyneal_scanner_test_paths():
""" Return a dictionary with relevant paths for the pyneal_scanner_tests
within the `tests` dir
"""
# set up dir... | jeffmacinnes/pyneal | tests/pyneal_scanner_tests/pynealScanner_helper_tools.py | pynealScanner_helper_tools.py | py | 5,196 | python | en | code | 30 | github-code | 36 |
34399989971 | from typing import List
from entity.MountAnimal import MountAnimal
class Camel(MountAnimal):
bent_quantity: int
def __init__(self, id: str, name: str, date_of_birth: str, commands: List[str], bent_quantity: int):
super().__init__(id, name, date_of_birth, commands)
self.bent_quantity ... | G0ncharovAA/GB_FINAL_TEST | app/entity/Camel.py | Camel.py | py | 1,030 | python | en | code | 0 | github-code | 36 |
6798954451 | import re
import datetime
from datetime import timedelta
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import Permission
from django.shortcuts import get_object_or_404
from exo_role.models import ExORole
from auth_uuid.jwt_helpers import _build_jwt
from auth_uuid.t... | tomasgarzon/exo-services | service-exo-opportunities/opportunities/tests/test_mixin.py | test_mixin.py | py | 5,626 | python | en | code | 0 | github-code | 36 |
6123602959 | import pandas as pd
from textslack.textslack import TextSlack
from gensim.models import doc2vec
# Architecture of the NLP Model
class NLPModel:
# The constructor instantiates all the variables that would be used throughout the class
def __init__(self, sp, conn, max_epochs=100, vec_size=50, alpha=0.025):
... | CUTR-at-USF/muser-data-analysis | AI/models.py | models.py | py | 2,575 | python | en | code | 0 | github-code | 36 |
4153153837 | import datetime
import difflib
import os
from inspect import isabstract
from typing import Any, List, Mapping, Optional, Set, Tuple, Type
import ee # type: ignore
from requests.structures import CaseInsensitiveDict
config_path = os.path.expanduser("~/.config/taskee.ini")
def initialize_earthengine() -> None:
"... | aazuspan/taskee | taskee/utils.py | utils.py | py | 3,865 | python | en | code | 10 | github-code | 36 |
36208541438 | from django.urls import path
from proyecto.views import index_proyecto, ProyectoCreate, ProyectoList, ProyectoUpdate, ProyectoDelete, proyecto_list_total
app_name = 'proyecto'
urlpatterns = [
path("", index_proyecto, name="index_proyecto"),
path("registrar/", ProyectoCreate.as_view(), name="registrar_proyecto... | joseiba/GestionSoftware | ProyectoIS2/Proyecto/proyecto/urls.py | urls.py | py | 636 | python | es | code | 0 | github-code | 36 |
28180715346 | from pathlib import Path
from .CUBEparser import parse_files
# yapf: disable
SHORTHAND_FUNCTIONALS = [
'svwn3',
'svwn5',
'pbe',
'pbe0',
'bpw91',
'bp86',
'b3p86',
'b3p86-g',
'blyp',
'b3lyp',
'b3lyp-g',
'olyp',
'kt1',
'kt2',
'kt3'
]
# yapf: enable
"""List of r... | MRChemSoft/mrchem | python/mrchem/helpers.py | helpers.py | py | 18,587 | python | en | code | 22 | github-code | 36 |
72911967144 | """The URL configuration of the application
When the particular URL is hit it feeds the request to the corresponding view.
"""
from django.urls import path
from django.views.generic import RedirectView
from .views import base, add_to_registry, validate_url, issue_registry, dashboard
urlpatterns = [
path('base/', ... | architsingh15/django-radius-github | issue_tracker/urls.py | urls.py | py | 585 | python | en | code | 1 | github-code | 36 |
38514393390 | """
This module contains functions to check whether a schedule is:
1. view-serializable
2. conflict-serializable
3. recoverable
4. avoids cascading aborts
5. strict
It also contains some nice functions to tabularize schedules into tex and draw
a conflict graph using matplotlib.
"""
from action im... | mwhittaker/serial | serial.py | serial.py | py | 13,575 | python | en | code | 2 | github-code | 36 |
5199805944 | from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from widgets.mixins import TextColorMixin
from utils.encoders import EncodeMethod, create_encoder
from strings import _
class EncodePage(QWidget, TextColorMixin):
def __init__(self, parent=None):
super(EncodePage, self).__init__(parent)
sel... | shuhari/DevToolbox | src/pages/py/encode_page.py | encode_page.py | py | 3,455 | python | en | code | 0 | github-code | 36 |
789669298 | import argparse
from experiment import Experiment
import Limited_GP
parser = argparse.ArgumentParser()
parser.add_argument('--number-of-batches', type=int, default=1)
parser.add_argument('--current-batch', type=int, default=1)
parser.add_argument('--budget', type=int, default=10000)
parser.add_argument('--suite-name',... | pfnet-research/limited-gp | solver/run.py | run.py | py | 564 | python | en | code | 5 | github-code | 36 |
3238091001 | import math
import numpy as np
import pandas as pd
def distance(point1,point2):
return math.sqrt(pow(point1[0] - point2[0], 2) + pow(point1[1] - point2[1], 2))
points = []
center_points = []
K = 0
file="D:\\experiment\\第三次豆瓣\\测试3\\train\\douban_train_zuobiao.csv"
data=pd.read_csv(file)
train_data = np.array(data... | JiaoZixun/Recommend_By_Canopy-K-means | recommend——豆瓣/step3———确定T值.py | step3———确定T值.py | py | 984 | python | en | code | 18 | github-code | 36 |
21535691646 |
def semantic_validity_factory(value, semantic_name, null_values=set(['Unspecified', 'N/A', '', 0, None]), **kwargs) :
if value in null_values:
return (None, None)
elif all(f(value) for name, f in kwargs.items() if 'semantic' in name):
if all(f(value) for name, f in kwargs.items() if 'valid' i... | charlesdguthrie/bigDataProject | scripts/semantic_validity_factory.py | semantic_validity_factory.py | py | 516 | python | en | code | 1 | github-code | 36 |
14432332319 | #from ast import If
#from pprint import pp
#from typing import final
from genericpath import exists
from multiprocessing.reduction import duplicate
import re
import string
from unittest import result
from tokens import tokens
from tkinter import *
from tkinter import messagebox as MessageBox
from tkinter import message... | AngelHernandez20/Mantenimiento | analizadorlexico.py | analizadorlexico.py | py | 2,210 | python | pt | code | 0 | github-code | 36 |
484991740 |
# features - word cnt, character cnt, sentence cnt, word freq
import sys
import time
import json
import string
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
import numpy as np
import pandas as pd
porter = PorterStemmer()
stop_words = set(stopwords... | AparAhuja/Machine_Learning | Naive Bayes and SVM/Q1/e.py | e.py | py | 6,378 | python | en | code | 0 | github-code | 36 |
23984522321 | def adde():
id = "id"
name = input('Employee Name : ')
lname = input('Employee Last Name')
email = input('Employee Email')
phone = input('Employee Phone Number :')
address = input('Employee Address :')
salary = input('Employee salary')
c_det = (id, name, lname, email, phone, addr... | hsvac/HR_aplication | vladislav_donea.py | vladislav_donea.py | py | 6,253 | python | en | code | 0 | github-code | 36 |
19352159399 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
def read_file(file_name):
with open(file_name, "r") as f:
return f.read()
setuptools.setup(
name="influx-line-protocol",
description="Implementation of influxdata line protocol format in python",
long_desc... | SebastianCzoch/influx-line-protocol | setup.py | setup.py | py | 879 | python | en | code | 20 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.