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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
70226513299 | from django.conf.urls import url
from django.views.generic.base import RedirectView, TemplateView
from .views import *
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/roo/courses/', permanent=False), name='index'),
url(r'^(?P<pk>\d+)', CourseUpdate.as_view(), name="detail"),
url(r'^expertise/(?P<pk>\... | ITOO-UrFU/openedu | apps/roo/urls.py | urls.py | py | 2,103 | python | en | code | 0 | github-code | 13 |
33690512296 | import numpy as np
class PSO:
def __init__(self, params):
self.n = params['n']
self.omega = params['omega']
self.a1 = params['a1']
self.a2 = params['a2']
self.X = params['X']
self.V = params['V']
self.X_hat = params['X_hat']
self.g_hat = params['g_hat... | DavidLeeftink/NaturalComputing2021 | Assignment_2/Code/pso.py | pso.py | py | 1,397 | python | en | code | 0 | github-code | 13 |
13030508085 | N, M, Q = map(int, input().split())
dart = [list(map(int, input().split())) for _ in range(N)]
spin = [list(map(int, input().split())) for _ in range(Q)]
def spin_dart(x,d,k):
for i in range(N):
if (i+1)%x==0:
new = [0]*M
if d==0:
for j in range(M):
... | chaeheejo/algorithm | samsung_previous/weird_dart_game.py | weird_dart_game.py | py | 2,118 | python | en | code | 0 | github-code | 13 |
71595941779 | # Type help("robolink") or help("robodk") for more information
# Documentation: https://robodk.com/doc/en/RoboDK-API.html
# Reference: https://robodk.com/doc/en/PythonAPI/index.html
# Note: It is not required to keep a copy of this file, your python script is saved with the station
from robolink import * ... | malek-luky/Industrial-Robotics | 3D Printing/62607_FinalReport_Team4/3Dprint_offline.py | 3Dprint_offline.py | py | 7,204 | python | en | code | 0 | github-code | 13 |
30754654555 | import numpy as np
import matplotlib.pyplot as plt
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Input, Dropout,Flatten, Conv2D
from tensorflow.keras.layers import BatchNormalization, Activation, MaxPooling2D
from tensorflow.keras.models... | cimejia/novel-FER-datasets | Training/emotiondetectionCNN-ARTIFICIAL-training.py | emotiondetectionCNN-ARTIFICIAL-training.py | py | 4,008 | python | en | code | 1 | github-code | 13 |
1020758301 | from datetime import datetime, date
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages # for message
from django.urls import reverse
from django.views import generic
from django.utils.safestring import mark_safe
from datetime im... | Kgermando/es-script | agenda/views.py | views.py | py | 2,154 | python | en | code | 0 | github-code | 13 |
10902239166 | #===============================================================================
# Default tasks.
# Can be overwritten by product configuration.
#===============================================================================
import os
import dragon
import shutil
import argparse
#=====================================... | HPCL-micros/bebop_codes | parrot_arsdk/sdk/arsdk_3_11_0_p0_stripped/build/dragon_build/deftasks.py | deftasks.py | py | 4,527 | python | en | code | 0 | github-code | 13 |
27720797233 | import os
from easybuild.easyblocks.generic.rpm import Rpm
class EB_QLogicMPI(Rpm):
def make_module_extra(self):
"""Add MPICH_ROOT to module file."""
txt = super(EB_QLogicMPI, self).make_module_extra()
txt += self.module_generator.set_environment('MPICH_ROOT', self.installdir)
... | ULHPC/modules | easybuild/easybuild-easyblocks/easybuild/easyblocks/q/qlogicmpi.py | qlogicmpi.py | py | 778 | python | en | code | 2 | github-code | 13 |
9070664080 | from sys import stdin
array = [True for i in range(1000001)]
for i in range(2, 1001):
if array[i]:
for k in range(i + i, 1000001, i):
array[k] = False
while True:
n = int(stdin.readline())
if n == 0: break
for i in range(3, len(array)):
if array[i] and array[n-i]:
... | mins1031/coding-test | baekjoon/GoldbachConjecture_6588.py | GoldbachConjecture_6588.py | py | 595 | python | ko | code | 0 | github-code | 13 |
28003863160 | import os
import sacrebleu
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--model', required=True, type=str)
parser.add_argument('--clean', action="store_true")
args = parser.parse_args()
def get_sentences(path, type):
path = os.path.join(path, "test" + type)
with open(path, "r", enco... | Coda-s/NMT | nmt/evaluate.py | evaluate.py | py | 1,889 | python | en | code | 0 | github-code | 13 |
43008758472 | """
File: Draw lines
Name: Elven Liu
-----------------------
Users can click anywhere in the window first and that place will have a ball. And users click another place in the window,
then this place and the circle will connect to be a line.
"""
from campy.graphics.gobjects import GOval, GLine
from campy.gr... | elven-liu/stanCode-projects | SC101/SC101_Assignment1/draw_line.py | draw_line.py | py | 1,544 | python | en | code | 0 | github-code | 13 |
29864466110 | import requests
import json
from flask import Flask, redirect, url_for, Blueprint, request, render_template, session
import datetime
import time
from satori import satori
from satori import satori_common
from satori import satori_bearer_token
from satori import satori_errors as error
from satori import satori_taxonomy... | northwestcoder/satori-api-server | routes/route_taxonomy.py | route_taxonomy.py | py | 3,635 | python | en | code | 0 | github-code | 13 |
7439620245 | import datetime
import time
from CTkMessagebox import CTkMessagebox
from ChatMate.client_side.meeting_page.meeting_client import MeetingClient
from ChatMate.client_side.meeting_page import meeting_page_functionality
from ChatMate.client_side import client_utils
from ChatMate.client_side.meeting_page import Se... | NONAME4322/ChatMate | ChatMate/client_side/meeting_page/meeting_page_gui.py | meeting_page_gui.py | py | 20,844 | python | en | code | 0 | github-code | 13 |
8734182556 | import tensorflow as tf
Model = tf.keras.applications.mobilenet_v2.MobileNetV2(
input_shape=None,
alpha=1.0,
include_top=True,
weights='imagenet',
input_tensor=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
)
Model.save('./base.model', save_format=None)
print(dir(Mo... | OsinValery/camera_effects | python/base_model_saver.py | base_model_saver.py | py | 468 | python | en | code | 0 | github-code | 13 |
39155274195 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
def sigmoid(x):
return 1/(1 + np.exp(-x))
raw_data = pd.read_csv("binary.csv")
target = raw_data['admit']
## Last error
last_loss = None
## Preprocessing Data
# One-Hot encoding of catagorical data
data = raw_data.drop... | SidGATOR/MachineLearning | perceptron/school_admit.py | school_admit.py | py | 2,231 | python | en | code | 0 | github-code | 13 |
7752615106 | """ get Covid19 rates and plot them
Initial date: 22 Oct 2020
Author: Margot Clyne
File get_rates.py
"""
from my_utils import get_column
from my_utils import binary_search
from my_utils import plot_lines
import sys
import argparse
from operator import itemgetter
from datetime import datetime
import matplo... | cu-swe4s-fall-2020/python-refresher-maclyne | get_rates_saveHW5.py | get_rates_saveHW5.py | py | 6,969 | python | en | code | 1 | github-code | 13 |
29572945619 | n=int(input())
l1=[int(input()) for x in range(n)]
class solution():
def insertion_sort(self,l1):
for i in range(len(l1)):
key=l1[i]
j=i-1
while j>=0 and key<l1[j]:
l1[j+1]=l1[j]
j-=1
l1[j+1]=key
print(l1)
s1=solution()
... | ShabbeirShaik/python | sorting_algorithms/insertionSort.py | insertionSort.py | py | 358 | python | en | code | 0 | github-code | 13 |
25110165599 | from flask import Flask, render_template, request, jsonify
from prometheus_flask_exporter.multiprocess import GunicornInternalPrometheusMetrics
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from prometheus_flask_exporter import PrometheusMet... | Patralekha/Metrics-Dashboard | backend/app.py | app.py | py | 3,932 | python | en | code | 0 | github-code | 13 |
16100486811 | from rest_framework.routers import SimpleRouter
from django.urls import include, path
from users.views import (
UsersViewSet,
get_token,
sign_up
)
router_v1 = SimpleRouter()
router_v1.register(r'users', UsersViewSet)
urlpatterns = [
path('v1/', include(router_v1.urls)),
path('v1/auth/signup/', si... | ShelepovNikita/api_yamdb | api_yamdb/users/urls.py | urls.py | py | 403 | python | en | code | 0 | github-code | 13 |
21880677921 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" utils.py - utility functions """
import sys
import os
import pathlib
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import torch
import torch.nn as nn
from torchvision import datasets, transforms
import torch_training_toolkit as t3
MEANS, STD... | mjbhobe/dl-pytorch | modern_cv_with_pytorch/utils.py | utils.py | py | 3,560 | python | en | code | 8 | github-code | 13 |
72371736979 | from django.http import HttpResponse
from datetime import datetime
from django.template import Context, Template, loader
import random
from home.models import Persona, Familiar
def hola(request):
return HttpResponse('<h1>Buenas clase 41765!</h1>')
def fecha(request):
fecha_y_hora = datetime.now()
return ... | gabicoderhouse/proyectoClase | proyectoClase/views.py | views.py | py | 2,852 | python | es | code | 0 | github-code | 13 |
37964037278 | from TrigMonitorBase.TrigGenericMonitoringToolConfig import defineHistogram, TrigGenericMonitoringToolConfig
class InDetTrigExtensProcessorMonitorBase(TrigGenericMonitoringToolConfig):
def __init__(self, name="InDetTrigExtensProcessorMonitorBase", type="electron"):
super (InDetTrigExtensProcessorMonitorBase, sel... | rushioda/PIXELVALID_athena | athena/InnerDetector/InDetTrigRecAlgs/InDetTrigExtensProcessor/python/InDetTrigExtensProcessorMonitoring.py | InDetTrigExtensProcessorMonitoring.py | py | 1,989 | python | en | code | 1 | github-code | 13 |
73042584019 | # Módulo para obter a ordem das letras
import name_utility
# Biblioteca para eu não precisar programar a estrutura de árvore binária
from binarytree import Node
# Função que será executada caso o programa seja executado, em vez de usado como módulo
def main():
# Arquivo de onde os nomes serão lidos
FILENAME =... | deiveria/av2-teoria-em-grafos | avl_tree.py | avl_tree.py | py | 6,837 | python | pt | code | 0 | github-code | 13 |
27206342719 | """
This module converts a message into numbers to prepare it for encryption
Trying out unit testing.
"""
import unittest
conversion_key = {
' ': '55',
'1': '91',
'0': '88',
'3': '93',
'2': '92',
'5': '95',
'4': '94',
'7': '97',
'6': '96',
'9': '99',
'8': '98',
'a': '11... | Kyle-Koivukangas/kCrypt | textConvert.py | textConvert.py | py | 3,038 | python | en | code | 0 | github-code | 13 |
34692311436 | import pandas as pd
import numpy as np
import collections
print(pd.__version__)
print(np.__version__)
# def my_write_answer(answer, part, number):
# name = 'answer' + str(part) + str(number) + '.txt'
# with open(name, 'w') as file:
# file.write(str(answer))
# def my_precision(d, k):
# sum = 0
# ... | RBVV23/Coursera | Прикладные задачи анализа данных/Week_4/sandbox_4.py | sandbox_4.py | py | 1,493 | python | en | code | 0 | github-code | 13 |
34469372394 | # this script is used to remove the extra seqs that do not correspond to the target gene.
# the target gene names are given in the keywords list below.
import os
import re
from Bio import SeqIO
input_directory = "/Users/hanli/Desktop/FYP/PAML/new_fna_faa"
output_directory = "/Users/hanli/Desktop/FYP/PAML/new_fna_faa/c... | lihanlilyy/Sulfur-Phytobiomes | PAML/clean.py | clean.py | py | 1,685 | python | en | code | 0 | github-code | 13 |
1955632721 | from tkinter import *
from tkinter import messagebox
# creamos una clase
class App():
def __init__(self):
# creamos el objeto de tiopo tkinter
ventana=Tk()
ventana.title('ventana principal')
ventana.geometry('400x400')
#ventana.configure(bg='green')
... | CRISTIANS02/CLASES_JMA | TKINTER/TKINTER_1.PY | TKINTER_1.PY | py | 937 | python | es | code | 6 | github-code | 13 |
39422891639 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
BSNIP SIMPLE UI
Simple UI for BSnip class
versions:
V1.0.0 [25.02.2019]
- first wrking version
V1.1.0 [06.04.2019]
- added option to save snippets on jsonstorage.net
'''
__author__ = "Bojan"
__license__ = "GPL"
__version__ = "1.1.0"
__mainta... | abrihter/bsnip | ui.py | ui.py | py | 8,784 | python | en | code | 0 | github-code | 13 |
36533129632 |
"""Report To Kill Google Spread module.
This module allows RTK scripts to communicate with google sheets to save report records.
"""
import os
from ast import literal_eval
from google.oauth2.service_account import Credentials
import gspread
GSPREAD_CLIENT_SECRET = os.getenv("GSPREAD_CLIENT_SECRET")
WORKSHEET_NAM... | MohamedSaidSallam/RTK | RTK/util/gspread.py | gspread.py | py | 2,001 | python | en | code | 0 | github-code | 13 |
655598766 | """Search in a table"""
import re
import pandas as pd
def search(table, pattern, columns=None):
"""Return the rows of the table for which a column matches the pattern"""
assert isinstance(table, pd.DataFrame), "'table' must be a Pandas DataFrame"
if columns is None:
columns = [col for col in tabl... | mwouts/world_bank_data | world_bank_data/search.py | search.py | py | 889 | python | en | code | 113 | github-code | 13 |
34739690299 | # coding: utf-8
from my_linear_algebra import *
from test_statistics import *
from test_gradient_descent import *
from my_multiple_regression import *
from test_adjusted_data import *
import math
import random
from collections import defaultdict
# 感知器(perception)可能是最简单的神经网络
def step_function(x):
return 1 if x >= 0 ... | lucelujiaming/dataScienceFromSCratch | my_neural_network.py | my_neural_network.py | py | 6,871 | python | en | code | 0 | github-code | 13 |
73864669138 | '''Demo-db initialization and data population'''
# Peewee has very poor type hinting support:
# pyright: reportUnknownMemberType=false
import random
from ..config import Hosts
from ..models.sql import pizza as schema
from ..models.payloads.v1 import pizza as payloads
from ..crud import pizza as db
def... | danielskovli/python-rest-api | simple_rest_api/utils/init_db.py | init_db.py | py | 1,306 | python | en | code | 1 | github-code | 13 |
34278842191 | from django.core.management import setup_environ
import settings
setup_environ(settings)
from scheduler.models import *
from datetime import datetime
from TypeObservingReport import TypeObservingReport
class ScienceObservingReport(TypeObservingReport):
"Quick report for Jay Lockman"
def getTypes(self):
... | nrao/nell | tools/reports/ScienceObservingReport.py | ScienceObservingReport.py | py | 1,329 | python | en | code | 0 | github-code | 13 |
38231436836 | # coding=utf-8
import statistics
import time
import color
from red import red
from tzdatastruct import *
# 装饰器,用于process_x
def nocode(fn):
fn.nocode = True
return fn
class BaseProcessor():
'''处理器 基类'''
# 注册的处理器
registered = list()
# 处理用的正则式list
# 三个元素分别为:匹配正则,flags,替换
re_list = (
... | animalize/tz2txt | tz2txt/BaseProcessor.py | BaseProcessor.py | py | 14,372 | python | en | code | 48 | github-code | 13 |
10259057475 | __config_version__ = 1
GLOBALS = {
'serializer': '{{major}}.{{minor}}.{{patch}}',
}
FILES = [
"setup.py",
"rfc5424logging/__init__.py",
"docs/conf.py",
]
VERSION = ['major', 'minor', 'patch']
VCS = {
'name': 'git',
'commit_message': "Version updated from {{ current_version }} to {{ new_versi... | jobec/rfc5424-logging-handler | punch_config.py | punch_config.py | py | 330 | python | en | code | 47 | github-code | 13 |
15214295902 | # -*- coding: utf-8 -*-
# greburs by InteGreat
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.tools import float_round
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
sale_order_ids = fields.Many2many(comodel_name="sale.order", string="OV",
compute="_compute_from_grou... | sgrebur/e3a | integreat_sale_mrp_mtso/models/purchase.py | purchase.py | py | 4,158 | python | en | code | 0 | github-code | 13 |
29835710015 | import numpy as np
from sklearn.model_selection import train_test_split
import cv2
import os
import Recognize
import re
import argparse
from itertools import product
def cross_validate(file_path, hyper_args):
plates = []
names = []
# uses sample recognition dataset
for f in os.listdir(file_path):
... | vdakov/license-plate-recognition-pipeline | cross_validation_recognition.py | cross_validation_recognition.py | py | 3,458 | python | en | code | 0 | github-code | 13 |
41643279595 | # Method: [Kadane's Algorithm] Calculate curr_max by adding new num, and update max_sum if curr_max is greater than it.
# TC: O(n), since traversing the list only once
# SC: O(1), since no extra space is used
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
ma... | ibatulanandjp/Leetcode | #53_MaximumSubarray/solution.py | solution.py | py | 536 | python | en | code | 1 | github-code | 13 |
12344609095 | # Program for printing top k frequent elements from the given input array
# Naive approach is to keep a count of all numbers in the array in a extra array in a tupled way
# (element, count) and then sort it on the basis of their frequencies and return the elements for
# top k frequencies and this would take atleast 0(N... | souravs17031999/100dayscodingchallenge | heaps_and_priorityQueues/top_k_frequent_elements.py | top_k_frequent_elements.py | py | 1,298 | python | en | code | 43 | github-code | 13 |
1376607641 | """
Functions to project renewals of contracts based on most recent inception date
Can be daily or monthly accuracy
# Sample products: coverage_period, lapse_rate, loss_ratio, comm_ratio, gwp, contracts
products = [[1, 0.1, 0.7, 0.2, 10, 10],
[3, 0.1, 1.2, 0.2, 10, 10],
[12, 0.1, 0.7, 0.4, 10, ... | pdavidsonFIA/insurance_gi | insurance_gi/renewals.py | renewals.py | py | 8,067 | python | en | code | 0 | github-code | 13 |
71312339858 | import torch
import torch.nn as nn
import copy
class TransformerEncoderLayer(nn.Module):
def __init__(self, embed_dim=1936, nhead=4, dim_feedforward=2048, dropout=0.1):
super().__init__()
self.self_attn = nn.MultiheadAttention(embed_dim, nhead, dropout=dropout)
self.linear1 = nn.Linear(em... | yrcong/STTran | lib/transformer.py | transformer.py | py | 8,023 | python | en | code | 155 | github-code | 13 |
21880766691 | """
metrics_logger.py - implements a custom logger that logs metrics across epochs,
which we can then used to plot metrics. This is useful when you don't want to
use Tensorboard for viewing epoch-wise progress of training
Thanks due to Marine Galantin
(@see: https://stackoverflow.com/questions/69276961/how-to-ext... | mjbhobe/dl-pytorch | pyt_lightning/metrics_logger.py | metrics_logger.py | py | 8,470 | python | en | code | 8 | github-code | 13 |
23007064499 | from frosch2010_Tabu_settings import tabu_settings
from random import shuffle
from random import randrange
import asyncio
import copy
import discord
import frosch2010_Tabu_variables as fTV
import frosch2010_Console_Utils as fCU
import frosch2010_Discord_Utils as fDU
import frosch2010_Tabu_other_funtions as f... | Frosch2010/discord-taboo | code-files/frosch2010_Tabu_On_Start_Game.py | frosch2010_Tabu_On_Start_Game.py | py | 3,787 | python | en | code | 1 | github-code | 13 |
72161184339 | from collections import deque
def bfs(graph, start, visited=[]):
qu = deque([start])
visited.append(start)
while qu:
v = qu.popleft()
for i in graph[v]:
if i not in visited:
visited.append(i)
qu.append(i)
return visited
graph = [
[],
... | hyunlae/Algorithm-Note | search/bfs/bfs_04.py | bfs_04.py | py | 474 | python | en | code | 0 | github-code | 13 |
8731021904 | import numpy as np
from numpy import ma
import gc
import veldstatistiek
def afstandmatrix(X,Y):
"""afstandmatrix van punten
#invoer: class roostereigenschappen, zie hieronder"""
assert X.size<15000, "Te veel punten tegelijkertijd ingevoerd.\nVoer een kleiner aantal punten in"
from scipy.spatial... | MarcRotsaert/Qgis-resource | hydromodel_staggerd/info_waquaveld.py | info_waquaveld.py | py | 3,709 | python | nl | code | 0 | github-code | 13 |
74166693457 | #!/usr/bin/env python
# -*- coding:utf8 -*-
#套一个大循环,循环下一页
import requests
import re
# 大学生群体
# 数据的爬取采集
# 数据的存储
# 数据的处理/过滤/筛选
# 数据的分析与展示
# 1、要知道去哪里爬取想要的数据
# 2、要分析这个地址的结构或解析
# /d/file/20171202/3226be099ad8d610e92bbab5218047d1.jpg"
#
# 加入一个循环 按照某个标准循环
# 写成一个jpg的文件
import requests
import re
url = 'http://www.xiaohuar.co... | levinyi/scripts | crawler/python_requests.py | python_requests.py | py | 1,417 | python | zh | code | 8 | github-code | 13 |
33979862335 | import tweepy
import json
# Authentication details. To obtain these visit dev.twitter.com
consumer_key = 'sk5h3aKTyje7Ffk8CwZa6vMtT'
consumer_secret = '5tHSJqEKxYc08bbWYfalFcBgoJ1E7y4lL3aLlH698Nx3wce5e6'
access_token = '287175928-IL2DnvCppJBM68iJHUgMl5svVzBj5RKM0qZrZUcv'
access_token_secret = 'TADqHOjlxhrQupHxaCxiyfx... | Srednogorie/twitter_data_mining | streaming_shell.py | streaming_shell.py | py | 1,683 | python | en | code | 0 | github-code | 13 |
1676238757 | class Node:
def __init__(self, val, l_c = None, r_c = None): # Left and right child pointers
self.value = val # Value
self.l_c = l_c # Left child
self.r_c = r_c # Right child
class BinaryTree:
def __init__(self, root):
self.root = root
# def __str__(self):
# str_lis... | farzan-dehbashi/toolkit | DS/tree/binary_3_LL.py | binary_3_LL.py | py | 566 | python | en | code | 5 | github-code | 13 |
32534272281 | from pico2d import *
import game_world
import random
IMAGE_WIDTH, IMAGE_HEIGHT = 32, 32
positionX = [0]
positionY = [0, 48, 96]
def intersected_rectangle(collided_Rect, rect1_left, rect1_top, rect1_right, rect1_bottom,
rect2_left, rect2_top, rect2_right, rect2_bottom):
vertical = False... | seungdam/2018182019-2DGP-project | 20181820192DGP/block3.py | block3.py | py | 8,069 | python | en | code | 0 | github-code | 13 |
30139454242 | """empty message
Revision ID: 3fee3bd10f9d
Revises: 45c2de366e66
Create Date: 2018-10-23 16:46:02.990772
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "3fee3bd10f9d"
down_revision = "45c2de366e66"
branch_labels = None... | cgwire/zou | zou/migrations/versions/3fee3bd10f9d_.py | 3fee3bd10f9d_.py | py | 969 | python | en | code | 152 | github-code | 13 |
28199617046 | import gym
from stable_baselines3 import PPO
import random
import argparse
import yaml
import csv
import numpy as np
import os
import matplotlib.pyplot as plt
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument('--config_path', type=str, required=True, help='Path to the config yaml')
return... | khaclinh/AST4AV-HighWay | main.py | main.py | py | 4,080 | python | en | code | 0 | github-code | 13 |
73659092816 | import sys, json
from collections import defaultdict
from urllib.parse import urljoin
try:
from owlready2.base import OwlReadyOntologyParsingError
except:
class OwlReadyOntologyParsingError(OwlReadyError): pass
"""
X ID
X LANGUAGE
X LIST
SET
X TYPE
X VALUE
INDEX
BASE
X REVERSE
CONTEXT
VOCAB
GRAPH
""... | haicheviet/ontology_food | lib_for_project/owlready2/jsonld_2_ntriples.py | jsonld_2_ntriples.py | py | 7,418 | python | en | code | 3 | github-code | 13 |
70309393937 | from tkinter import * #The game is interfaced on tkinter
import tkinter as tk
import random #Random library for adding new tiles
import colors as c #User-defined package for setting bg and colors ... | gauri0707/2048-Game | 2048.py | 2048.py | py | 9,421 | python | en | code | 0 | github-code | 13 |
29725869349 | #
#
#Morgans great example code:
#https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc
#
# GitHub utility for freezing graphs:
#https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py
#
#https://www.tensorflow.org/api_docs/python/tf/g... | muhdhuz/compareTF | Training/utils/pickledModel.py | pickledModel.py | py | 11,477 | python | en | code | 2 | github-code | 13 |
6396249945 | # WAP to fill a square matrix with value zero on the diagonals, 1 on the upper right triangle, and -1 on the lower left triangle.
from numpy import *
row,col = [int(i) for i in input("Enter no. of Rows and Columns of the array: ").split()]
a = zeros((row,col),int)
for i in range(row):
for j in range(col):
... | miral25/SIMPLE-PYTHON-PROGRAM | PYTHON SIMPLE PROGRAM/31.py | 31.py | py | 463 | python | en | code | 0 | github-code | 13 |
36674725659 | """
Programmer: Troy Bechtold
Class: CptS 322-01, Spring 2022
Programming Assignment #3
Description: plot utils for jupternotebooks
"""
import matplotlib.pyplot as plt
import utils
plt.style.use('seaborn-dark')
def bar_chart(values, columns, title, x_axis_name, y_axis_name, save=False, file_name=""):
'''
... | tbech12/CPSC322-Final-Project | plot_utils.py | plot_utils.py | py | 3,708 | python | en | code | 0 | github-code | 13 |
16808782554 | import datetime
import subprocess
import sys
from unittest import TestCase
import pytest
from hypothesis import example, given, strategies as st
from hypothesis._settings import (
HealthCheck,
Phase,
Verbosity,
default_variable,
local_settings,
note_deprecation,
settings,
)
from hypothesis... | HypothesisWorks/hypothesis | hypothesis-python/tests/cover/test_settings.py | test_settings.py | py | 13,475 | python | en | code | 7,035 | github-code | 13 |
31093844719 | from utils import *
import numpy
import shutil
# LEEEEMEEEEEEEEE (para correr)
# 1. borrar imgs en imgs_input
# 2. generar imgs a correr en imgs_input: python csv_converter.py ../data/ imgs_input/ .png 32
# los archivos tienen que ser de la forma "nombre-tamaño.csv" (el conversor los genera asi por default)
# 2. corr... | ABorgna/metnum | tp3/conversor_csv/exp_psnr_tiempos_variando_cant_rayos.py | exp_psnr_tiempos_variando_cant_rayos.py | py | 3,500 | python | es | code | 0 | github-code | 13 |
14581220540 | import os
import pytest
import torch
from src.models.train_model import build_model
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname + "/..")
# Get model struct
model, model_conf = build_model()
model.train()
@pytest.mark.parametrize("batch", [20, 10, 90])
def test_dim_output(ba... | NWeis97/ML_Ops_Project | tests/test_model.py | test_model.py | py | 783 | python | en | code | 0 | github-code | 13 |
70180226258 | from rest_framework.test import APITestCase
from rest_framework import status
class SampleTests(APITestCase):
def test_sample(self):
http = status.HTTP_200_OK
url = '/apiv1/'
res = self.client.get(url)
self.assertEqual(res.status_code, http)
| emori92/drf-jwt-practice | back/apiv1/tests.py | tests.py | py | 281 | python | en | code | 0 | github-code | 13 |
5878839207 | from ast import ClassDef
import numpy as np
import struct
from ismember import ismember
#funcion struct2table en python: convierte una estructura a una lista
def myStruct2table(list):
#arr = np.array(estructura)
try:
arr = np.array(list)
except:
print('error en arr = np.array(estruc... | marioaguileraaa/TFG | Core/bfs.py | bfs.py | py | 5,195 | python | en | code | 0 | github-code | 13 |
37910377158 | from CaloRec.CaloRecFlags import jobproperties
from AthenaCommon.Resilience import treatException
from RecExConfig.RecFlags import rec
from AthenaCommon.GlobalFlags import globalflags
from AthenaCommon.DetFlags import DetFlags
from AthenaCommon.Logging import logging
if globalflags.DataSource()=='data':... | rushioda/PIXELVALID_athena | athena/Calorimeter/CaloRec/share/CaloRec_jobOptions.py | CaloRec_jobOptions.py | py | 16,046 | python | en | code | 1 | github-code | 13 |
15293744968 | # %%
import requests
import pandas
import os
import re
from bs4 import BeautifulSoup
# %%
page = requests.get('http://www.howstat.com/cricket/Statistics/Matches/MatchListMenu.asp')
# %%
soup = BeautifulSoup(page.content, 'html.parser')
# %%
a_all = soup.select('#odis > table > tr > td > table > tr > ... | nadeeg/cricket-2019 | data/source_match_players.py | source_match_players.py | py | 4,537 | python | en | code | 0 | github-code | 13 |
73837473298 | import sys
sys.path.append(".")
from bank.Bank import BankTransaction
def test_read_file_input():
"""
test BankTransaction.read_file_input method
"""
expected_output = [
{
"account":{
"active_card":True,
"available_limit":100
}
},
{
... | yennanliu/BankSimulator | tests/unit_test.py | unit_test.py | py | 1,893 | python | en | code | 0 | github-code | 13 |
12967204210 | import pygame
from pygame.locals import *
import sys
import random
class Text:
"""create a Text for GUI screen"""
def __init__(
self, WINDOW_WIDTH, WINDOW_HEIGHT, frame, location, value, color, size
):
pygame.font.init()
self.CreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT)
... | AliiAhmadi/learn | Text.py | Text.py | py | 1,469 | python | en | code | 1 | github-code | 13 |
70063995857 | # DEPENDENCIES (Local)
# ----------------------------------------------------------------------------------------------------
from constants.enums import Models, ClassificationModels, RegressionModels, NeuralModels
from constants.params import ClassificationParams, RegressionParams, NeuralParams
# AUX METHODS
# ------... | gouvina/ml-python-predictor | src/utils/parser.py | parser.py | py | 3,102 | python | en | code | 0 | github-code | 13 |
12359955538 | # run training code
from torch.utils.data import Dataset
import glob
import numpy as np
import scipy.io as io
import os
import cv2
import PIL
from torch import Tensor, einsum
from image import ImageDataset
from ground_truth import GroundTruthDataset
import matplotlib.pyplot as plt
import numpy as np
import torch
from ... | KIngsleyU/Vascular-Tree-Lifting | train.py | train.py | py | 11,603 | python | en | code | 0 | github-code | 13 |
37202482145 | from __future__ import division
from torchvision import models
import torch.utils.data.distributed
import os, sys
if len(sys.argv) != 4:
print('Arguments : models_load_path_prefix, S , destination_dir')
sys.exit(-1)
models_load_path_prefix = sys.argv[1]
S = int(sys.argv[2])
destination_dir = sys.argv[3]
if ... | EdenBelouadah/class-incremental-learning | cil/lucir/codes/extract_last_layer_weights.py | extract_last_layer_weights.py | py | 1,448 | python | en | code | 166 | github-code | 13 |
37969898788 | ## jO to run H6 TB 2004 simulation
##--------------------------------
if not 'PoolHitsOutput' in dir():
PoolHitsOutput="H6LAr_MyOutputFile.root"
if not 'EvtMax' in dir():
EvtMax=10
if not 'CryoXPos' in dir():
CryoXPos=0.
if not 'TableYPos' in dir():
TableYPos=0.
if not 'ParticlePDG' in dir():
Partic... | rushioda/PIXELVALID_athena | athena/LArCalorimeter/LArG4TB/H6G4Sim/share/jobOptions.G4TB_LArH6-2004.py | jobOptions.G4TB_LArH6-2004.py | py | 5,114 | python | en | code | 1 | github-code | 13 |
22827248573 | from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential
# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "https://testpdfrecognize.cognitiveservices.azure... | NickKletnoi/pythonProject | form_recongnize.py | form_recongnize.py | py | 3,966 | python | en | code | 0 | github-code | 13 |
26377142147 | #!/usr/bin/env python
# coding: utf-8
# # Import libraries
# In[1]:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense, Dropout,MaxPooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import classificat... | nipun2123/Schizophrenia_detection | Model development & training/Schizophrenia Detection (ResNet50)-Single best.py | Schizophrenia Detection (ResNet50)-Single best.py | py | 2,626 | python | en | code | 1 | github-code | 13 |
24784363448 | # нахождение корней у многочлена
restore = [] # корни уравнения
a = [int(i) for i in input().split()] # многочлен
w = len(a) - 1
a2 = [] # указатель на решения
s2 = 1
while len(a) != len(a2) and s2 < w:
s = 0
if a2 != []:
a = a2
p = []
b1 = a[-1]
q = []
b2 = a[0]
for... | SUPERustam/Special-projects | src/SuperA.py | SuperA.py | py | 1,753 | python | en | code | 0 | github-code | 13 |
46286727914 | # TODO: import reports
import matplotlib
# use the Agg backend, which is non-interactivate (just for PNGs)
# this way, a separate script isn't started by matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime
from diva import Diva, Dashboard... | mgriley/diva | examples/rough_examples/my_demo.py | my_demo.py | py | 5,455 | python | en | code | 45 | github-code | 13 |
20346979993 | """Classes in this module are used to declare the place where a xml value is located inside a document.
They also provide a mapping between XML data types (which are always stings in specific formats) and
python types. By doing so these classes completely hide the XML nature of data.
The basic offered types are Elemen... | Draegerwerk/sdc11073 | src/sdc11073/xml_types/xml_structure.py | xml_structure.py | py | 62,864 | python | en | code | 27 | github-code | 13 |
31738949573 | # Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
# Edited by Lucas Saldyt, 25 Sep 2018
def gen_numbers(start=2, primes=True):
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositen... | LSaldyt/sence | keras/sieve.py | sieve.py | py | 1,575 | python | en | code | 3 | github-code | 13 |
11408327797 | import time #スリープ関数用.必須じゃない.
import RPi.GPIO as GPIO #GPIO用のライブラリ
PIN = 4 # サーボモータの信号線を接続したGPIO番号の設定
GPIO.setmode(GPIO.BCM) # ポート番号の指定方法をGPIO番号に指定
GPIO.setup(PIN, GPIO.OUT) # GPIOを出力に設定
servo = GPIO.PWM(PIN, 50) # PWMの周波数を50に設定
servo.start(3.0) # PWMのデューティー比を2.5で開始
def servo_lock():
# servo.start... | jphacks/D_2002 | controller/watcher/src/control.py | control.py | py | 1,672 | python | ja | code | 4 | github-code | 13 |
1643891311 | from flask import Flask, render_template, request, jsonify
import requests
OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_KEY = "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"
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
MODEL = "gpt-3... | Version40/flask_openai | app.py | app.py | py | 1,870 | python | uk | code | 0 | github-code | 13 |
26124182511 | from datetime import date, datetime, timedelta
from django.db import models
from django.db.models.fields import DateField
from django.db.models.functions import Cast, ExtractMonth
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from ... | AndreImasato/tasktime-backend | tasktime/views.py | views.py | py | 18,641 | python | en | code | 0 | github-code | 13 |
30793301588 | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import Truncator
from django.utils.translation import ugettext_lazy as _
from cms.models import CMSPlugin
from djangocms_text_ckeditor.models import AbstractText
from filer.fields.image import FilerImag... | nephila/djangocms-revealjs | djangocms_revealjs/models.py | models.py | py | 3,629 | python | en | code | 1 | github-code | 13 |
39401597600 | import random
from is_win_checker import is_win
matrix = [
['', '', ''],
['', '', ''],
['', '', ''],
]
print(matrix)
def gen_numbers():
x, y = random.randrange(0, 3), random.randrange(0, 3)
return [x, y]
def comp_step():
[x, y] = gen_numbers()
if matrix[x][y] == '':
matrix[x][y... | ShamilSE/tic_tac_toe | main.py | main.py | py | 711 | python | en | code | 0 | github-code | 13 |
9229836676 | import asyncio
from typing import TypeVar
from aiogram import types, Bot
MESSAGE_LIMIT = 4096
ReplyMarkup = TypeVar("ReplyMarkup", types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove,
types.ForceReply)
async def split_sending(message: types.Message,
... | taimast/aiochatgpt | aiochatgpt/utils/message.py | message.py | py | 1,434 | python | en | code | 1 | github-code | 13 |
6386912863 | from collections import namedtuple
from gi.repository import BlockDev as blockdev
import logging
log = logging.getLogger("blivet")
from . import raid
from ..size import Size
from ..i18n import N_
from ..flags import flags
# some of lvm's defaults that we have no way to ask it for
LVM_PE_START = Size("1 MiB")
LVM_PE_... | TimothyAsirJeyasing/blivet | blivet/devicelibs/lvm.py | lvm.py | py | 3,163 | python | en | code | null | github-code | 13 |
43129916160 | import re
from django.utils.safestring import mark_safe
def strip(s, all_tags=None):
try:
from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup(s)
except ImportError:
soup = None
valid_tags = ('strong b a i'.split() if not all_tags else '')
valid_attrs = ('hre... | freshplum/django_utils | manage_html.py | manage_html.py | py | 1,326 | python | en | code | 6 | github-code | 13 |
16936229277 | # https://www.acmicpc.net/problem/1208
import sys
from itertools import combinations
n, s = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
# 가운데를 기점으로 두개의 배열로 나눈다.
arr1 = a[:n // 2]
arr2 = a[n // 2:]
# 나눈후, 각 왼쪽, 오른쪽의 값들 조합으로 새로운 배열 생성
left, right = [], []
for i in range(len... | JaeHyeok-2/Algorithm1 | 알고리즘 연습문제/이분 탐색/부분수열의 합2.py | 부분수열의 합2.py | py | 1,751 | python | ko | code | 0 | github-code | 13 |
40485516951 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='barbell',
version='0.2.1',
scripts=['barbell'],
author="Henrique de Paula",
author_email="oprometeumoderno@gmail.com",
description="A tool for creating Gym environments",
long_desc... | oprometeumoderno/barbell | setup.py | setup.py | py | 738 | python | en | code | 0 | github-code | 13 |
3720913130 | class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
# 참고 : Anavil
from collections import Counter
from collections import defaultdict
c = Counter(words)
words_len = len(words)
n = len(words[0])
result = []
for k in range(n... | JaeEon-Ryu/Coding_test | LeetCode/0030_ Substring with Concatenation of All Words.py | 0030_ Substring with Concatenation of All Words.py | py | 1,750 | python | en | code | 1 | github-code | 13 |
29652491613 | #!/usr/bin/python3
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*-
# Partly based on a script from Review Board, MIT license; but modified to
# act as a unit test.
from __future__ import print_function
import os
import re
import subprocess
import unittest
CURDIR = os.path.dirname(os.path.... | GalliumOS/update-manager | tests/test_pyflakes.py | test_pyflakes.py | py | 1,995 | python | en | code | 4 | github-code | 13 |
10835707497 | from flask import Flask, request, jsonify
import response_builder
import json
from flask_mysqldb import MySQL
import os
import json
import collections
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def main():
city_name = request.args.get("cityName")
statistics = response_builder.build_statistic(ci... | whatwouldmarvindo/sweetgeeks | backend/app.py | app.py | py | 3,042 | python | en | code | 0 | github-code | 13 |
40916863729 | import torch
import numpy as np
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split
def get_data_loader_X_C_Y(X, C, Y, batch_size):
'''
To improve, allow for batch loading of data for large data
'''
if C is None:
C = np.empty((X.shape[0],... | simonzabrocki/variational-models | src/utils.py | utils.py | py | 1,215 | python | en | code | 0 | github-code | 13 |
24845969938 |
"""
This file contains a content handler for parsing sumo network xml files.
It uses other classes from this module to represent the road network.
"""
from collections import defaultdict
from copy import deepcopy
from enum import Enum, unique
from typing import List, Dict, Tuple, Optional, Callable, TypeVar, Iterable... | CommonRoad/crgeo | commonroad_geometric/external/map_conversion/sumo_map/sumolib_net.py | sumolib_net.py | py | 62,888 | python | en | code | 25 | github-code | 13 |
71793555218 | """
This script clears the output of the rp_win as it can be rather long and hard to work with. The script
groups the ROP gadgets based on the gadget and shows a maximum of 10 addresses for better readability.
It also removes gadgets with call/jmp to a dword as it is hardly usable in exploitation scenarios.
Author: To... | tomas-kabrt/Exploits-Vulns | sort_rp_win_rop_gadgets.py | sort_rp_win_rop_gadgets.py | py | 1,172 | python | en | code | 0 | github-code | 13 |
14386319195 | #
# @lc app=leetcode.cn id=283 lang=python3
#
# [283] 移动零
#
from typing import List
# @lc code=start
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = 0
for j in range(n):... | largomst/leetcode-problem-solution | 283.移动零.py | 283.移动零.py | py | 546 | python | en | code | 0 | github-code | 13 |
41581933949 | import os
import pandas as pd
from luigi.format import Nop
from luigi import Task, Parameter, LocalTarget
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from machine_learning_utils.luigi.task import Requires, Requirement, TargetOutput
from machine_learning_utils.luigi.target import Base... | Gayle19/2020fa-final-project-Gayle19 | machine_learning_utils/luigi/data.py | data.py | py | 2,626 | python | en | code | 0 | github-code | 13 |
16021865995 | """
Example demonstrating the use of dcompressee
"""
import os
import pathlib
import time
import dcompressee
# get path to local file
path = os.path.dirname(os.path.abspath(__file__))
files_uncmp = os.path.join(path, "example_Seq0000.fasta")
files_gz = [os.path.join(path, f"example_Seq000{i}.fasta.gz") for i in rang... | MDU-PHL/dcompressee | examples/example1.py | example1.py | py | 836 | python | en | code | 0 | github-code | 13 |
36925786052 | import numpy as np
from external_libraries.spline import get_natural_cubic_spline_model
def spline(x=None, y=None, frames=None):
nodes = max(frames) - min(frames)
spline_x = get_natural_cubic_spline_model(x=frames, y=x, minval=min(frames), maxval=max(frames),
n_... | RSantos94/vessel-impact-detection | tools/interpolate_tool.py | interpolate_tool.py | py | 1,268 | python | en | code | 1 | github-code | 13 |
73714033616 | """empty message
Revision ID: 67720836cc61
Revises: 3d9cea121ce6
Create Date: 2022-04-04 15:18:15.590110
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '67720836cc61'
down_revision = '3d9cea121ce6'
branch_labels = None
depends_on = None
def upgrade():
# ... | d-rocham/sofka-challenge | backend/migrations/versions/67720836cc61_.py | 67720836cc61_.py | py | 1,672 | python | en | code | 0 | github-code | 13 |
41844112110 | import logging
import sys
import os
import optparse
from pmpmanager.__version__ import version as pmpman_version
import json
import lsblk
import time
import pmpmanager.db_devices as model
if __name__ == "__main__":
main()
import uuid
#import queue_display
import pmpmanager.initialise_db as devices
from cli_p... | osynge/pmpman | pmpmanager/cli.py | cli.py | py | 7,399 | python | en | code | 0 | github-code | 13 |
72915521618 | import os
import pytest
from qutebrowser.qt.core import Qt
from qutebrowser.mainwindow import prompt as promptmod
from qutebrowser.utils import usertypes
class TestFileCompletion:
@pytest.fixture
def get_prompt(self, qtbot, config_stub, key_config_stub):
"""Get a function to display a prompt with a... | qutebrowser/qutebrowser | tests/unit/mainwindow/test_prompt.py | test_prompt.py | py | 3,870 | python | en | code | 9,084 | github-code | 13 |
13913005623 | from . import gamefield
import datetime
import random
import logging
LOGGER = logging.getLogger("reversi.game")
class GameState:
def __init__(self, field, current_player, mode):
self._field = field
self._current_player = current_player
self._other_player = gamefield.DiskType(int(not self.c... | BobMarleysFan/Reversi | reversi/game.py | game.py | py | 3,942 | python | en | code | 0 | github-code | 13 |
6113283460 | def calcular_imc(peso, altura):
imc = peso / (altura ** 2)
return imc
def classificar_imc(imc):
if imc < 18.5:
return "Abaixo do peso"
elif imc < 24.9:
return "Peso normal"
elif imc < 29.9:
return "Sobrepeso"
elif imc < 34.9:
return "Obesidade Grau I"... | HyagoRubo/IMC_Phyton | desafio_IMC/imc.py | imc.py | py | 703 | python | pt | 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.