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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
74761603857 | from rest_framework import serializers
from . import models
from yggram.users import models as user_models
class SmallImageSerializer(serializers.ModelSerializer):
""" Used fro the notifications """
class Meta:
model = models.Image
fields = (
'file',
)
class CountImageS... | zedonora/yggram | yggram/images/serializers.py | serializers.py | py | 1,965 | python | en | code | 0 | github-code | 13 |
12904532595 | import numpy as np
debug = False
# This class runs games
# it takes in the following:
# -> agent_a
# -> agent_b
# -> A payoff table in the following format:
# [[1,1], [1,0]
# [0,1], [0,0]]
# where 0 and 1 are the moves available to
# agent_a and agent_b in symmetric 2-player games
#
# it then... | yaserBK/QLearning | Game_Runner.py | Game_Runner.py | py | 5,732 | python | en | code | 1 | github-code | 13 |
40924869271 | import xml.etree.ElementTree as ET
import sys
def main(filename):
tree = ET.parse(filename)
root = tree.getroot()
print(get_entities(root))
print(get_relationships(root))
logical_transform(get_entities(root), get_relationships(root))
def get_entities(root):
entities = []
for e in root.find... | cjpappas/xml-er-transform | main.py | main.py | py | 2,887 | python | en | code | 0 | github-code | 13 |
37284623980 | from fonctions.fonctions_affichage import afficher_pile, afficher_file, afficher_silos
from fonctions.algo_repartition.algorithme import algorithme_tri_silos
from fonctions.algo_repartition.vidange_silos import vidange_silos
from fonctions.fonctions_piles_files import empiler, defiler
from fonctions.fonction_generation... | romainflcht/APP1 | main.py | main.py | py | 1,790 | python | fr | code | 0 | github-code | 13 |
26297117424 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 19:41:21 2018
@author: DELL
"""
#https://www.analyticsvidhya.com/blog/2017/09/naive-bayes-explained/
# =============================================================================
# How to build a basic model using Naive Bayes in Python?
# Again, scikit learn... | khanmbjob/python | TextClassification_NB.py | TextClassification_NB.py | py | 1,980 | python | en | code | 0 | github-code | 13 |
43397815861 | from Functions import PrimeSieve
def Solve(p=600851475143):
prime = PrimeSieve()
f = next(prime)
while not p == 1:
if p % f == 0:
p = p / f
else:
f = next(prime)
return f
if __name__ == '__main__':
print(Solve())
| Adam-Hoelscher/ProjectEuler.py | Problem3.py | Problem3.py | py | 276 | python | en | code | 0 | github-code | 13 |
20742770454 | import sys
def isP(n: int):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
return(False)
return(True)
else:
return(False)
if __name__ == "__main__":
min, max = int(sys.argv[1]), int(sys.argv[2])
r = [x for x in range(max, min - 1, -1) if isP(x) and x ... | mgirard772/python_month_of_code | day14/mary_prime_get.py | mary_prime_get.py | py | 432 | python | en | code | 0 | github-code | 13 |
71088759058 | # @Time : 2018/7/21 10:05
# @Author : cap
# @FileName: find_jpg.py
# @Software: PyCharm Community Edition
# @introduction: # 查找所有jpg文件并分类,以dic和list的形式
import os
import pickle
import xml.etree.ElementTree as ET
dict_map = {0: '正常', 1: '吊经', 2: '擦洞', 3: '跳花', 4: '毛洞', 5: '织稀', 6: '扎洞',
7: '缺经', 8: '毛斑', ... | zhnin/competitions | tianchi/xuelang/test/find_jpg.py | find_jpg.py | py | 3,137 | python | en | code | 1 | github-code | 13 |
41568419393 | import logging
import requests
from binstar_client import errors
from binstar_client.utils import jencode
import binstar_client
import binstar_build_client
from binstar_build_client.utils.worker_stats import worker_stats
log = logging.getLogger('binstar.build')
class BuildQueueMixin(object):
def register_worke... | anaconda-graveyard/anaconda-build | binstar_build_client/mixins/build_queue.py | build_queue.py | py | 6,823 | python | en | code | 2 | github-code | 13 |
27345176390 | print("uno")
from tkinter import *
raiz= Tk()
raiz.title("primera ventana")
raiz.config(width=300, height=300)
raiz.resizable(0,0)
raiz.iconbitmap("imagen.ico")
raiz.config(bg="red")
raiz.mainloop() | Williams5656/EJE | miprimer.py | miprimer.py | py | 199 | python | es | code | 1 | github-code | 13 |
71497022419 | # 언어 : Python
# 날짜 : 2021.08.23
# 문제 : BOJ > 음식물 피하기 (https://www.acmicpc.net/problem/1743)
# 티어 : 실버 1
# ======================================================================
import sys
sys.setrecursionlimit(100000)
def dfs(r, c):
global cur_ans
dx, dy = [0, 0, 1, -1], [1, -1, 0, 0]
for i in range(4):... | eunseo-kim/Algorithm | BOJ/최고빈출 DFS, BFS 기본문제/04_음식물피하기.py | 04_음식물피하기.py | py | 1,084 | python | en | code | 1 | github-code | 13 |
71763755858 | import numpy as np
from matplotlib import pyplot as plt
from ANN_lab_3.hopfield_net import HopfieldNet, find_two_largest_factors
def display_image(pict, shape, title=None, show=True, fig=None, ax=None):
"""
Display an image.
:param pict:
:param shape:
:param title:
:param show:
:param fig... | tommasopiehl/ANN_lab1 | ANN_lab_3/pict_memory.py | pict_memory.py | py | 3,768 | python | en | code | 0 | github-code | 13 |
3835256775 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 8 17:30:59 2018
@author: 606C
"""
import cv2
#import matplotlib.pyplot as plt
mode = True
def get_xy_point(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print('x= ',x)
print('y= ',y)
img1 = cv2.imread('Fig1.jpg')
cv2.namedWindow(... | dennis2110/Computer_Vision | homography/find_xy_point.py | find_xy_point.py | py | 540 | python | en | code | 0 | github-code | 13 |
70614738258 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from task_manager.statuses.forms import CreateStatusForm
from task_manager.statuses.models import Status
def index(request):
statuses = Status.objects.all()
return render( request, 'statuses/index.html', {'statuses': statuses})
... | zhabinka/python-web-development-project-lvl4 | task_manager/statuses/views.py | views.py | py | 1,319 | python | en | code | 0 | github-code | 13 |
3672501012 |
"""
Build a heirarchical bayesian model
Here we to estimate the positive predictive and sensitivity of different gene targets available
for pubchem.
This seems to be a good resource....
https://docs.pymc.io/projects/examples/en/latest/case_studies/hierarchical_partial_pooling.html
Heres another maybe better resourc... | russodanielp/training_json | bayes_heirarchical.py | bayes_heirarchical.py | py | 1,830 | python | en | code | 0 | github-code | 13 |
70331393298 | import os
import json
import requests
from config import validator, COURSE_DIR, COURSE_YAML_DIR, INDEX_YAML
from course import Course
from parser import yaml
from utils import aplus_json, PrintColor
# os.environ['PLUGIN_API'] = 'http://0.0.0.0:8080/api/v1/'
# os.environ['PLUGIN_TOKEN'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJS... | apluslms/deploy-aplus | main.py | main.py | py | 2,648 | python | en | code | 0 | github-code | 13 |
2514351107 | import logging
from datetime import date
import geocoder
from django import forms
from django.conf import settings
from events.models import ExternalEvent
class ExternalEventForm(forms.ModelForm):
class Meta:
model = ExternalEvent
exclude = []
widgets = {
"starts_on": forms.w... | przem8k/piosenka | events/forms.py | forms.py | py | 1,556 | python | en | code | 7 | github-code | 13 |
28620801106 | # This script created as part of the application process for
# the Star AI course.
# python 3.7.0
message = (
"How many times do you want to display the message "
"\"Reinforcement Learning\" on screen? "
)
user_input = input(message)
try:
times = int(user_input)
for _ in range(times):
print(... | paulfioravanti/starai | reinforcement_learning.py | reinforcement_learning.py | py | 446 | python | en | code | 0 | github-code | 13 |
4748533295 | # Hjólaleiga Skilaverkefni
# Jón og Sesselja
from time import sleep as wait
from random import randint as rand
class Bike:
def __init__(self, hourly_price, daily_price, weekly_price, nr):
self.hourly_price = hourly_price
self.daily_price = daily_price
self.weekly_price = weekly_price
... | nonni1234/hjolaleiga-skilaverk | hjolaleiga.py | hjolaleiga.py | py | 5,081 | python | en | code | 0 | github-code | 13 |
10314493180 | import csv
import json
def csv_to_json(csv_file, json_file):
# Abrir o arquivo CSV de origem
with open(csv_file, 'r') as file:
# Ler as linhas do arquivo CSV
csv_data = csv.DictReader(file)
# Converter as linhas para uma lista de dicionários
data_list = list(csv_data)
... | Beguiny/python_projects | document_converter/CSV/csv_para_json.py | csv_para_json.py | py | 543 | python | pt | code | 0 | github-code | 13 |
36375154005 | from tkinter import *
import customtkinter
from threading import Thread
from PIL import ImageTk, Image
import GUIHandler
import logging
import sys
import time
import math
import WeatherStationProperties
properties = WeatherStationProperties.WeatherStationProperties()
customtkinter.set_appearance_mode("dark")
logging... | luke-redwine-sudo/Weather-Station | WeatherStationMain.py | WeatherStationMain.py | py | 4,392 | python | en | code | 0 | github-code | 13 |
41313477434 | #
# @lc app=leetcode id=274 lang=python3
#
# [274] H-Index
#
# @lc code=start
class Solution:
def hIndex(self, citations: List[int]) -> int:
citations.sort(reverse = True)
h = 0
for i,v in enumerate(citations):
if v >= i+1:
h = i+1
return h
# @lc code=en... | WrathOP/LeetCode | 274.h-index.py | 274.h-index.py | py | 323 | python | en | code | 0 | github-code | 13 |
23810954676 | # -*- coding: utf-8 -*-
"""This module defines the necessary things to load an ASS file,
and the objects that allow to draw text with cairo"""
import codecs, math
from draw import extra
import common
#Constants, don't change anything if you don't want the program to crash
#From Style
S_NAME = 'name'
S_FONT = 'fontname... | jerobarraco/kafx | branches/kafx/libs/asslib.py | asslib.py | py | 17,575 | python | en | code | 1 | github-code | 13 |
19351873486 | MAX_EXP = 200
GRID_DEPTH = 3
INF = float('inf')
VERBOSE = True
PLOT_LOG_SCALE = True
USE_BIGFLOAT = False
STEP = 1.1
OPTIMIZATION_METHOD = 'L-BFGS-B'
# OPTIMIZATION_METHOD = 'TNC'
INITIAL_GRID_COUNT = 20
INITIAL_GRID_STEP = 3
DEFAULT_ERR_SCALE = 1
DEFAULT_K = 21
DEFAULT_READ_LENGTH = 100
DEFAULT_REPEAT_MODEL = 0
DEFAU... | mhozza/covest | covest/constants.py | constants.py | py | 608 | python | en | code | 5 | github-code | 13 |
14312045609 | from bs4 import BeautifulSoup
import requests
source = requests.get('http://tibia.pl/exp-table').text
soup = BeautifulSoup(source, 'html5lib')
for search in soup.find_all('tr'):
info = search.text.split()
lvl = info[0]
exp = info[1]
if lvl.isnumeric() and exp.isnumeric():
print("Poziom: ",lvl... | Pablit4o/aplikacje-internetowe-21716-185ic | Lab5/scrape-web-2.py | scrape-web-2.py | py | 347 | python | en | code | 0 | github-code | 13 |
25392061458 | from django.conf.urls import include, url
from django.contrib import admin
from account import views as account_views
# from reports import views as reports_views
from groups import views as group_views
from messaging.views import *
from django.conf import settings
from django.conf.urls.static import static
urlpattern... | jyou543/cs3240-s17-team22 | Fintech/urls.py | urls.py | py | 3,762 | python | en | code | 0 | github-code | 13 |
19870715404 | import tweepy #https://github.com/tweepy/tweepy
from datetime import datetime
from datetime import timedelta
class KEY:
def __init__(self, _consumer_key, _consumer_secret, _access_key, _access_secret):
self.consumer_key = _consumer_key
self.consumer_secret = _consumer_secret
self.access_key = _access_key
se... | Nealsoni00/cs376-server | api.py | api.py | py | 3,236 | python | en | code | 0 | github-code | 13 |
72605103699 | import sys
sys.setrecursionlimit(1000000)
def melt(l, y, x):
moves = [[0, 1], [1, 0], [0, -1], [-1, 0]]
for move in moves:
dy, dx = move
if not (len(l) > y+dy >= 0 and len(l[0]) > x+dx >= 0):
continue
if l[y+dy][x+dx] == '.' or l[y+dy][x+dx] == 'L':
l[y][x] = '#... | gitdog01/AlgoPratice | random/no_category/3197/main.py | main.py | py | 1,820 | python | en | code | 0 | github-code | 13 |
21583053826 | import debug # pyflakes:ignore
import io
import json
import os
from django.conf import settings
from django.urls import reverse
from ietf.doc.models import Document
from ietf.group.factories import RoleFactory
from ietf.meeting.models import SchedTimeSessAssignment, SchedulingEvent
from iet... | ietf-tools/old-datatracker-branches | ietf/secr/proceedings/tests.py | tests.py | py | 8,814 | python | en | code | 5 | github-code | 13 |
42053692807 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from democritus.elements import Elements
from democritus.molecules import Molecules
OWNER = 'Research Labs'
def test_create_group_from_tcex_json():
e = Elements(OWNER)
data = {
"attribute": [
{
"type": "Description",
... | fhightower-tc/old-tcex-utility | tests/test_elements.py | test_elements.py | py | 8,622 | python | en | code | 0 | github-code | 13 |
31392612179 | from pathlib import Path
class Solution:
def __init__(self):
with open(Path(__file__).parent / "input", "r") as f:
self.input = f.readlines()
def solve_part_1(self):
stack_len = 10007
stack = list(range(stack_len))
for line in self.input:
if "new" in li... | Gramet/adventofcode | 2019/day22/solution.py | solution.py | py | 2,376 | python | en | code | 0 | github-code | 13 |
3745999878 | #!/usr/bin/env python
import os
import sys
module_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(module_dir, "..", ".."))
from data.base import get_version
from data.base import setup
_V = get_version()
_D = [
"omim-data-borders",
"omim-data-essential",
"omim-data-files... | organicmaps/organicmaps | tools/python/data/all/setup.py | setup.py | py | 455 | python | en | code | 7,565 | github-code | 13 |
37944007538 |
__doc__ = """Run pythia 6 validation monitoring"""
from PyJobTransformsCore.trf import *
from PyJobTransformsCore.full_trfarg import *
from PyJobTransformsCore.trfutil import *
from HepMCAnalysis_i.Pythia6TrfConfig import pythia6config
class Pythia6valid_trf( JobTransform ):
def __init__(self):
... | rushioda/PIXELVALID_athena | athena/Generators/HepMCAnalysis_i/scripts/Pythia6valid_trf.py | Pythia6valid_trf.py | py | 826 | python | en | code | 1 | github-code | 13 |
72088373777 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 20:55:13 2019
@author: ZQZ
"""
# import smtplib
import re, os, sys
import pandas as pd
from collections import Counter
# from email.header import Header
# from email.utils import formataddr
# from email.mime.text import MIMEText
from sklearn.externals im... | loneMT/BBPpred | codes/predict.py | predict.py | py | 4,354 | python | en | code | 0 | github-code | 13 |
72764868499 | import json
import discord
import requests
import asyncio
from threading import Timer
from discord.utils import get
from discord.ext import commands
from core.cog_core import Cog_Extension
with open('setting.json', 'r', encoding='utf8') as jfile:
jdata = json.load(jfile)
# detecting price alerts
as... | freewayfuh/dApp-discord-bot | cmds/watchlist.py | watchlist.py | py | 7,882 | python | en | code | 1 | github-code | 13 |
30241203403 | "============================JSON============================"
#JavaScript Object Notation - единый формат, в котором
# могут храниться только те типы данных,
# которые есть во всех яз-прог поддерживающие json
# числа itn, float
# строки str
# словари dict
# булевые значения True, False
# списки list
# пустое значение... | Bekaaaaaaaa/python27---lections- | files/json_.py | json_.py | py | 1,728 | python | ru | code | 0 | github-code | 13 |
70587946258 | import numpy as np
import cv2
from keras.models import Sequential
from keras.layers import Dense, Activation
num_inputs=18
depth=3
image=cv2.imread('lena.png')
out = image.reshape(len(image)**2, 3)
inp = np.array(list(map(lambda x: list(("{0:"+str(num_inputs)+"b}").format(x).replace(' ', '0')), range(len(out)))))
... | corollari/overfitted | main.py | main.py | py | 788 | python | en | code | 1 | github-code | 13 |
22726911764 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
impor... | kksignal/industry-stream-predict | industry stream predict.py | industry stream predict.py | py | 24,624 | python | en | code | 0 | github-code | 13 |
9520397117 | import json
from clip.simple_tokenizer import SimpleTokenizer
if __name__ == "__main__":
tok = SimpleTokenizer()
encoder = tok.encoder
ranks = dict(("`".join(k), v) for k, v in tok.bpe_ranks.items())
with open("models/tokenizer.json", "w") as f:
json.dump({
"bpe_ranks": ranks,
... | simon987/sist2-models | clip/create_tokenizer_data.py | create_tokenizer_data.py | py | 363 | python | en | code | 1 | github-code | 13 |
17250031221 | from itertools import product
from collections import defaultdict
def count_up(p, q, r):
return product(*[range(p,q+1)]*r)
def force_solve(lhs, rhs):
l = len(lhs) + len(rhs)
for mults in count_up(1, 10, l):
nl, nr = lhs.copy(), rhs.copy()
lm, rm = mults[:len(lhs)], mults[len(lhs):]
... | nayakrujul/balance-equation | balance/balance.py | balance.py | py | 1,413 | python | en | code | 1 | github-code | 13 |
42075608238 | """
Base module for processing all timeseries based data.
Use this as the base module for processing illfiles,bf.txt,weafiles.
Dependencies: none
Python version : 2.7
"""
from __future__ import print_function
from __future__ import division
import logging
logger = logging.getLogger("__main__")
logging... | sariths/stadicViewer | StadicViewer/gui/dataStructures/timeSeries.py | timeSeries.py | py | 3,404 | python | en | code | 1 | github-code | 13 |
2250421859 | """This is a simple example demonstrating how to clone the behavior of an expert.
Refer to the jupyter notebooks for more detailed examples of how to use the algorithms.
"""
import numpy as np
from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.ppo i... | HumanCompatibleAI/imitation | examples/quickstart.py | quickstart.py | py | 2,727 | python | en | code | 1,004 | github-code | 13 |
7438277931 | #!/usr/bin/env python
"""
Basic web server thing
"""
from bottle import request, response, debug, run, error, route, static_file
import bottle
import logging
import json
import os
FRONT_END_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'front_end')
@error(400)
def error400(error):
logging.info(... | rdooley/et_al | server.py | server.py | py | 809 | python | en | code | 0 | github-code | 13 |
11602040162 | # Question: Given a string and a pattern, find the smallest substring in the given string which has all the characters of the given pattern.
# Example 1:
# Input: String="aabdec", Pattern="abc"
# Output: "abdec"
# Explanation: The smallest substring having all characters of the pattern is "abdec"
# Example 2:
# Input... | webdevlex/algorithms-in-python | grokking/1 - Sliding Window/1.10 - Smallest Window containing Substring (hard).py | 1.10 - Smallest Window containing Substring (hard).py | py | 1,784 | python | en | code | 0 | github-code | 13 |
41922270163 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import scipy.misc
import shutil
import os
import conv_model
max_iter = 20000
batch_size = 256
output_path = 'output'
log_path = 'log'
freq_print = 20
freq_save = 1000
KEEP_RATE = 0.7
IM_HEIGHT = 28
IM_WIDTH = 28
IM_SI... | bruno-31/toy-gan | gan.py | gan.py | py | 5,449 | python | en | code | 0 | github-code | 13 |
71900046737 | import matplotlib.pyplot as plt
import networkx as nx
import random
import tkinter as tk
from tkinter import simpledialog
# This function checks that there are undefended provinces with respect to the problem or not.
def IsFeasible(G):
x = 0
y = 0
z = 0
for node in G.nodes:
if G.nodes[node]["N... | mhmtacar/Roman-Domination-Number | BruteForce.py | BruteForce.py | py | 4,369 | python | en | code | 0 | github-code | 13 |
2061037791 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from dynsettings.decorators import override_dynsettings
from dynsettings.models import SettingCache
from dynsettings.tests import dyn_settings
class OverrideDynsettingsTestCase(TestCase):
"""
Verify the override... | infoscout/dynsettings | dynsettings/tests/test_decorators.py | test_decorators.py | py | 961 | python | en | code | 0 | github-code | 13 |
1346718941 | import hashlib
import os
from datetime import datetime
from typing import List, Tuple, Optional
import pickle
from dateutil.parser import parse as dateutil_parse
from torch.utils.data import DataLoader
from pyhealth import BASE_CACHE_PATH
from pyhealth.utils import create_directory
MODULE_CACHE_PATH = os.path.join(B... | sunlabuiuc/PyHealth | pyhealth/datasets/utils.py | utils.py | py | 3,910 | python | en | code | 778 | github-code | 13 |
26512233840 | '''Desenvolva um programa que leia nome, idade e sexo de quatro pessoas. No final do programa,
mostre:
A média de idade do grupo;
Qual é o nome do homem mais velho;
Quantas mulheres têm menos de 20 anos'''
count_wo=0
count_ma=0
nom_hom=""
med=0
for i in range(1,5):
print("{:=^20}".format("{}ª pessoa").format(i))
... | MLucasf/PythonExercises | ex056.py | ex056.py | py | 1,002 | python | pt | code | 0 | github-code | 13 |
10280125747 | #!/usr/bin/env python
import subprocess
import argparse
import os
exe_path = "/proj/kweeks/bin/"
smo = "shapemapper_out"
rmo = "ringmapper_out"
pmo = "pairmapper_out"
apo = "arcplot_out"
dmo = "dancemapper_out"
fco = "foldclusters_out"
def sbatch(command, params, dep=None):
if dep is not None:
params["de... | Weeks-UNC/longleaf-dotfiles | pipelines/map-pipeline.py | map-pipeline.py | py | 9,561 | python | en | code | 2 | github-code | 13 |
39115456920 | def main():
entrada = input()
qtd_vertices = int(entrada)
estudantes = list(range(qtd_vertices))
vertices = dict()
for i in range(len(estudantes)):
entrada = input()
entrada = list(map(int, entrada.split()))
entrada = entrada[1:]
vertices[i] = {'color':... | LorhanSohaky/UFSCar | 2018/PAA/T2/Debate.py | Debate.py | py | 1,019 | python | pt | code | 1 | github-code | 13 |
37595690391 | ###########################################################
#### Initialization --- do not change #####################
###########################################################
print('hallo')
import sys
sys.path.append('D:\BeamlineControllPython\programming_python')
import p05.devices, p05.nano, p05.tools #########... | hereon-wpi/p05nano | 01_standard_flyScan.py | 01_standard_flyScan.py | py | 3,672 | python | en | code | 0 | github-code | 13 |
34737417249 | import math
import numpy as np
import torch
from torch import nn
import test_softmax
# 下面的代码用来生成假数据。
# 生成假数据的公式如下:
# y = 5 + 1.2 * x / (1!) + (-3.4) * x^2 / (2!)
# + 5.6 * x^3 / (3!) + normal()
max_degree = 20 # 多项式的最⼤阶数
n_train, n_test = 100, 100 # 训练和测试数据集⼤⼩
true_w = np.zeros(max_degree) # 分配⼤量的空间... | lucelujiaming/luceluDiveIntoDeepLearning | ch04_multilayer-perceptrons/test_normal.py | test_normal.py | py | 4,819 | python | zh | code | 0 | github-code | 13 |
28401719431 | from __future__ import unicode_literals
import os, re, json
# Metadata
RAW_URL = r'https://www.pluralsight.com/courses/'
HTML_FILE = os.path.join("...", "data", "search_results.html")
JSON_OUTPUT_FILE = os.path.join("...", "data", "courses.json")
def lookaround_tags(start_tag, end_tag):
# Contruct regular express... | wenliangz/plura_py_private | scrapeutils/scrape_html_to_json.py | scrape_html_to_json.py | py | 1,856 | python | en | code | 0 | github-code | 13 |
26806301955 | from django.urls import path, include, re_path
from rest_framework import routers
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from account.api.v1.viewsets import UserRegistrationView, LoginTokenObtainView, GoogleLogin, FacebookLogin, AppleLogin
router = routers.SimpleR... | sibtainDev/django_social_login | account/api/v1/urls.py | urls.py | py | 847 | python | en | code | 0 | github-code | 13 |
6921789676 | while True:
try:
x,y = input("Fraction: ").strip().split("/")
x = int(x)
y = int(y)
if y == 0:
raise
fuel = str(x) + "/" + str(y)
if fuel == "1/4":
print("25%")
elif fuel == "1/2":
print("50%")
elif fuel == "2/4":... | mobile-desk/cs50p-projects | ps3/fuel_gauge.py | fuel_gauge.py | py | 603 | python | en | code | 0 | github-code | 13 |
10331692850 | from discord.ext import commands
from bot import Commands, run_timer
bot = commands.Bot(command_prefix=commands.when_mentioned_or('='), description='Techraptor Control Bot')
@bot.event
async def on_ready():
run_timer()
print('Logged in as: {0} (ID: {0.id})'.format(bot.user))
bot.add_cog(Comma... | Techraptor/TechBot | main.py | main.py | py | 344 | python | en | code | 0 | github-code | 13 |
26062210399 | # -*- coding: utf-8 -*-
import numpy as np
class Network(object):
def __init__(self,sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.rand(y,1) for y in sizes[1:]] #随机从正态分布(均值0,方差1)中生成
self.weights = [np.random.rand(y,x)
for x,y... | Rheasilvia/PythonLearning | Handwriting/mnielsen/Network.py | Network.py | py | 429 | python | en | code | 0 | github-code | 13 |
40614163600 | import os
import copy
import move
import board
import numpy as np
from model import *
from config import *
def cast(string, res=None):
pad = copy.deepcopy(move.initPad)
i = 0
while i < len(string):
x = ord(string[i]) - ord('0')
y = ord(string[i + 1]) - ord('0')
id = int(i / 2)
... | VGxiaozhao/ChineseChess | CNN/cnn_go.py | cnn_go.py | py | 2,114 | python | en | code | 0 | github-code | 13 |
69983077138 | #Fibonacci's sequence using recursion
def fib(n):
if n < 2:
return n
else:
# fn = fn-1 + fn-2
return fib(n-1) + fib(n-2)
for x in range(10):
print(fib(x)) | cabrera-evil/python | MD2/Partial-02/fibonacci.py | fibonacci.py | py | 195 | python | en | code | 2 | github-code | 13 |
21800478452 | # Time Limit per Test: 3 seconds
# Memory Limit per Test: 512 megabytes
# Using: PyPy 3-64
# Solution Link: https://codeforces.com/contest/1795/submission/195399945
'''
Question Link: https://codeforces.com/contest/1795/problem/D
You are given an undirected graph consisting of 𝑛
vertices and 𝑛
edges, where 𝑛
is ... | Squirtleee/AlgoPractice | Solutions/Triangle Coloring.py | Triangle Coloring.py | py | 2,934 | python | en | code | 0 | github-code | 13 |
2792179790 | # Write a Python program to create a person class.
# Include attributes like name, country and date of birth.
# Implement a method to determine the person's age.
months = ["january", "februry", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
class Person:
def __i... | Nebrocebro/Programmering-2 | Prog2-NeoMalmros/obj-ori-ex-2.py | obj-ori-ex-2.py | py | 961 | python | en | code | 0 | github-code | 13 |
42110537778 | import sys
sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inl = lambda: [int(x) for x in sys.stdin.readline().split()]
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))
A, B = inl()
def solve():
xt = []
... | keijak/comp-pub | yukicoder/1236/main.py | main.py | py | 723 | python | en | code | 0 | github-code | 13 |
2568603214 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""
Класс где мы реализовываем работу корабля.
"""
def __init__(self, ai_settings, screen):
"""
Функция иницирования работы корабля, его изображения, настроек.
"""
super(Ship, self).__init__()
se... | MaxKuznetsovGHST/alien_invasion | ship.py | ship.py | py | 1,583 | python | ru | code | 0 | github-code | 13 |
32029130635 | from dataclasses import dataclass
from typing import Optional
from langchain import FewShotPromptTemplate, PromptTemplate
from langchain.chains import LLMChain
from langchain.docstore.document import Document
from summ.classify.classes import Classes
from summ.shared.chain import Chain
from summ.shared.utils import d... | yasyf/summ | summ/factify/factifier.py | factifier.py | py | 4,757 | python | en | code | 141 | github-code | 13 |
24016051138 | from params_hom import *
from processingNetwork import ProcessingNetwork
from matplotlib import pyplot as plt
import pickle
from utils import *
# Load pretraining policy
with open('qtable_policy.pickle','rb') as file:
custom_policy = pickle.load(file)
print('Q-table policy:', custom_policy)
dir_path = path()
with... | lucaballotta/ProcessingNetworks-RL | CDC paper/test_custom_policy.py | test_custom_policy.py | py | 1,904 | python | en | code | 1 | github-code | 13 |
3763837274 | import cv2
import numpy as np
from skimage.exposure import match_histograms
from watchdog.events import *
reference = cv2.imread('D:/aiImg/img/1.png') # 目标图像
def piliangzhifanghu(image_reade,img_output):
data_base_dir = image_reade # 输入文件夹的路径
outfile_dir = img_output # 输出文件夹的路径
processed_number = 0 # ... | sdy555/pythonTest | function/批量去除章印.py | 批量去除章印.py | py | 2,386 | python | en | code | 0 | github-code | 13 |
74880905618 | from seismic_zfp.read import SgzReader
import segyio
import time
import os
import sys
from PIL import Image
import numpy as np
from matplotlib import cm
base_path = sys.argv[1]
LINE_NO = int(sys.argv[2])
CLIP = 200
SCALE = 1.0/(2.0*CLIP)
with segyio.open(os.path.join(base_path, '0.sgy'), strict=False) as segyfile:
... | equinor/seismic-zfp | examples/sgz_reading/read-crossline-unstructured.py | read-crossline-unstructured.py | py | 1,496 | python | en | code | 57 | github-code | 13 |
19933241667 | # 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
# 示例 1:
# 输入:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# 输出:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.... | Vivhchj/LeeeCode_Notes | 73.矩阵置零_mid.py | 73.矩阵置零_mid.py | py | 1,296 | python | en | code | 0 | github-code | 13 |
16324784397 | # django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
A database backend for the Django ORM.
Allows access to all Salesforce objects accessible via the SOQL API.
"""
import logging
import warnings
import django
__version__ ... | jhflorey/djangoSalesforceMaster | salesforce/__init__.py | __init__.py | py | 1,475 | python | en | code | 1 | github-code | 13 |
30711886159 | # pLADMPSAP
# By ZincCat
from scipy.optimize import minimize
import numpy as np
from matplotlib import pyplot as plt
# from joblib import Parallel, delayed
np.random.seed(19890817)
n = 70
s = 30
x = np.random.normal(0, 1, (n, s))
y = np.random.choice([0, 1], s)
w0 = np.random.normal(0, 1, n)
def f(w):
return n... | zinccat/Convex-Analysis-homework | 20/2.py | 2.py | py | 3,365 | python | en | code | 15 | github-code | 13 |
43263227092 | def main():
def nearlist(n0, lst):
res = [[] for _ in range(n0)]
for a, b in lst:
res[a - 1].append(b - 1)
res[b - 1].append(a - 1)
return res
def bfs(s0, n0):
dist = [-1] * n0
dist[s0] = 0
que = [s0]
for q in que:
for... | Shirohi-git/AtCoder | agc/agc033_c.py | agc033_c.py | py | 846 | python | en | code | 2 | github-code | 13 |
4060511988 | import pandas as pd
df_prices=pd.read_csv("prices.csv")
df_prices_adjusted=pd.read_csv("prices-split-adjusted.csv")
df_securities=pd.read_csv("securities.csv")
#print(df_prices)
def process_prices(df):
df['date']=df['date'].apply(lambda x:x[:10])
df_filtered=df[['date', 'symbol','close']]
df_pivot=pd.pivo... | Vilmos97/NumFin4 | eset.py | eset.py | py | 2,333 | python | en | code | 0 | github-code | 13 |
5640908700 | # importing packages
from CharacterProfiles import *
from Statics import *
import numpy as np
import itertools as it
from time import perf_counter
# returns iterable power set of an iterable
def powerset(iterable):
s = list(iterable)
return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s) + ... | prodbywinter/StarRail | EnergyCalcs.py | EnergyCalcs.py | py | 4,736 | python | en | code | 0 | github-code | 13 |
19905712207 | class Solution:
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
#recursive
if k == 1:
return [[x,] for x in range(1, n+1)]
if n == k:
return [[i for i in range(1, n+1)]]
return [i + [... | littleliona/leetcode | medium/77.combinations.py | 77.combinations.py | py | 769 | python | en | code | 0 | github-code | 13 |
28911961430 | import h5py
import numpy as np
import os
import argparse
import math
batch_size = 5000
def hdf5_process(in_file, out_file):
# initialise the output
tmp_file = os.path.join(os.path.dirname(out_file), ".tmp." + os.path.basename(out_file))
combined = h5py.File(tmp_file, 'w')
try:
fileread = h5py... | xiaoyaohu0325/chess_deeplearning | preprocessing/features_converter.py | features_converter.py | py | 3,761 | python | en | code | 1 | github-code | 13 |
25329032064 | import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import mannwhitneyu
class Detector:
def __init__(self):
pass
def detect(self, ts):
self.ts = ts
self.err_indices = []
return self.err_indices
def plot_result(self):
plt.plot(self.ts)
plt.p... | maksimchup/Error_tracking_GTS | detectors.py | detectors.py | py | 2,285 | python | en | code | 0 | github-code | 13 |
26570577445 | """Dad joke plugin."""
import server_utils
from plugins._base_plugins import BaseCommandPlugin
class DadJokeCommand(BaseCommandPlugin):
"""Dad joke plugin."""
COMMAND = 'dadjoke'
async def run(self) -> None:
"""Dad jokes provided by icanhazdadjoke.com."""
url = 'https://icanhazdadjoke.... | amorphousWaste/twitch_bot_public | twitch_bot/plugins/dad_joke_command.py | dad_joke_command.py | py | 638 | python | en | code | 0 | github-code | 13 |
5976050231 | import string
import typing
import unittest
import tempfile
import os
import random
import file_helper
from random_test_case_helper import get_random_catalog_page_url, get_random_detail_page_url, get_random_filename
class ImageExistsTestCase (unittest.TestCase):
# region Helpers
@staticmethod
def get_ran... | MacJim/Safebooru-Downloader | test_file_helper.py | test_file_helper.py | py | 9,514 | python | en | code | 0 | github-code | 13 |
70073798739 | # -*- coding: utf-8 -*-
#Integrantes: Carolina Hong y Andrés Pirela
import ply.lex as lex
import ply.yacc as yacc
reserved={
'kcal' : 'KCAL',
'ate' : 'ATE',
'limit' : 'LIMIT',
'average' : 'AVERAGE',
'intake': 'INTAKE',
'=' : 'ASIGN',
'sum': 'SUM',
'day': 'DAY',
'food': 'FOOD',
'with': 'W... | caroohong/CalorEase | calorease.py | calorease.py | py | 10,636 | python | es | code | 0 | github-code | 13 |
73643891217 | # Ejercicio 863: Extraer todas las palabras que se hallen entre comillas dobles desde una cadena de caracteres.
import re
texto = '"Python", "JavaScript", "C++", "Java"'
patron = r'"(.*?)"'
lenguajes = re.findall(patron, texto)
print(lenguajes)
print()
for l in lenguajes:
print(l)
| Fhernd/PythonEjercicios | Parte001/ex863_extraer_palabras_entre_comillas_dobles.py | ex863_extraer_palabras_entre_comillas_dobles.py | py | 293 | python | es | code | 126 | github-code | 13 |
7899241629 | from tree import Node
def retr_subgraph(val, g, starting_cands, degree, size_of_sub_graph, list_of_elements_found):
root_node = Node(val)
for i in range (0,len(starting_cands)):
# if len(sub_graph_found) == size_of_sub_graph:
# print("Returned")
# return sub_graph_found
... | 4m4npr33t/De-Anonymising_Social_Networks | codes/retr.py | retr.py | py | 1,277 | python | en | code | 0 | github-code | 13 |
73783070098 | import numpy as np
import matplotlib.pyplot as plt
# ----------- 2
T_e = 1
T = 100
sigma_Q = 1
sigma_px = 1
sigma_py = 30
x_init = np.array([[3, 40, -4, 20]]).transpose()
x_kalm = x_init
P_kalm = np.eye(4)
F = np.array([[1, T_e, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, T_e],
[0, 0, 0... | AlexandreChaussard/Cassiopee_Chirurgie | Anciens Programmes/TP - Inférences bayésiennes/TP 2 - Filtrage de Kalman/principal.py | principal.py | py | 13,063 | python | fr | code | 1 | github-code | 13 |
17691952682 | import re
import unicodedata
def convert_lower_case(doc):
return doc.lower()
def remove_control_char(doc):
chars = [char for char in doc]
for i in range(len(chars)):
if unicodedata.category(chars[i])[0] == "C":
chars[i] = " "
return "".join(chars)
def remove_non_word_char(doc):
... | vietnguyen012/QA1 | botchat-api/search-engine/postprocess.py | postprocess.py | py | 924 | python | en | code | 0 | github-code | 13 |
4699104737 | #prompting user to enter value
x = input("Enter the value :") #input is string so need to typecast into int for doing math functions
print(x+" is what you entered")
#two ways of string formatting
user_input = input("Enter you name: ")
user_surname = input("Enter surname: ")
message_1 = "Hello %s %s!" %(user_input,user... | Soundwavepilot1969/Udemy_Python_Mega_Course | Section2_to_12/basics_6_7.py | basics_6_7.py | py | 1,608 | python | en | code | 0 | github-code | 13 |
475336591 | from pyspark.sql import SparkSession
from pyspark.sql.functions import sum,count
if __name__ == '__main__':
spark = SparkSession.builder.appName("NewAssign").master("local[*]").getOrCreate()
sc = spark.sparkContext
#RDD
textf = sc.textFile("/home/saif/LFS/cohort_c9/datasets/ratings.csv")
header = te... | divya-anand21/PySpark_Lab | c9/rddQ3.py | rddQ3.py | py | 1,212 | python | en | code | 0 | github-code | 13 |
36294187691 | from django.forms import *
from models import Roast, Alert
from django.utils.translation import ugettext as _
class RoastForm(ModelForm):
class Meta:
model = Roast
fields = ['body', 'keys']
widgets = {
'keys': SelectMultiple(attrs={'class': 'js-data-example-ajax-multiple', 'placeholder': 'Roast Description'}... | Shoop123/Roast-Dictionary-Django | roasts/forms.py | forms.py | py | 898 | python | en | code | 0 | github-code | 13 |
23248077746 | # encoding: utf-8
"""
Created by misaka-10032 (longqic@andrew.cmu.edu).
"""
class Solution(object):
def strStr(self, haystack, needle):
"""
Naive matching
:type haystack: str
:type needle: str
:rtype: int
"""
l_needle = len(needle)
l_haystack = len... | misaka-10032/leetcode | coding/00028-strstr/solution.py | solution.py | py | 781 | python | en | code | 1 | github-code | 13 |
11531831074 | #!/usr/bin/python
import collections
import logging
import sys
import termios
import tty
from typing import Dict
def getch() -> str:
"""
Utility function to get a single character from the user
Returns:
str: A single character
"""
fd = sys.stdin.fileno()
old_settings = termios.t... | joshuagawley/bf.py | bf.py | bf.py | py | 4,363 | python | en | code | 0 | github-code | 13 |
33256521247 | # -*- coding: utf-8 -*-
from django.urls import path
from django.contrib.sitemaps.views import sitemap
from django.utils.translation import gettext_lazy as _
from . import views
from marketing.views import email_list_signup
from shop.sitemaps import CatSitemaps
sitemaps = {
'cat': CatSitemaps,
}
app_name = 's... | sujayshekhar/django-ecommerce | shop/urls.py | urls.py | py | 1,905 | python | en | code | 5 | github-code | 13 |
20349629640 | import sys
sys.path.append('/home/silentknight/School/CS434/434proj/cmpt-434-proj')
import asyncio
from rpcudp.protocol import RPCProtocol
@asyncio.coroutine
def sayhi(protocol, address):
# result will be a tuple - first arg is a boolean indicating whether a
# response was received, and the second argument ... | rowan-maclachlan/cmpt-434-proj | async_test/client.py | client.py | py | 931 | python | en | code | 0 | github-code | 13 |
24887920489 | from data import dataset # Input data in datastr
from data import dataset_sorted
import collections
import math
n = len(dataset)
print("Data Statistics: \n")
# Calculate Mean:
def mean(dataset, n):
sum = 0
for i in range (0, n):
sum += dataset_sorted[i]
return sum / n
print("Mean: " + str(mean(dataset, n)) ... | RT5x/Python-Data-Sorter | Python Statistics/main.py | main.py | py | 1,710 | python | en | code | 0 | github-code | 13 |
7593404667 |
def kanpsack_0_1(vals, weight, W, curr):
"""
Returns the maximum price that we can fill in the knapsack
vals = array of prices
weight = array of weights
W = limit of max weight in knapsack
curr = current index in consideration
"""
if curr == 0:
if weight[curr] <= W:
... | shashank231/practice-design | raman1.py | raman1.py | py | 787 | python | en | code | 0 | github-code | 13 |
39157886290 | from machine import Pin, ADC
from time import sleep
lm35_pin = 34
lm35 = ADC(Pin(lm35_pin))
lm35.width(ADC.WIDTH_12BIT)
lm35.atten(ADC.ATTN_11DB)
def read_tempc():
lm35_value = lm35.read()
voltage = (lm35_value / 4096.0) * 3300
tempc = voltage * 0.1
return tempc
def read_tempf():
lm35_value = lm... | akmyat/electronics | esp32_LM35/esp32-LM35-micropython/main.py | main.py | py | 776 | python | en | code | 0 | github-code | 13 |
38287690009 | # no need to import smtplib for this code
# no need to import time for this code
import imaplib
import email
import pickle
import pandas as pd
import keras
from keras import *
from keras import layers, optimizers
from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense, Dropout
from keras.models import M... | codermedia/spam_email_recognition | detection_cnn.py | detection_cnn.py | py | 4,626 | python | en | code | 0 | github-code | 13 |
9477069285 | # ---------------------------------------------------------- #
# Title: TestHarness
# Description: A main module for testing
# ChangeLog (Who,When,What):
# RRoot,1.1.2030,Created script
# MClark, 3.13.2021, Created Script
# ---------------------------------------------------------- #
if __name__ == "__main__":
... | MClark89/Assignment09 | TestHarness.py | TestHarness.py | py | 1,120 | python | en | code | 0 | github-code | 13 |
31046436159 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
simple module to translate English to Chinse, Chinese to English
'''
# API key:701380394
# keyfrom:youdao-python
from __future__ import print_function, unicode_literals
import json
import sys
try:
# compatible for python2
from urllib import urlencode
fro... | khaman1/Video_Translator | library/image/chinese.py | chinese.py | py | 2,221 | python | en | code | 1 | github-code | 13 |
71454096337 | print()
# data_kr.xlsx 파일읽기
import re
from openpyxl import load_workbook
# 원본 문자 : python VS java
# VS를 기준으로 문자열 분리 => ['python', 'java']
pattern = re.compile(" VS ") # 공백까지 확인
print(pattern.split("python VS java"))
print()
# 주민번호 컬럼을 읽어서 화면 출력 단, 주민번호 뒷자리는 *로 변경해서 출력
wb = load_workbook("./RPAbasic/crawl/download/da... | HwangJuu/pythonsource | RPAbasic/regex/regex5.py | regex5.py | py | 777 | python | ko | code | 0 | github-code | 13 |
14494142463 | import pandas as pd
from src.utils import get_root_folder, insert_to_table
from codetiming import Timer
def insert_from_csv(root_path, path, table_name):
path = root_path.joinpath(path).as_posix()
bookmarks_df = pd.read_csv(path)
n_elem = bookmarks_df.shape[0]
with Timer(text=f"Inserted to '{table_nam... | StepDan23/okko-postgres | src/database/init_db.py | init_db.py | py | 1,085 | python | en | code | 0 | github-code | 13 |
42746230615 | from sys import stdin
# n: number of lines (int)
# k: length of a word (int)
# d: dictionary <key, val> <int, int>
# w: word (string)
# c: character occurence counter array (int list size: 26)
# a: ascii value of 'a' (int)
# j: ascii mapping to c index 'a' -> 0 (int)
def f(w):
"""
This function takes in strin... | gurpartb/kattis | mr_anaga2.py | mr_anaga2.py | py | 963 | 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.