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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
30223581161 | # Time Complexity:O(n) for linear or sequential search as it traverse through all elements
def linear_search(list, item):
for x in range(len(list)):
if list[x] == item:
return x
return None
def main():
my_array = [1, 2, 3, 4, 5, 6, 7, 10, 45, 869, 32, 44, 22, 55]
print(linear_searc... | rushad01/python-practice | algorithms/linear_search.py | linear_search.py | py | 416 | python | en | code | 0 | github-code | 1 |
71555251875 | import math
from src.VAR import Var
from src.VAR_distance import Var_distance
from scipy.spatial import distance
class Grangercalculator_distance:
def __init__(self, df, lag):
self.df = df
self.lag = lag
def GC_calculator(self, bi_pairs, W, tau):
distances = []
tau_exp = mat... | SanderBos1/Thesis | src/GC_calculation_distance.py | GC_calculation_distance.py | py | 1,884 | python | en | code | 0 | github-code | 1 |
4738835983 | # services/tienda/project/api/tienda.py
from flask import Blueprint, jsonify, request, render_template
from project.api.models import Tienda
from project import db
from sqlalchemy import exc
tienda_blueprint = Blueprint('tienda', __name__, template_folder='./templates')
@tienda_blueprint.route('/tienda/ping', me... | danilomorales/tienda-app | services/tienda/project/api/tienda.py | tienda.py | py | 3,483 | python | es | code | 0 | github-code | 1 |
40848481289 | def findPeakElement(nums):
if nums[0]>nums[1]:
return 0
if nums[-1]>nums[-2]:
return len(nums)-1
left = 1
right = len(nums)-2
while left<=right:
mid = (left+ right)//2
if nums[mid]>nums[mid-1] and nums[mid]>nums[mid+1]:
return mid
elif nums[... | tpark49/DSA_problems- | 162.py | 162.py | py | 496 | python | en | code | 0 | github-code | 1 |
29372890358 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
# Miles to kilometer
# 1mile = 1.6km
mls=float(input("Enter miles"))
km= 1.6*mls
print(mls ,"miles is" ,km,"km" )
# In[15]:
# checking leap year
# Number should be completely divided by 4, centuries should be completely divided by 4
year = int(input("Enter a year:... | Vyom20798/Vyom20798 | Easy questions.py | Easy questions.py | py | 993 | python | en | code | 0 | github-code | 1 |
3071630471 | # 필요한 숫자들의 개수의 최댓값이 필요한 세트의 개수이다.
# 6과 9는 대체될 수 있으므로, 나올때마다 0.5씩 한 쪽에만 더해주면 된다.
from math import ceil
n = input()
cntOfNeededNums = {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0}
pair = ("6", "9")
for num in n:
if num in pair:
cntOfNeededNums["6"] += 0.5
else:
cntOfNe... | changwoolab/Algorithm | BOJ_Answers/1475.py | 1475.py | py | 483 | python | ko | code | 2 | github-code | 1 |
74229130912 | from typing import Optional
# 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 = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
... | TimHung000/leetcode | 0701_insertIntoABinarySearchTree/main.py | main.py | py | 1,158 | python | en | code | 0 | github-code | 1 |
13391269308 | import re
from graia.ariadne import Ariadne
from graia.ariadne.event.message import (
GroupMessage,
FriendMessage,
MessageEvent,
)
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.parser.twilight import (
Twilight,
UnionMatch,
FullMatch,
RegexResult,
Wildc... | ProjectNu11/NullPlugins | HexToText/__init__.py | __init__.py | py | 1,494 | python | en | code | 6 | github-code | 1 |
36427178633 | """
15. 3Sum
Medium
4048
463
Favorite
Share
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums =... | fengyang95/OJ | LeetCode/python3/15_3Sum.py | 15_3Sum.py | py | 1,852 | python | en | code | 2 | github-code | 1 |
71728267235 | #!/usr/bin/env python
# coding: utf-8
# import
import os
import numpy as np
import tensorflow as tf
from models import simple_CNN
from keras.callbacks import EarlyStopping, ModelCheckpoint, CSVLogger, TensorBoard
import matplotlib.pyplot as plt
init = tf.global_variables_initializer()
config = tf.ConfigPr... | menhai/ANALYSIS-OF-STABILOMETRIC-DATA | train.py | train.py | py | 2,129 | python | en | code | 0 | github-code | 1 |
16723479999 | import random
def roll_dice():
numbers = ''
for i in range(1, 7):
numbers += str(i)
selected_num = (random.choice(numbers))
print(f'Your dice is rolling! You got: {selected_num}')
roll_dice()
| satu06/pythonworld | Dice Roll/dice.py | dice.py | py | 230 | python | en | code | 0 | github-code | 1 |
266936940 | # Clean the experiment directory so you can start fresh.
import sys
sys.path.insert(0,'./')
import shutil
import os
import subprocess
from set_parameters import Options
from coupling_utils import copy_ua_restart
# Function to clean the given Ua executable directory
def clean_ua (directory):
restart_name = None
... | knaughten/UaMITgcm | coupling/clean.py | clean.py | py | 2,541 | python | en | code | 3 | github-code | 1 |
32918049245 | import logging
import time
import dataset
import discord
from discord import Member
from discord.ext import commands
from cogs.commands import settings
from utils import database, embeds
# Enabling logs
log = logging.getLogger(__name__)
class MutesHandler(commands.Cog):
"""Handles actions such as mute evasion.... | richtan/chiya | cogs/listeners/mutes_handle.py | mutes_handle.py | py | 3,224 | python | en | code | null | github-code | 1 |
75207759392 | '''
通过解析xml文件,批量修改xml文件里的标签名称,比如把标签zero改成num
'''
import os.path
import glob
import xml.etree.ElementTree as ET
path = r'数据集\Annotations' #存储标签的路径,修改为自己的Annotations标签路径
sum3 = 0
for xml_file in glob.glob(path + '/*.xml'):
####### 返回解析树
tree = ET.parse(xml_file)
##########获取根节点
root = tree.getr... | cccccccyyyyyyyyy/shiny-waddle | xcyxmlchange.py | xcyxmlchange.py | py | 1,283 | python | zh | code | 0 | github-code | 1 |
36565638138 | """
Created on Tue Oct 23 03:00:14 2018
@author: Rahul
"""
import numpy as np
import pandas as pd
import math
import random
import datetime
from logging import info
from .constant import STOCK_LIST
WILLIAM_K_UL = -80
WILLIAM_K_LL = -20
A = [
{'sector' : 'Mining', 'stock' : 'ABIRLANUVO'},
{'sector' : 'Computers', 'st... | rahulspsec/StockScreenerSite | StockScreenerSite/stockscreener/StockScreenerUtility/StockScreener.py | StockScreener.py | py | 14,224 | python | en | code | 0 | github-code | 1 |
30655627614 | money = 0
def add():
for i in range(1000000):
global money
lock.acquire()
money += 1
lock.release()
def reduce():
for i in range(1000000):
global money
lock.acquire()
money -= 1
lock.release()
if __name__ == '__main__':
from threading i... | lvah/201903python | day20/09_共享数据.py | 09_共享数据.py | py | 567 | python | en | code | 5 | github-code | 1 |
72199681314 | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute... | aidanby/JARVIS-MUSIC | google-cloud-sdk/lib/surface/compute/networks/subnets/create.py | create.py | py | 8,803 | python | en | code | 5 | github-code | 1 |
35341136686 | from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.blog_list, name='blog-list'),
path('article/<int:id>/', views.blog_detail, name='blog-detail'),
path('add-article/', views.add_article, name='add-article'),
path('confirm-add-article/', views.con... | javadsalman/k111-blog-project | blog/urls.py | urls.py | py | 736 | python | en | code | 0 | github-code | 1 |
9609670000 | # Print "Type "play" to play the game, "exit" to quit:" when game starts
# - Start game if user types "play"
# - Do nothing if user types "exit"
# - Print message again if user types anything else
# Print "Type "play" to play the game, "exit" to quit:" when game end
import random as r
def play_game():
list_of_o... | HemlockBane/hangman | hangman.py | hangman.py | py | 2,516 | python | en | code | 0 | github-code | 1 |
8556855206 | __author__ = 'Marcelo Ferreira da Costa Gomes'
import sys
import logging
import pandas as pd
import numpy as np
import random
from .episem import lastepiweek, epiweek2date
module_logger = logging.getLogger('update_system.delay_table')
def extract_quantile(dforig=pd.DataFrame, filtertype='srag'):
if filtertype n... | FluVigilanciaBR/seasonality | methods/data_filter/delay_table.py | delay_table.py | py | 9,005 | python | en | code | 1 | github-code | 1 |
32629544059 | import rospy, time
from sensor_msgs.msg import LaserScan
TOPIC_scan_nomap = '/scan_nomap'
class AugmentedResolutionScan(object):
def __init__(self):
self.scan_pub = rospy.Publisher("/scan_nomap_augmented", LaserScan, queue_size=1)
self.max_scan_range = 10.0
def ScanPub(self):
rospy.... | metmatera/master_thesis_marrtino_apps | laser/scan_augment_resolution.py | scan_augment_resolution.py | py | 1,724 | python | en | code | 0 | github-code | 1 |
26957711514 | import random
import string
words = ['coffee', 'approach', 'advance', 'message', 'edition', 'attachment', 'receipt', 'mouth', 'degree', 'license',
'retreat', 'concert', 'acquaintance', 'measure', 'kitchen', 'pool', 'chain', 'swell', 'call', 'crash', ]
word = random.choice(words)
guessed_word = ['_' for cha... | grayblackcode/Hangman-Game | HangmanGame.py | HangmanGame.py | py | 1,954 | python | en | code | 0 | github-code | 1 |
10613171903 | t = int(input())
answer = list()
for i in range(1, t+1):
alpha = list(input().rstrip())
alpha.sort()
idx = 0
res = list()
while idx < len(alpha):
if idx < len(alpha) - 1 and alpha[idx] == alpha[idx+1]:
idx += 2
continue
else:
res.append(alpha[idx... | lkc263/Algorithm_Study_Python | swexpert/10912.py | 10912.py | py | 459 | python | en | code | 0 | github-code | 1 |
11647920658 | import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
import sys
import random
import urllib.request
import json
engine = pyttsx3.init('sapi5')
voices = engine.ge... | BishalKumarSingh/Desktop_Assistant | Jarvis.py | Jarvis.py | py | 4,633 | python | en | code | 0 | github-code | 1 |
32058618637 | import time
import os
import sys
model_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], '../../')
sys.path.append(model_dir)
from dianping.utils.mongodb_utils import get_db
from dianping.utils import load_cities, load_shops
if __name__ == "__main__":
format = '%Y-%m-%d-%H-%M-%S'
current = tim... | djangommq/dianping | dianping/utils/statistics_shop.py | statistics_shop.py | py | 1,351 | python | en | code | 3 | github-code | 1 |
8039560044 | import time
import telebot
from telebot import types
import base
bot = telebot.TeleBot('5194270771:AAF2zvg8MEBgCjOusmaIyX6u4yF7X_CtmCw')
#bot = telebot.TeleBot('5188999206:AAFDzoHQCE6_YTsAxTA8hlhJD4M2tPXyVh4') #dev
bd = base.Base("localhost")
@bot.message_handler(commands=['start'])
def start(message):
print(m... | UzorStudio/exchenge | tgBot.py | tgBot.py | py | 2,051 | python | en | code | 0 | github-code | 1 |
19116501223 | import time
import bot_core as lcmbotcore
from director import lcmUtils
from director import applogic
from director.visualization import updateText
from drake.tools.workspace.drake_visualizer.plugin import scoped_singleton_func
class TimeVisualizer(object):
def __init__(self):
self._name = "Time Visual... | GTLIDAR/safe-nav-locomotion | motion_planner/drake/tools/workspace/drake_visualizer/plugin/show_time.py | show_time.py | py | 2,314 | python | en | code | 21 | github-code | 1 |
13857010706 | from bs4 import BeautifulSoup
import requests
import urllib.parse
import json
from discord.ext import commands
class CodInGame(commands.Cog):
def __init__(self,config, bot: commands.Bot):
self.bot = bot
self.config = config
@commands.command()
async def gofish(self, ctx):
u... | JeppeLovstad/Discord-Meme-Delivery-Bot | BotModules/codingame.py | codingame.py | py | 1,196 | python | en | code | 0 | github-code | 1 |
23808835097 | import pandas as pd
from scipy.sparse.construct import rand
from sklearn.linear_model import Ridge
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
#import matplotlib.pyplot as plt
from sklearn import metrics
import os
from sklearn import tree
from sklearn.externals im... | sandeep7/Food_delivery_time | train.py | train.py | py | 4,660 | python | en | code | 0 | github-code | 1 |
8499870149 | import random
import matplotlib.pyplot as plt
import numpy as np
class bandit:
def __init__(self, arm_num):
self.arms = []
for _ in range(arm_num):
arm = {'mean': random.gauss(0, 1), 'std': 1}
self.arms.append(arm)
def reset(self, random_walk_std):
for i in ran... | Ja1r0/RL-an-introduction-exercise | Capter 2/Figure 2-4.py | Figure 2-4.py | py | 4,156 | python | en | code | 0 | github-code | 1 |
37715080612 | #!/bin/python3
"""
Basic code for learning Python
Problem 22 - Designer Door Mat
(https://www.hackerrank.com/challenges/designer-door-mat/)
"""
if __name__ == '__main__':
l = input().split()
m = int(l[0])
n = m * 3
lines = []
above_center_line = (m // 2)
for i in range(1, above_center_line... | rustnnes/HackerRank | python/p22.py | p22.py | py | 580 | python | en | code | 1 | github-code | 1 |
38177507754 | import os
import csv
import time
import psutil
import traceback
import subprocess
import multiprocessing
from PySide6.QtCore import *
from param import *
from utils import *
from process import *
from gridbox import *
from backend import *
from prepare import *
__all__ = ['AutodockWorker', 'AutodockVinaWorker', 'Qui... | lmdu/dockey | src/worker.py | worker.py | py | 19,170 | python | en | code | 32 | github-code | 1 |
8819603725 | import torch
import torch.nn as nn
from Networks.Transformer_Encoder import TransformerEncoderLayer, TransformerEncoder
from Networks.Transformer_decoder import TransformerDecoderLayer, TransformerDecoder
from Networks.FiLM import Model as Model_Film
from Networks.Informer import Model
from Networks.wavenet impor... | YXING-CC/Dark-Light | Networks/Generators.py | Generators.py | py | 8,766 | python | en | code | 0 | github-code | 1 |
25103319583 | import logging
from egtsdebugger.egts import *
import socket
class RnisConnector:
"""Provide functional for connecting to RNIS"""
def __init__(self, host, port, num, dispatcher, file, **kwargs):
self.host = host
self.port = port
self.num = 0
self.max = num
self.did = di... | SatisSoft/egts-debugger | rnis_connector.py | rnis_connector.py | py | 4,475 | python | en | code | 1 | github-code | 1 |
1392454468 | import torch
import torchtext
from src.models.conversational.checkpoint import Checkpoint
from src.models.conversational.emotion_dialogue_dataset import UTTERANCE_FIELD_NAME, RESPONSE_FIELD_NAME, \
EMOTION_FIELD_NAME
from src.models.conversational.emotion_model import EmotionSeq2seq, EmotionTopKDecoder
from src.mo... | Neronuser/EmoCourseChat | src/models/conversational/emotion_trainer.py | emotion_trainer.py | py | 6,845 | python | en | code | 1 | github-code | 1 |
39869800287 | from tkinter import *
from tkinter import ttk #theme of tk
from tkinter import messagebox
from money import *
from info import *
from study import *
GUI = Tk()
GUI.title('โปรแกรมบันทึกข้อมูล')
GUI.geometry('500x400')
L1 = Label(GUI,text='Account Info',fg='blue')
L1.pack(ipadx=10,ipady=20)
def Info():
... | poppy166/python101 | test04_module/test_tk_hw02.py | test_tk_hw02.py | py | 1,790 | python | th | code | 0 | github-code | 1 |
2524005655 | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib._png as png
import numpy as np
import cv2
np.seterr(divide='ignore', invalid='ignore')
def region_of_interest(img, vertices):
# Define a blank matrix that matches the image height/width.
mask = np.zeros_like(img)
# Retriev... | ghazalsaf/mobNavigation | road_detect2.py | road_detect2.py | py | 4,234 | python | en | code | 0 | github-code | 1 |
72112054114 | import argparse
import sys
from pathlib import Path
from tokenizer import JackTokenizer
from compilation_engine import CompilationEngine
JACK = '.jack'
XML = '.xml'
VM = '.vm'
def compile(file_name, analyze):
vm_name = file_name.parent.joinpath(file_name.stem + VM)
xml_name = file_name.parent.joinpath(file_n... | akaps/nand2tetris | projects/project_10/JackCompiler.py | JackCompiler.py | py | 1,477 | python | en | code | 0 | github-code | 1 |
18276494920 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 号码相关
# 号段解析,号码类型解析
# 号码RN生成
#
from neko import color_str, MySQL
import os,sys
class Number:
def __init__(self, mysql_exe_fun, number):
self.execute = mysql_exe_fun
self.number = number
def __del__(self):
pass
@property
def section(self):
prev_exe_number... | sudaning/Ftest | scripts/script/number.py | number.py | py | 8,375 | python | en | code | 2 | github-code | 1 |
28860200568 | # 怎样在一个序列上面保持元素顺序的同时消除重复的值?
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
a = [1, 5, 2, 1, 9, 1, 5, 10]
print(list(dedupe(a))) # [1, 5, 2, 9, 10]
# 这个方法仅仅在序列中元素为 hashable 的时候才管用。
# 如果你想消除元素不可哈希(比如 dict 类型)的序列中... | congshanru/Tutorial | 1.10删除序列相同元素并保持顺序.py | 1.10删除序列相同元素并保持顺序.py | py | 1,465 | python | zh | code | 0 | github-code | 1 |
8904685658 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import json
class Metadata:
def __init__(self):
self._meta = None
def set(self, pAttribute, pValue):
d = {pAttribute : pValue}
s = json.dumps(d)
if self._meta is None:
self._meta = {}
self._meta[pAttribute] = pValue
... | CogComp/NLP-Multipackage-Demo | backend/texas/core/Metadata.py | Metadata.py | py | 1,365 | python | en | code | 1 | github-code | 1 |
11393567802 | import tensorflow as tf
import pandas as pd
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import cv2
import time
import matplotlib.pyplot as plt
##cap = cv2.VideoCapture(1)
##ret, frame = cap.read()
images = []
##while True:
## ret, frame = cap.read()
##
## cv2.imshow('frame', f... | Jedite/TensorFlow | HandGestures/NearestNeighbor/NearestNeighbor.py | NearestNeighbor.py | py | 2,800 | python | en | code | 0 | github-code | 1 |
28123538513 | from mythril.laser.ethereum.state.annotation import (
StateAnnotation,
MergeableStateAnnotation,
)
from copy import copy
from typing import Dict, List, Set
import logging
import json
from collections import namedtuple
log = logging.getLogger(__name__)
class MutationAnnotation(StateAnnotation):
"""Muta... | rjx18/mythril | mythril/laser/plugin/plugins/plugin_annotations.py | plugin_annotations.py | py | 9,835 | python | en | code | 0 | github-code | 1 |
43009482204 | # THE FOLLOWING LIST CONTAINS THE UNITS OF THE INGREDIENTS
units = ['cups', 'tablespoons', '', 'cups',
'teaspoons', 'teaspoons', 'slices', '']
# THE FOLLOWING LIST CONTAINS THE NAMES OF THE INGREDIENTS
ingredients = ['flour', 'sugar', 'eggs', 'milk',
'cinnamon', 'baking powder', 'bread', ... | CaribbeanCool/Recipe_Book | Phase4.py | Phase4.py | py | 6,579 | python | en | code | 0 | github-code | 1 |
11711168032 | import pandas as pd
import pickle
import datetime
import sys
from nltk.metrics import edit_distance
from siuba import *
from siuba.dply.vector import row_number
needs_to_be_matched = pickle.load(open("../data/manual_cleaning/needs_to_by_joined_wip.p", "rb"))
new_songs = pickle.load(open("../data/data2.p", "rb"))
# Re... | bakera81/itunesutils | python/search_for_matches.py | search_for_matches.py | py | 7,409 | python | en | code | 0 | github-code | 1 |
15496264249 | from hpp.corbaserver.rbprm.rbprmbuilder import Builder
from hpp.corbaserver.rbprm.rbprmfullbody import FullBody
from hpp.gepetto import Viewer
import time
from constraint_to_dae import *
from hpp.corbaserver.rbprm.rbprmstate import State,StateHelper
from hpp.corbaserver.rbprm.tools.display_tools import *
import flatGro... | humanoid-path-planner/hpp-rbprm-corba | script/dynamic/flatGround_hrp2_interpSTATIC_testTransition.py | flatGround_hrp2_interpSTATIC_testTransition.py | py | 12,261 | python | en | code | 3 | github-code | 1 |
25588409878 | from django.shortcuts import render
from django.views.generic import ListView
from acheve_mgt.models import Student, MyClass, ScoreShip, Course
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
# Create your views here.
@login_required
def person(request, pk):
user = r... | liuqiao1995/stu_mgt | apps/acheve_mgt/views.py | views.py | py | 6,981 | python | en | code | 0 | github-code | 1 |
15744201729 |
# header files
import numpy as np
import tensorflow as tf
inputList=[]
# function to make indexing
def convertToOneHotVector(dataPointIndex, vocabularySize):
temp = np.zeros(vocabularySize) # 1 vector of vocabularySize * 1
temp[dataPointIndex] = 1
return temp
def functionToCalculate(sentence):
#c... | rizveeredwan/CSEDU | CSE-3205[MFCS]/MFCS_Project_BN_sentiment_analysis/implementation/GeneralWord2Vec.py | GeneralWord2Vec.py | py | 3,524 | python | en | code | 0 | github-code | 1 |
42838147863 | import heapq
import nltk
import numpy as np
def tfIdf(intents):
dataset = []
for intent in intents:
dataset.append(' '.join(intent["patterns"]))
word2count = {}
for data in dataset:
words = nltk.word_tokenize(data)
for word in words:
if word not in word2count.keys(... | arduini-eduarda/Pos-MachineLearning | Src/DataProcessing/TfIdf.py | TfIdf.py | py | 3,701 | python | en | code | 0 | github-code | 1 |
7922606907 | import matplotlib.pyplot as plt
def show_graphics(result_list1, list1_tag,
result_list2, list2_tag,
common_tag):
fig, axes = plt.subplots(2, sharex=True, figsize=(10, 5))
fig.suptitle('Resultados')
axes[0].set_ylabel(list1_tag, fontsize=12)
axes[0].plot(result_lis... | JulianSalinas/carrots-finder | tec/ic/ia/pc2/model/graph_utils.py | graph_utils.py | py | 468 | python | fa | code | 0 | github-code | 1 |
11411241005 | """Test logging utils."""
import logging
import re
import pytest
import youtube_monitor_action.__main__
@pytest.fixture()
def _setup_logger(mocker, tmp_path):
logger = logging.getLogger("test_logger")
mocker.patch.object(youtube_monitor_action.__main__, "_MODULE_LOGGER", logger)
youtube_monitor_action._... | mshafer1/youtube_monitor_action | tests/test_loggin_utils.py | test_loggin_utils.py | py | 2,117 | python | en | code | 0 | github-code | 1 |
39998799154 | import dill
import pickle
from heppy.utils.diclist import diclist
class Counter(diclist):
def __init__(self, name):
self.name = name
super(Counter, self).__init__()
def register(self, level):
self.add( level, [level, 0] )
def inc(self, level, nentries=1):
'''Call ... | cbernet/heppy | heppy/statistics/counter.py | counter.py | py | 3,535 | python | en | code | 9 | github-code | 1 |
32539547598 | # A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# create dict
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 40
}
# use a constructor
# person_1 = dict(first_name='Jane', last_name='Doe', age=30)
# get value
print(person['first_name'])
print(p... | Swappea/python-crash-course | src/dictionaries.py | dictionaries.py | py | 924 | python | en | code | 0 | github-code | 1 |
19067045748 | import time
import urllib.request
import json
import os
from enum import Enum
import numpy as np
import pandas as pd
import ast
GRASS_HOPPER_KEY = 'fc4feee8-6646-46a1-a480-ad2a14f094c2'
class SORT_BY(Enum):
haversine_distance = 1
Distance = 2
Time = 3
Risk = 4
POIScore = 5
class ROUTE_FROM(Enum... | techGIAN/Risk-Based-Trip-Recommender | utilityMethods.py | utilityMethods.py | py | 7,577 | python | en | code | 0 | github-code | 1 |
16295874822 | # Databricks notebook source
from pyspark.sql.functions import col, count, isnull, when
# COMMAND ----------
def remove_duplicates(table):
"""
Removes duplicate rows from table
Parameters:
----------
table : Pyspark Dataframe(pyspark.sql.dataframe.DataFrame)
Name of the dataframe
Ret... | SoumyaAkunoori/GitActionsDemo | databricks/databricks/tpc_ds/de_workload/enriched/rdbms/sales/historical/Data_Cleaning_utils.py | Data_Cleaning_utils.py | py | 2,484 | python | en | code | 0 | github-code | 1 |
74588081952 | import os
import sys
import openai
import requests
from uni_kie.models.model import LargeLanguageModel
from uni_kie.prompts.prompts import STOP_KEY
class GPT3_Davinci(LargeLanguageModel):
def __init__(self):
super().__init__()
# openai.api_key = os.getenv("OPENAI_TOKEN")
# we are subtra... | ivo-1/bachelor-thesis | uni_kie/models/gpt.py | gpt.py | py | 3,238 | python | en | code | 0 | github-code | 1 |
10255627866 | import torch.nn as nn
import torch
from .linear_net import LinearNet
class LPDiscriminator(nn.Module):
def __init__(self, light_num, lp_dim, ndf):
super(LPDiscriminator,self).__init__()
self.linear = LinearNet(light_num, lp_dim)
# 256 x 256
self.layer1 = nn.Sequential(nn.Conv2d(l... | xuxmin/NeuralTexture_gan | core/models/lp_discriminator.py | lp_discriminator.py | py | 1,978 | python | en | code | 1 | github-code | 1 |
41935303161 | from django import forms
class FirebaseUploadWidget(forms.TextInput):
template_name = 'base/widgets/firebase-upload-widget.html'
class Media:
js = (
'https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js',
'https://www.gstatic.com/firebasejs/7.8.1/firebase-storage.js',
... | Benbb96/benbb96-website | base/widgets.py | widgets.py | py | 719 | python | en | code | 1 | github-code | 1 |
73207285794 | # Basic imports --------------------------------------------
from __future__ import annotations
import sys
# 파이썬 기본 재귀 limit이 1000이라고 함 --> 10^6으로 manual하게 설정
sys.setrecursionlimit(10**6)
from os.path import dirname, abspath, basename, normpath ... | etture/algorithms_practice | leetcode/google_prep/arrays_and_strings/3_rotate_image.py | 3_rotate_image.py | py | 1,934 | python | en | code | 0 | github-code | 1 |
12071969574 | # Databricks notebook source
# MAGIC %md
# MAGIC # CSR reports
# MAGIC
# MAGIC Any large scale organisation is now facing tremendous pressure from their shareholders to disclose more information about their environmental, social and governance strategies. Typically released on their websites on a yearly basis as a for... | claudiomirti/esg-scoring | 01_esg_report.py | 01_esg_report.py | py | 22,529 | python | en | code | 6 | github-code | 1 |
26375743384 | from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton
import sys
from random import choice
window_titles = [
'My App',
'My App',
'Still My App',
'Still My App',
'What on earth',
'What on earth',
'This is surprising',
'This is surprising',
'Something went wrong'
]
# ... | BigMoonTech/GuiTutorials | SlotsAndSignals/03_changing_ui.py | 03_changing_ui.py | py | 1,916 | python | en | code | 0 | github-code | 1 |
38639063239 | """
Find when the difference between ensembles of different precision is
significant.
"""
import matplotlib.pyplot as plt
import iris
import iris.quickplot as qplt
from iris.analysis import MEAN
from myscripts.statistics import rms_diff
from myscripts.models.speedy import datadir
def main():
# Parameters
path... | leosaffin/scripts | myscripts/projects/ithaca/precision_errors/ensembles.py | ensembles.py | py | 1,150 | python | en | code | 2 | github-code | 1 |
26194787166 | import sys
input = sys.stdin.readline
for _ in range(int(input())):
k, f = int(input()), list(map(int, input().split()))
prefix_sum = [0] * (k + 1)
for i in range(k):
prefix_sum[i + 1] = prefix_sum[i] + f[i]
dp = [[0] * (k + 1) for _ in range(k + 1)]
for i in range(2, k +... | sinryuji/algorithm | 백준/Gold/11066. 파일 합치기/파일 합치기.py | 파일 합치기.py | py | 533 | python | en | code | 0 | github-code | 1 |
22704557894 | import tqdm
import pickle
import torch
from torch.utils.data import DataLoader
import sentencepiece as spm
from custom_dataset import CustomDataset
from models.rnn.model import Encoder, NMTDecoder, StylizedNMT
from loss import ce_loss
# os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
torch.cuda.empty_cache()
torch.autogr... | TrellixVulnTeam/kcc_7NVH | models/rnn/test.py | test.py | py | 4,423 | python | en | code | 0 | github-code | 1 |
70039834274 | import pygame
world_size = (1600, 768 + 64)
import random
from data.src.utils.utils import wait
class ScreenShake:
def __init__(self, display):
self.display = display
self.timer = 0
self.screen_position = [0, 0]
self.shake = False
def update(self):
if self.shake:
... | eliczi/project_arena | data/src/display.py | display.py | py | 2,773 | python | en | code | 0 | github-code | 1 |
9324696870 | from multiprocessing import Pool
import pandas as pd
from datetime import datetime
from functools import partial
from Task232 import get_count_vacancies, get_salary_level, DataSet, print_statistic
def get_statistic_by_year(file, vacancy, statistics):
df = pd.read_csv(file)
df['salary'] = df[['salary_from', '... | Elenaz441/Zasypkina | Task322.py | Task322.py | py | 2,229 | python | en | code | 0 | github-code | 1 |
21459642036 | # Advent of Code
# Dec 1, Part 2
# @geekygirlsarah
import struct
inputFile = "input.txt"
# Tracking vars
x = 0
y = 0
facing = "N"
places = []
placesX = []
placesY = []
firstTwiceVisitedPlace = ""
firstTwiceVisitedPlaceDist = 0
with open(inputFile) as f:
while True:
contents = f.readline(-1)
if n... | geekygirlsarah/adventofcode-2016 | dec01/dec01part2.py | dec01part2.py | py | 3,169 | python | en | code | 1 | github-code | 1 |
7417459883 | from dataserver import FileServer
from model import Modelrunner, ModelDef
import argparse
import time
import numpy as np
from collections import defaultdict
from pathlib import Path, PurePath
import multiprocessing as mp
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator, FormatStrForm... | REPLICA-Collective-Rep/DATECentral | train.py | train.py | py | 4,740 | python | en | code | 0 | github-code | 1 |
32061157997 | """RecipeBase URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | djangoner/RecipeBase | RecipeBase/urls.py | urls.py | py | 2,437 | python | en | code | 0 | github-code | 1 |
1489810940 | # -*- coding: utf-8 -*-
import tensorflow as tf
from util.LayerUtil import LayerUtil
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import numpy as np
#导入MNIST数据集
mnist = input_data.read_data_sets("D:\\tensorflow\\cha5\\mnist_data", one_hot=True)
#定义模型的超参数
learning_rate = ... | guozhenqiang/AILib | dl/classfication/MnistAutoEncoder.py | MnistAutoEncoder.py | py | 2,280 | python | en | code | 0 | github-code | 1 |
41437728573 | import logging
import os
import re
import pytest
import sqlalchemy
from datetime import datetime, timedelta, timezone
from sqlalchemy.dialects import oracle
from streamsets.testframework.markers import database, sdc_min_version
from stage.utils.common import cleanup
from stage.utils.utils_migration import LegacyHandl... | streamsets/datacollector-tests | stage/standard/test_oracle_cdc_client.py | test_oracle_cdc_client.py | py | 16,206 | python | en | code | 17 | github-code | 1 |
38288069447 | #!/usr/bin/env python3
# Convert hex to base64
import string
from base64 import b64encode
from utils import ans_check
# --------------------------------------------------------
# ---------------------- functions -----------------------
# --------------------------------------------------------
def hexToB64(data: str) ... | IOKernel/cryptopals | challenge01.py | challenge01.py | py | 1,189 | python | en | code | 0 | github-code | 1 |
42426561813 | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
x, y, d = map(int, input().split())
room = [list(map(int, input().split())) for _ in range(n)]
clean = [[0] * m for _ in range(n)]
move = [(-1, 0), (0, 1), (1, 0), (0, -1)]
cnt = 0
while True:
clean[x][y] = 1
nd = (d - 1) % 4
dx, dy = mo... | jhchoy00/baekjoon | 14503.py | 14503.py | py | 749 | python | en | code | 0 | github-code | 1 |
69996666913 | # coding:utf-8
from py2neo import Graph, Node, Relationship, NodeMatcher
import csv
from tkinter import *
#调用node_set()函数和relationship_set()函数进行结点和关系的创建。
def node_set(dict1, node_list1, key1, label1):
temp1 = dict1[key1].replace(' ', '')
temp_list1 = temp1.split('/')
for j1 in temp_list1:
node_lis... | daixiangxiang/Crawler-knowledge-map-NLP | knowledge_map.py | knowledge_map.py | py | 3,792 | python | en | code | 0 | github-code | 1 |
25755211571 | from accounts.forms.profile_form import ProfileForm
from accounts.models import Profile
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse, reverse_lazy
from django.utils.d... | walexhenrique/skype-clone | friendships/views.py | views.py | py | 5,892 | python | en | code | 0 | github-code | 1 |
13944459830 | from django.db import models
from django.contrib.auth.models import AbstractUser
from Image.models import File
# Create your models here.
class Gender(models.TextChoices):
MALE = 'M', 'Male'
FEMALE = 'F', 'Female'
OTHER = 'O', 'Other'
class User(AbstractUser):
age = models.DateField(auto_now=... | jafarjtown/educhat-like-facebook | user_profile/models.py | models.py | py | 1,346 | python | en | code | 0 | github-code | 1 |
10526556499 |
"""
TensorFlow 2.0 implementation of Product-based Neural Network[1]
Reference:
[1] Product-based Neural Networks for User ResponsePrediction,
Yanru Qu, Han Cai, Kan Ren, Weinan Zhang, Yong Yu, Ying Wen, Jun Wang
[2] Tensorflow implementation of PNN
https://github.com/Snail110/Awesome-RecSystem-Models/blob/mas... | Snail110/recsys | PNN/PNN.py | PNN.py | py | 4,910 | python | en | code | 34 | github-code | 1 |
5310388437 | def k_consec_sum(arr, k, n):
rem = n-k
sum1 = sum(arr[:rem])
minsum= sum1
for i in range(rem, n):
sum1+= arr[i]
sum1-= arr[i]
minsum = min(minsum, sum1)
return sum(arr) - minsum
if __name__ == "__main__":
arr=[]
arr = [int(item) for item in input().split(',')]
... | Sourolio10/Leetcode-Practice | Sliding_Window/Max_consec_card_sum.py | Max_consec_card_sum.py | py | 388 | python | en | code | 0 | github-code | 1 |
2056739113 | # from urllib import request
from flask import Flask, render_template,request,make_response
from sklearn.pipeline import Pipeline
import joblib
from sklearn import linear_model
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_... | Abii9443/Fake_news_identifier | app.py | app.py | py | 2,994 | python | en | code | 0 | github-code | 1 |
43942664647 | import os
import sys
import time
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
import PIL.Image as Image
from collections import OrderedDict
def stochasticGradient(cost,params,lr = 0.01):
'''
Stochastic Gradient Descent
'''
... | hallvardnydal/autoencoder | dA.py | dA.py | py | 3,954 | python | en | code | 2 | github-code | 1 |
20800086141 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 09:05:41 2017
@author: ros
"""
from xmlrpclib import ServerProxy
s=ServerProxy('http://ubuntu:2345/')
caller_id='/teleop_turtle'
topic='/turtle1/cmd_vel'
caller_api='http://ubuntu:5678'
s.publisherUpdate(caller_id, topic, caller_api) | gitgaoqian/Python | pythonxmlrpc/publisherupdate.py | publisherupdate.py | py | 285 | python | en | code | 0 | github-code | 1 |
41631110068 | import os
import subprocess
import sys
import logging
import shutil
from flask import Flask, jsonify, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)
app.config['PROPAGATE_EXCEPTIONS'] = True... | matteotiziano/secret-harbor | app.py | app.py | py | 2,568 | python | en | code | 25 | github-code | 1 |
21334492303 | # Tema 5
# Exercitiul 1
print("Exercitiul 1")
nr_a = int(input("1 Scrie un nr\n"))
nr_b = int(input("2 Scrie un nr\n"))
def suma_mea(a, b):
return a + b
print(f"Suma ta este {suma_mea(nr_a, nr_b)}")
# Exercitiul 2
print("Exercitiul 2")
def functie_numere_pare(numar):
if numar % 2 == 0:
... | nqryn/ITS-TA20 | lazarica_petrut/Tema 5.py | Tema 5.py | py | 2,819 | python | ro | code | 0 | github-code | 1 |
15635617106 | '''
Context managers
Why do we need context managers ?
How context managers works?
Context managers allocate and release resources when you need.
Basic example of context managers is `with` statement.
'''
# Simple example
with open('hello.txt', 'r') as file_obj:
data = file_obj.read()
# The above code is e... | nix1947/python_scripts | languages/Python/context_managers.py | context_managers.py | py | 1,555 | python | en | code | 0 | github-code | 1 |
7695458108 | # coding=utf-8
import os
import sys
import time
import tkinter
from tkinter import messagebox
import requests
from myConvert import ConvertPDF, ConvertPic
class tkPDF:
"""
创建PDF转换的Tk窗体\n
width: 窗体宽度\n
height: 窗体高度\n
"""
__Url: str
__APP_ID: str
__API_KEY: str
... | wwzhg77777/convertPDF | src/tkPDF.py | tkPDF.py | py | 8,532 | python | zh | code | 0 | github-code | 1 |
24276109692 | import string
with open("input_D6") as fi:
txt = fi.read()
answers_by_group = txt.split('\n\n')
out1 = 0
out2=0
for ex in answers_by_group:
ex = ex.strip('\n')
part1=ex.replace('\n', '')
part1=set(part1)
out1 += len(part1)
matching = set(string.ascii_lowercase... | susamerz/AoC2020 | AoC2020_D6.py | AoC2020_D6.py | py | 556 | python | en | code | 1 | github-code | 1 |
74440479394 | def mix(nums: list[int], original_indexes=None, current_indexes=None):
if not original_indexes:
original_indexes = list(range(len(nums)))
current_indexes = list(range(len(nums)))
for original_index in range(len(nums)):
index = current_indexes[original_index]
num = nums[index]
... | knthmn/advent-of-code-2022 | src/d20.py | d20.py | py | 2,122 | python | en | code | 0 | github-code | 1 |
72506235875 | #!/usr/bin/env python
# --------------------------------------------------------------------
# cli.py
#
# Author: Lain Musgrove (lain.musgrove@hearst.com)
# Date: Monday October 9, 2023
# --------------------------------------------------------------------
import asyncio
import getpass
import shlex
import signal
impor... | lainproliant/bivalve | bivalve/cli.py | cli.py | py | 6,202 | python | en | code | 1 | github-code | 1 |
73241129635 | import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
import time
time_start=time.clock()
scope = [r'https://spreadsheets.google.com/feeds']
#os.chdir('discord_bots\\pss_bot')
credentials = ServiceAccountCredentials.from_json_keyfile_name('pss_bot.json', scope)
gc = gspread.au... | DT-1236/pss_bot_legacy | old versions/pss_bot v0.4.py | pss_bot v0.4.py | py | 3,363 | python | en | code | 0 | github-code | 1 |
21246357311 | '''
Faça um programa que leia 10 inteiros positivos, ignorando não positivos, e imprima sua média.
'''
i = 1
soma = 0
while i <= 10:
cont = int(input(f"Insira o numero {i}: "))
if cont > 0:
i += 1
num = cont
soma = soma + num
else:
print("Numero invalido. Insira um numero pos... | higor-gomes93/curso_programacao_python_udemy | Sessão 6 - Exercícios/ex7.py | ex7.py | py | 407 | python | pt | code | 0 | github-code | 1 |
28710736014 | from glob import glob
import os
import re
import sys
USAGE = """USAGE:
{} [DIR]"""
def print_usage(name):
print(USAGE.format(name))
def main():
args = sys.argv
if len(args) < 2 or not os.path.isdir(args[1]):
print_usage(args[0])
exit(1)
# extract /* */ and //
comment_patter... | komori-n/KomoringHeights | tools/extract_comments.py | extract_comments.py | py | 1,804 | python | en | code | 27 | github-code | 1 |
3569043832 | # -*- coding: utf-8 -*-
"""currency view."""
from flask import Blueprint, jsonify, request
from flask.views import MethodView
from flask_jwt_extended import verify_jwt_in_request
from marshmallow import ValidationError
from sqlalchemy import func
from evolux_solution.database import db
from evolux_solution.views impor... | Mateus-Brito/evolux-back-end-challenge | evolux_solution/currency/views.py | views.py | py | 3,168 | python | en | code | 0 | github-code | 1 |
30168449782 | import pygame
from pygame.locals import *
import FrontEnd as f
import BackEnd as b
import Fight
WHITE = 250,250,250
#This is where the main loops are... main game control
# game class that is instantiated in the Launcher
class Game():
# Initialise what we need
def __init__(self, screenSize, name):
self.screen... | prithmanickam/2-Player-Platformer-Projectile-Shooter-Game | iteration 3/GameControl.py | GameControl.py | py | 3,099 | python | en | code | 0 | github-code | 1 |
12083402248 | # to capture images from webcam
import cv2
# to work on arrays
import numpy as np
# opens webcam and gives us the handle back
capture = cv2.VideoCapture(0)
# load face detection classifier
dataset = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# an empty to store images later on
data = []
# an infini... | brainmentorspvtltd/MSIT_MachineLearning | faceStore.py | faceStore.py | py | 3,090 | python | en | code | 0 | github-code | 1 |
5549227980 | #!/usr/bin/python3
# coding: utf-8
import os
import glob
import re
import sys
import shutil
import logging
import subprocess
def logging_init():
'''
紀錄檔格式初始化
格式:
[ 2015 Nov 19 21:13:06 ] ryHalign.py:090 [INFO] : Generate 4 scp files: genScpFiles() Success!
[ 2015 Nov 19 21:13:07 ] ryHalig... | don6105/PR2015 | TTS/ryHalign.py | ryHalign.py | py | 14,449 | python | en | code | 0 | github-code | 1 |
12597692501 | from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
import json
from .models import Idea
def index(request):
idea = Idea.objects.all()
response = json.dumps([{}])
return HttpResponse(response, content_ty... | adilmoumni/python_in_practice | apiapp/views.py | views.py | py | 1,356 | python | en | code | 0 | github-code | 1 |
33940811458 | import tensorflow as tf
import numpy as np
g = tf.Graph()
with g.as_default():
a = tf.Variable(tf.constant(4.))
x_val = 5.
x_data = tf.placeholder(dtype=tf.float32)
with tf.name_scope("output"):
multiplication = tf.multiply(a, x_data)
with tf.name_scope("loss"):
loss = tf.square(... | briupdingcm/LearningCookbook | Code/Chap06/gates_1.py | gates_1.py | py | 868 | python | en | code | 0 | github-code | 1 |
28785181845 | import torch
import tensorflow as tf
import math
import numpy as np
import cv2
from tensorflow import keras
def NME(y_true,y_pred):
w = 256
h = 256
d = (w**2+h**2)**(1/2)
nose_x = y_true[:,0]
nose_x_pred = y_pred[:,0]
nose_y = y_true[:,1]
nose_y_pred = y_pred[:,1]
distance_nose =... | JIYOON-INNOPOST/INNOFACE | crop.py | crop.py | py | 4,569 | python | en | code | 0 | github-code | 1 |
191299604 | from __future__ import absolute_import
from __future__ import print_function
import pyspark
import h5py
import json
from keras.optimizers import serialize as serialize_optimizer
from keras.models import load_model
from .utils import lp_to_simple_rdd
from .utils import model_to_dict
from .mllib import to_matrix, from_... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/jamesluhz@elephas/elephas/spark_model.py | spark_model.py | py | 10,442 | python | en | code | 2 | github-code | 1 |
17658319642 | #!/usr/bin/env python
from distutils.core import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='panasonic-comfort-cloud-mqtt',
version='0.5.0',
description='Home-Assistant MQTT bridge for Panasonic Comfort Cloud ',
long_description=long_description,
long_descrip... | slvwolf/panasonic-comfort-cloud-mqtt | setup.py | setup.py | py | 871 | python | en | code | 2 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.