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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
18932220810 | import os
import time
import datetime
from pathlib import Path
from datetime import datetime
import psutil
import math
class Location(str):
def __call__(self, *args) -> 'Location':
return Location(self.format(*args))
def exists(self):
return Path(self).exists()
def read(self):
wit... | idlab-discover/wasm-operator | profile/wasmProfiler.py | wasmProfiler.py | py | 3,043 | python | en | code | 47 | github-code | 36 |
33634152186 | from re import A
import time, random
from Yinsh.yinsh_model import YinshGameRule
from template import Agent
from copy import deepcopy
from collections import deque
import numpy as np
THINKTIME = 0.5
C_PARAM = 1.414
class Node():
def __init__(self, state, game_rule=None, agent_id=None, parent=None, parent_action=... | bzr1/automated-agent-for-a-board-game-yinsh- | agents/t_056/mcts.py | mcts.py | py | 7,015 | python | en | code | 0 | github-code | 36 |
5925495311 | """
Spyral, an awesome library for making games.
"""
__version__ = '0.2'
__license__ = 'MIT'
__author__ = 'Robert Deaton'
from types import ModuleType
import sys
import compat
import pygame
# import mapping to objects in other modules
all_by_module = {
'spyral.sprite' : ['Sprite', 'Group', 'AggregateSprite'],
... | rdeaton/spyral | __init__.py | __init__.py | py | 2,378 | python | en | code | 3 | github-code | 36 |
74962738343 | from rest_framework.serializers import ModelSerializer
from rest_framework import exceptions
from api.models import VDO
from django_celery_results.models import TaskResult
class VDOSerializer(ModelSerializer):
def create(self, validated_data):
newvdo_record = self.Meta.model.objects.create(**validated_dat... | 6410615147/cartrack | cartrack/api/serializer.py | serializer.py | py | 688 | python | en | code | 0 | github-code | 36 |
23616237270 | debug_queue = "queue", "inter"
""" How to select the debug queue.
First part of the tuple is the keyword argument to modify when calling
the pbs job, and the second is its value.
"""
accounts = ["BES000"]
""" List of slurm or pbs accounts allowed for use.
This is used by ipython's %launch magic functio... | mdavezac/LaDa | config/redmesa_mpi.py | redmesa_mpi.py | py | 1,720 | python | en | code | 5 | github-code | 36 |
73434596264 | import pandas as pd
import json
import requests
# # ----------from fred---------------
# api_keys = ["36211f27396765eca92b93f01dca74db", "4808384bf945022005347fcf2f6957fb",
# "a66fc3e61d360c6088b022f2c06c831c", "1836f996f9157acd994d59547bb0f65c",
# "4e2f7a3a68190b6584419017414974d5", "bc4c30a69... | stergioa/masterThesis4 | src/download_data/download_timeseries_values.py | download_timeseries_values.py | py | 1,818 | python | en | code | 0 | github-code | 36 |
40152772858 | """Display a rotomap."""
import enum
import functools
import sys
import cv2
import numpy
import mel.lib.common
import mel.lib.fullscreenui
import mel.lib.image
import mel.rotomap.detectmoles
import mel.rotomap.mask
import mel.rotomap.moles
import mel.rotomap.tricolour
DEFAULT_MASKER_RADIUS = 200
_WHITE = (255, 255... | aevri/mel | mel/rotomap/display.py | display.py | py | 24,857 | python | en | code | 8 | github-code | 36 |
17895408730 | import tensorflow as tf
import utils # local file import from baselines.toxic_comments
class UtilsTest(tf.test.TestCase):
def test_make_cv_train_and_eval_splits(self):
num_folds = 10
train_fold_ids = ['2', '5']
(train_split, eval_split, train_folds, eval_folds,
eval_fold_ids) = utils.make_cv_tra... | google/uncertainty-baselines | baselines/toxic_comments/utils_test.py | utils_test.py | py | 1,078 | python | en | code | 1,305 | github-code | 36 |
71946585384 | from pyspark.sql import SparkSession
from pyspark.sql.functions import lit
spark = (SparkSession
.builder
.appName("files_creator")
.config("spark.sql.sources.partitionOverwriteMode", "dynamic")
.config("hive.exec.dynamic.partition", "true")
.config("hive.exec.dynamic.parti... | actweird/data_repository | Python/files_creator.py | files_creator.py | py | 574 | python | en | code | 0 | github-code | 36 |
40302056937 | import sys
import datetime
from project import app
from common_utilities import Constant
from project.users.models import Counter, Users
from flask_login import login_required, logout_user, current_user
from flask import Blueprint, render_template, session, make_response, jsonify, request, redirect, url_for
sys.path.a... | PatelFarhaan/ACCEPTME-PROD | project/users/views.py | views.py | py | 5,641 | python | en | code | 0 | github-code | 36 |
29884391783 | """ Run Length Decoding """
def main():
""" print decoded password """
text = input()
result = ""
for i in range(len(text)):
if ord(text[i]) > 65:
result += text[i]
temp = len(result) - 1
print(int(result[:temp])*result[-1], end="")
result = ""
... | DefinitelyNotJay/ejudge | Run Length Decoding.py | Run Length Decoding.py | py | 368 | python | en | code | 0 | github-code | 36 |
34694883753 |
import os,sys
sys.path.append("..")
from tools.iPrint import *
from misc.Color import Colors
class Shell:
def __init__(self) -> None:
self.runShell()
def runShell(self):
while True:
try:
command = input(Colors.RED + "IShell ~$shell> " + Colors.END)
... | lanbinshijie/IceShell | models/shell.py | shell.py | py | 639 | python | en | code | 18 | github-code | 36 |
9783557706 | import requests
from bs4 import BeautifulSoup
# 製作一個串列裝所有可輸入的星座代號
# astros = ["牡羊座","金牛座","雙子座","巨蟹座","獅子座","處女座","天秤座","天蠍座","射手座","摩羯座","水瓶座","雙魚座"]
astrosDict = {"牡羊座":"0","金牛座":"1","雙子座":"2","巨蟹座":"3","獅子座":"4","處女座":"5","天秤座":"6","天蠍座":"7","射手座":"8","摩羯座":"9","水瓶座":"10","雙魚座":"11"}
# 組合字串,並印出所有可選星座
# text = ''
# ... | byunli/python | 參考_星座.py | 參考_星座.py | py | 1,621 | python | en | code | 0 | github-code | 36 |
38516771350 | import boto.exception
from awscompat import config, util
from awscompat.connections import ec2_conn
from awscompat.tests.base import TestNode
class TestDescribeImages(TestNode):
"""Failing test for https://bugs.launchpad.net/nova/+bug/755829"""
def pre(self):
assert ec2_conn.get_all_images(
... | mwhooker/aws-compat | awscompat/tests/ec2.py | ec2.py | py | 3,744 | python | en | code | 1 | github-code | 36 |
14065685389 | def lying_down(R):
tot = 0
for row in R:
cnt = 0
for j in range(N):
if row[j] == '.':
cnt += 1
if j == N-1 and cnt >= 2:
tot += 1
else:
if cnt >= 2:
tot += 1
cnt = 0
... | yeon-june/BaekJoon | 1652.py | 1652.py | py | 530 | python | en | code | 0 | github-code | 36 |
70233514344 | from flask import render_template,request,redirect,url_for
from .import main
from ..request import get_sources,get_articles,search_news
from ..models import Source
@main.route("/")
def index():
"""
View root function that returns the index page and its data
"""
popular_news = get_sources("popular")
... | alexmwaura/NewsApp | app/main/views.py | views.py | py | 1,389 | python | en | code | 0 | github-code | 36 |
72163194664 | # quizz, homework, test college calculator
# 12/09/20
# luis Velasquez
students = {
"frank": {"name": "frank",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]},
"alice": {"name": "alice",
"homework": [100.0, 92.0... | alejjuuu/Code-work | Python/CCM/grading_list_students.py | grading_list_students.py | py | 1,179 | python | en | code | 2 | github-code | 36 |
7775666459 | import sys
n = int(input())
l = []
for i in range(n):
l.append(int(input()))
lsf = sys.maxsize
pist = 0
maxprofit = 0
for i in l:
if(i < lsf):
lsf = i
pist = i - lsf
if(pist > maxprofit):
maxprofit = pist
print(maxprofit)
| nishu959/Pepcodingdynamicprogramming | busandsellstocksoneyransaction2.py | busandsellstocksoneyransaction2.py | py | 257 | python | en | code | 0 | github-code | 36 |
39114860473 | """
The basic framework of the Iterative Closest Points Matching is provided by Albert-Ludwigs-Universität Freiburg,
the course Introduction to Mobile Robotics (engl.) - Autonomous Mobile Systems
Lecturer: Prof. Dr. Wolfram Burgard, Dr. Michael Tangermann, Dr. Daniel Büscher, Lukas Luft
Co-organizers: Marina Kollmitz, ... | SiweiGong/mobile_robot_framework | icp_matching.py | icp_matching.py | py | 4,026 | python | en | code | 1 | github-code | 36 |
25051037536 | import sys
import math
from math import *
from numpy import *
import matplotlib.pyplot as plt
from D52 import R_lst, t_lst, L_lst
from mat import A2195_T84 as mat
from D53 import buckling_opt
from D54 import getConfigs
def format_list(beam_configurations):
cor_list = []
for i in range(len(m_viable)):
... | C08-System-Design/WP5 | D55.py | D55.py | py | 1,865 | python | en | code | 0 | github-code | 36 |
8797239686 |
import json
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import os
import argparse
from pathlib import Path
import tqdm
#import models
from models.backbone import Backbone
from models.classification_head import ... | rajatmodi62/multi-purpose-networks | train_conditioned.py | train_conditioned.py | py | 14,471 | python | en | code | 0 | github-code | 36 |
29290582448 | #!/usr/bin/env python
import rospy
import tf
if __name__ == '__main__':
rospy.init_node('pose_saver')
listener = tf.TransformListener()
listener.waitForTransform('/map', '/base_footprint', rospy.Time(0), rospy.Duration(1.0))
rate = rospy.Rate(20.0)
with open('/media/hao/hao/dataset/ros_pose.txt... | QinHarry/CNN_SLAM | data/ros/src/mit_data/src/pose_saver.py | pose_saver.py | py | 788 | python | en | code | 6 | github-code | 36 |
11903172959 | import time
from flask import request
from data_sheet import session, ShortMessage
from utils.tool import short_message
from ..user import bp
@bp.route('/mobile_text')
def test():
phone = request.json.get("phone")
if phone is None:
return {'code':201,'message':'请输入手机号码'}
try:
... | yyiridescent/exchange | api/user/mobile_text.py | mobile_text.py | py | 1,107 | python | en | code | 0 | github-code | 36 |
31949200751 |
# Escreva um programa para aprovar o empréstimo bancario para a compra de uma casa. O valor da casa,
# o sálario do comprador e em quantos anos ela vai pagar.
# calcule o valor da prestação mensal, sabendo que ela não pode excerder 30 % do sálario ou então o
# emprestimo será negado.
##############################... | Valdo04/Curso_em_videos_python | ex0036.py | ex0036.py | py | 901 | python | pt | code | 0 | github-code | 36 |
36918913878 | # based on A Plus Coding's tutorial at: https://www.youtube.com/watch?v=GKe1aGQlKDY&list=PLryDJVmh-ww1OZnkZkzlaewDrhHy2Rli2
import pygame
import sys
from game_window_class import *
from button_class import *
FPS = 60 # max frames per second
EVALUATE_DAMPER = 10 # decrease to fo evaluations faster
WIDTH = 1150
HEIGHT... | ruankie/game-of-life | main.py | main.py | py | 5,738 | python | en | code | 0 | github-code | 36 |
37362852715 | import PAsearchSites
import PAgenres
def search(results,encodedTitle,title,searchTitle,siteNum,lang,searchByDateActor,searchDate,searchAll,searchSiteID):
searchResults = HTML.ElementFromURL(PAsearchSites.getSearchSearchURL(siteNum) + encodedTitle)
for searchResult in searchResults.xpath('//div[@class="video-ite... | PhoenixPlexCode/PhoenixAdult.bundle | Contents/Code/sitePorndoePremium.py | sitePorndoePremium.py | py | 4,420 | python | en | code | 102 | github-code | 36 |
25325013946 | from rest_framework import status
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.generics import RetrieveAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from rest_framework_jwt.au... | mathemartins/vendescrow | rates/api/views.py | views.py | py | 2,400 | python | en | code | 0 | github-code | 36 |
12134276149 | import logging
from rest_framework import viewsets, mixins, serializers, generics
from apps.proceso.models.forms.campo import Campo
from .campo_validation_view import CampoValidationSerializer
from .validation_view import ValidationSerializer
log = logging.getLogger(__name__)
class CampoSerializer(serializers.ModelS... | vitmaraliaga/TesisDgiService | apis/proceso_api/viewsets/forms/campo_view.py | campo_view.py | py | 1,852 | python | en | code | 0 | github-code | 36 |
4824133992 | import pygame
from pygame import font
class Button():
def __init__(self,alien_setting,screen,msg):
# 初始化按钮属性
self.screen = screen
self.screenRect = screen.get_rect()
#设置按钮的尺寸和其他属性
self.width,self.height = 200,50
self.buttonColor = (0,255,0)
self.textColor = (... | hongnn/myRemoteWarehouse | alien_game/button.py | button.py | py | 1,077 | python | en | code | 0 | github-code | 36 |
28630512846 | import traceback
from icebox.billing.biller import BaseBiller
from icebox.billing.biller import RESOURCE_TYPE_BANDWIDTH
from densefog import logger
logger = logger.getChild(__file__)
class EipBiller(BaseBiller):
def _collect_usages(self, project_id, eip_ids):
from icebox.model.iaas import eip as eip_mod... | hashipod/icebox | core/icebox/billing/eips.py | eips.py | py | 3,051 | python | en | code | 0 | github-code | 36 |
36522588108 | import numpy as np
import os
def read_obj(filename):
faces = []
vertices = []
fid = open(filename, "r")
node_counter = 0
while True:
line = fid.readline()
if line == "":
break
while line.endswith("\\"):
# Remove backslash and concatenate with next l... | wangkangkan/3DClothedHumans | vertex-level_regression/write2obj.py | write2obj.py | py | 3,378 | python | en | code | 5 | github-code | 36 |
4809944238 | '''
Generating and sampling shapes
u,v \in [0,1]
'''
# TODO Derive each class from PhiFlow Geometry class
from phi.torch.flow import *
# Helper function to sample initial and target position of 2 shapes
# Get O overlapping, and U non-necessarily overlapping ('unique') sample points
def get_points_for_shapes(shape_0... | bobarna/eigenfluid-control | src/shapes.py | shapes.py | py | 7,366 | python | en | code | 1 | github-code | 36 |
35015760399 | import argparse
import numpy as np
import torch
from copy import deepcopy
from gluonts.dataset.multivariate_grouper import MultivariateGrouper
from gluonts.dataset.repository.datasets import get_dataset
from gluonts.evaluation.backtest import make_evaluation_predictions
from gluonts.evaluation import MultivariateEvalu... | morganstanley/MSML | papers/Stochastic_Process_Diffusion/tsdiff/forecasting/train.py | train.py | py | 6,723 | python | en | code | 12 | github-code | 36 |
247176838 | from trytond.model import ModelView, ModelSQL, fields
from trytond.pool import Pool
from sql import Table, Column, Literal, Desc, Asc, Expression, Flavor
from sql.functions import Now, Extract
from sql.operators import Or, And, Concat, ILike, Operator
from sql.conditionals import Coalesce
from sql.aggregate import Cou... | coalesco/trytond_songbook | artist.py | artist.py | py | 4,420 | python | en | code | 0 | github-code | 36 |
7706902084 | from bert_models.base_bert_model import BaseBertModel
import joblib
from sklearn.ensemble import GradientBoostingClassifier
import os
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.metrics import f1_score
class BaseBertModelWithBoost(BaseBertModel):
def __init_... | MariyaIvanina/articles_processing | src/bert_models/base_bert_model_with_boosting.py | base_bert_model_with_boosting.py | py | 4,205 | python | en | code | 3 | github-code | 36 |
44217228363 | """
@author: Miguel Taibo Martínez
Date: Nov 2021
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import gpflow
import pandas as pd
import sobol_seq
from gpflow.utilities import print_summary
from frontutils import get_pareto_undominated_by
class frontGP(object):
def __init__(se... | MiguelTaibo/DashboardMOO | streamlit-front/frontGP.py | frontGP.py | py | 8,161 | python | en | code | 0 | github-code | 36 |
4224070148 | import os
import argparse
import gzip
import sys
import time
import numpy as np
from multiprocessing import Pool
from contextlib import closing
import csv
import tensorflow as tf
from six.moves import urllib
bin_freq = 23
spect_width = bin_freq # Don't add one pixel of zeros on either side of the image
window_size = ... | KaranKash/DigitSpeak | untrained/load_data.py | load_data.py | py | 5,542 | python | en | code | 2 | github-code | 36 |
16221940900 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import unittest
from nose.tools import assert_in, assert_raises
from wechatsogou.const import WechatSogouConst
from wechatsogou.request import WechatSogouRequest
class TestBasicGenSearchArticleURL(unittest.TestCase):
... | chyroc/WechatSogou | test/test_request_gen_hot_url.py | test_request_gen_hot_url.py | py | 1,032 | python | en | code | 5,658 | github-code | 36 |
70376094505 | SPACE4 = " "*4
SPACE_SIZE = 4
MAX_CELL_LENGTH = 50
CONTROL_STATEMENTS = 'if,elif,else,while,def,for,try,except'.split(",")
REMOVE_VARS = ["_input_as_print", "_this_func", "_params", "_namespace", "_inputs", "_code"] # helpers for identifying scope
PRINT_INPUT_DEC = "!@#$@###"
SYMBOL_REPS = {">":"$gt",
"<":... | try-except-try-accept/trace_to_the_top | config.py | config.py | py | 604 | python | en | code | 0 | github-code | 36 |
73408801703 | from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import cgi
import string
import random
from controller import *
hostname="localhost"
serverport=8000
global userid
userid=1
class server(BaseHTTPRequestHandler):
def do_GET(self):
if self.path =='/':
self.send_response(200)
self.send... | crash1604/PurePythonBackend | server.py | server.py | py | 5,714 | python | en | code | 0 | github-code | 36 |
35058044672 | from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.engine import Engine
from sqlalchemy import event
import os
import sqlite3
database = SQLAlchemy()
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY = 'dev',
SQLALCHEMY_DATABASE... | Talha7011235/studentCourseInstructorDatabaseFlaskIndividualAssignment | backend/__init__.py | __init__.py | py | 857 | python | en | code | 0 | github-code | 36 |
9678451404 | def has_valid_checksum(card_number):
total = []
check_digit = None
if len(card_number) == 16:
check_digit = int(card_number[-1])
card_number = card_number[:-1]
# Multiply odd digits by 2 + # Subtract 9 to numbers over 9 #
for i, number in enumerate(card_number, start=1):
... | stasshi/SimpleBankingApp | banking/Test.py | Test.py | py | 718 | python | en | code | 0 | github-code | 36 |
28524863095 | import numpy as np
# Read matrix A and vector b from user input
n = int(input("Enter the size of the matrix: "))
A = np.zeros((n,n))
b = np.zeros(n)
for i in range(n):
row = input(f"Enter the coefficients of row {i+1} of matrix A, separated by spaces: ")
A[i,:] = np.array([float(x) for x in row.split()])
b... | umang27102001/AssignmentsMCA | assignmentNM/.py/assignment3A.py | assignment3A.py | py | 1,183 | python | en | code | 0 | github-code | 36 |
41898945847 | a = [11,2,1,15]
b = [235,127,19,4,12,23]
def smallest_pair():
a.sort()
b.sort()
i = 0
j = 0
current_pick = None
minimum = None
minimum_pair = None
while i < len(a) and j < len(b):
print(a[i], b[j], current_pick)
if a[i] <= b[j]:
if current_pick and current_p... | puyuan/codejam | practice/smallestdiffpairs.py | smallestdiffpairs.py | py | 1,219 | python | en | code | 0 | github-code | 36 |
71032555624 | """add adventure logs
Revision ID: 36dc23330424
Revises: 0db346b0362b
Create Date: 2022-02-06 21:15:27.347180
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '36dc23330424'
down_revision = '0db346b0362b'
branch_labels = None
depends_on = None
def upgrade():
... | lauraturnbull/griddle-earth | engine/migrations/alembic/versions/36dc23330424_add_adventure_logs.py | 36dc23330424_add_adventure_logs.py | py | 1,863 | python | en | code | 0 | github-code | 36 |
19565236986 | import spacy
nlp = spacy.load('en_core_web_md')
with open('movies.txt', 'r') as f_movies:
movies = f_movies.readlines()
compare_movie = ('''Planet Hulk: Will he save
their world or destroy it? When the Hulk becomes too dangerous for the
Earth, the Illuminati trick Hulk into a shuttle and launch him into... | vho1988/semantic_similarity | watch_next.py | watch_next.py | py | 921 | python | en | code | 0 | github-code | 36 |
20584236046 | from typing import *
class Solution:
def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
res = 0
totalNum = len(scores)
bestScoreOnPlayer = [0] * totalNum
score_age = sorted(list(zip(scores, ages)))
for i in range(totalNum):
for prev in range(i):... | RabbltMan/leetcode_dump | 1626/1626.py | 1626.py | py | 714 | python | en | code | 0 | github-code | 36 |
37636283080 | # Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.
# If there isn't any rectangle, return 0.
# Example 1:
# Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]
# Output: 4
# Example 2:
# Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4... | sunnyyeti/Leetcode-solutions | 939 Minimum Area Rectangle.py | 939 Minimum Area Rectangle.py | py | 1,086 | python | en | code | 0 | github-code | 36 |
8012209011 | from __future__ import absolute_import, print_function, division
from deepmedic.frontEnd.configParsing.utils import getAbsPathEvenIfRelativeIsGiven, parseAbsFileLinesInList, parseFileLinesInList, check_and_adjust_path_to_ckpt
from deepmedic.dataManagement import samplingType
class TrainSessionParameters(object) :
... | ZerojumpLine/OverfittingUnderClassImbalance | DeepMedic/deepmedic/frontEnd/configParsing/trainSessionParams.py | trainSessionParams.py | py | 52,975 | python | en | code | 21 | github-code | 36 |
31045721366 | import sys, getopt
import os, shutil
from subprocess import Popen, PIPE
def main(argv):
targetDir = ""
propFile = ""
try:
opts, args = getopt.getopt(argv, "hd:p:", ["help", "dir=", "prop="])
except getopt.GetoptError:
print("LockExternalsRevision.py -d <TargetDir> -p <SvnPropsFile>")
... | NguyenThanhDung/Study | Python/LockExternalsRevision.py | LockExternalsRevision.py | py | 1,206 | python | en | code | 0 | github-code | 36 |
42979785156 | from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render
from django.template import RequestContext
from .models import Project
# Create your views here.
def index(request):
'''Show all news'''
posts_list = Project.objects.all().order_by('-id')
paginator ... | gulla-k/pwd | project/views.py | views.py | py | 749 | python | en | code | 0 | github-code | 36 |
37630155256 | #!/usr/bin/env python
from net import *
import csv
import cv2
from cv_bridge import CvBridge, CvBridgeError
import os
import numpy as np
from PIL import Image
import tensorflow as tf
from skimage import color
import time
import rospy
from cone_detection.msg import Label
#Init ros.
rospy.init_node('local_network_test... | ProjectARCConeDetection/cone_detection | neural_net/local_network_test.py | local_network_test.py | py | 3,822 | python | en | code | 1 | github-code | 36 |
73921921384 | import pandas as pd
import sys, os, MySQLdb
import pandas as pd
import numpy as np
from collections import defaultdict
import click
db = MySQLdb.connect(host="localhost", user=os.environ["DATAVIVA2_DB_USER"],
passwd=os.environ["DATAVIVA2_DB_PW"],
db=os.environ["DATAVI... | vamsijkrishna/dataviva-scripts | scripts/rais_new/helpers/csv2hdf.py | csv2hdf.py | py | 3,228 | python | en | code | 0 | github-code | 36 |
32531618030 | """
Author: Michael Thompson (mjt106@case.edu)
Date: 9/20/2020
Brief: This file navigates commands input from the client physically accessing the device
"""
from src import client_command_list
import inspect
class ClientCommander:
def __init__(self):
self._client_command_list = client_command_list.Client... | Rembed/Rembed-EmbeddedBackend | src/client_commander.py | client_commander.py | py | 1,333 | python | en | code | 0 | github-code | 36 |
35919708000 | import difflib
import redis
from pymongo import MongoClient
client = MongoClient('mongodb+srv://Alex:goit123@utcluster.zrkwr.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
def add():
name = input('Enter name: ')
if db.ContactBook.find_one({'name': name}):
print(f"The record with name '{na... | AlexUtchenko/goit-python | WEB10/PA_Mongo_Redis_Nodic.py | PA_Mongo_Redis_Nodic.py | py | 4,975 | python | en | code | 0 | github-code | 36 |
34566807465 | import pytorch_lightning as pl
from transformers import AdamW
class DST_Seq2Seq(pl.LightningModule):
def __init__(self, args, tokenizer, model):
super().__init__()
self.tokenizer = tokenizer
self.model = model
self.lr = args["lr"]
def training_step(self, batch, batch_idx):
self.model.train()
outputs = s... | minson123-github/ADL21-Final-Project | T5DST/model.py | model.py | py | 1,211 | python | en | code | 0 | github-code | 36 |
33227873422 | import urllib.request
import sys
import time
from os import path
from os import popen
import argparse
def arguments():
"""Parse the arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('URL', help="URL of the file",
default=None, type=str)
parser.add_argument('... | TrendingTechnology/QuickWall | QuickWall/download.py | download.py | py | 4,652 | python | en | code | null | github-code | 36 |
3592670664 | from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from db.database import get_db
from security.auth import oauth2_scheme, get_current_user
from . import schemas, crud
router = APIRouter()
@router.post("/news/add")
async def add_new(title: str, desc: st... | ostrekodowanie/Synapsis | backend/api/news/routes.py | routes.py | py | 1,024 | python | en | code | 0 | github-code | 36 |
20926366393 | from .env_reader import env, csv
from .base import BASE_DIR
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')
ALLOWED_HOSTS = env('ALLOWED_HOSTS', cast=csv())
DATABASES = {
'de... | akkbaeva/sixbox_pr | src/sixbox_pr/settings/local.py | local.py | py | 426 | python | en | code | 0 | github-code | 36 |
9571125723 | #!/usr/bin/env python
import os, subprocess, sys, pwd, grp, stat
import socket, requests, json, yaml, time, logging, re, argparse
import paramiko
from pprint import pprint
_api = 'https://foobar.ru/api/'
user, group = pwd.getpwuid(os.getuid()).pw_name, grp.getgrgid(pwd.getpwuid(os.getuid()).pw_gid).gr_name
def get_h... | ttymonkey/python | file_sync/sync.py | sync.py | py | 7,025 | python | en | code | 0 | github-code | 36 |
26164662406 | import lpips
import numpy
import torch
import json
from skimage.metrics import structural_similarity as ssim
class ImageMetrics:
@staticmethod
def __l2__metric__tensor(first_image: torch.Tensor, second_image: torch.Tensor, range=255.):
return ImageMetrics.__l2_metric__numpy(first_image.numpy(), second_... | dinogrgic1/real-time-video-upscale-master-thesis | models/ImageMetrics.py | ImageMetrics.py | py | 4,275 | python | en | code | 0 | github-code | 36 |
39453776358 | from functools import reduce
class Solution:
def multiply(self, num1: str, num2: str) -> str:
sumList = []
i = 0
for a in num1[::-1]:
inta = int(a)
snum = 0
tempSingleList = []
for b in num2[::-1]:
intb = int(b)
... | haodongxi/leetCode | 43.py | 43.py | py | 1,429 | python | en | code | 0 | github-code | 36 |
19102436100 | # _*_ coding: utf-8 _*_
from pycse import regress
import numpy as np
time=np.array([0.0,50.0,100.0,150.0,200.0,250.0,300.0])
Ca=np.array([50.0,38.0,30.6,25.6,22.2,19.5,17.4])*1e-3
T=np.column_stack([time**0,time,time**2,time**3,time**4])
alpha=0.05
p,pint,se=regress(T,Ca,alpha)
print(pint)
# new one
... | ruanyangry/pycse-data_analysis-code | PYSCE-code/58.py | 58.py | py | 1,483 | python | en | code | 0 | github-code | 36 |
17041944520 | import numpy as np
import typing
import random
import string
import os
import pickle
import inspect
import time
# time stamp + line numbers
def write_log(file, timestamp, function_name, input_ids=[], output_ids=[], frame=None, args=None):
# if function_name == '__getitem__': # handle edge case
# return
... | j2zhao/DSClean | ds_clean/logged_array.py | logged_array.py | py | 11,555 | python | en | code | 0 | github-code | 36 |
18374339178 | import numpy as np
from src.utils import *
def ica(X, iterations, limit = 1e-5):
X = center(X)
X = whiten(X)
dim = X.shape[0]
W = np.zeros((dim, dim), dtype=X.dtype)
for i in range(dim):
w = np.random.rand(dim)
for j in range(iterations):
w_new = update_w(w, X)
if i >= 1:
w_new -=... | sashrika15/Unsupervised_Learning_Algorithms | component_analysis/ICA/src/ica.py | ica.py | py | 519 | python | en | code | 7 | github-code | 36 |
10411828796 | import text_file as tf
import text_dictionary as td
import text_corpus as tc
import text_sentence_extraction as se
def task_9(texts_dir, output_dir):
output_filename = "task_9"
text = tc.get_corpus_text(texts_dir)
normalized_dict = td.create_normalized_dictionary(text)
result = td.dictionary_to_string... | EkatherinaS/Data-Analysis-Technologies-in-Internet | Lab1/lab1.py | lab1.py | py | 2,200 | python | en | code | 0 | github-code | 36 |
8756905825 | # -*- coding: utf-8 -*-
from odoo import fields, models, api
class AccountJournal(models.Model):
_inherit = 'account.journal'
of_pos_payment_mode_ids = fields.Many2many(
comodel_name='of.account.payment.mode', string=u"Mode de paiement associé au journal pour le point de vente")
class AccountMoveL... | odof/openfire | of_point_of_sale/models/account.py | account.py | py | 2,047 | python | fr | code | 3 | github-code | 36 |
37000566143 | from itertools import product
from messenger import *
def _write_matrix(builder, matrix):
# Write as column major
for col, row in product(range(4), range(4)):
# Float here since ShuffleLog stores matrices as float
builder.add_float(matrix[row][col])
class ShuffleLogAPI:
_MSG_QUERY_ENVIRONM... | recordrobotics/Jetson2023 | borrowed/TagTracker-master/src/shufflelog_api.py | shufflelog_api.py | py | 2,316 | python | en | code | 0 | github-code | 36 |
37084706650 | import asyncio
import aiohttp
from aiohttp import ClientSession
from utils import page_status
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from fake_useragent import UserAgent
from selenium.webdriver.common.by import By
class PriseParser:
ATB_regular_divclass = ... | Sautenko-Andrey/OOP-and-other | selenium_python/chrome_driver/simple_try.py | simple_try.py | py | 2,459 | python | en | code | 0 | github-code | 36 |
3826160034 | """empty message
Revision ID: 14c462e99a28
Revises: 630e94f464d4
Create Date: 2021-09-16 16:48:21.728550
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '14c462e99a28'
down_revision = '630e94f464d4'
branch_labels = None
depends_on = None
def upgrade():
# ... | knedgen/flaskwebsiteproject | migrations/versions/14c462e99a28_.py | 14c462e99a28_.py | py | 649 | python | en | code | 0 | github-code | 36 |
24327828185 | import os, socket
from time import time
import numpy as np
import tensorflow as tf
tf_float_prec = tf.float64
from pdb import set_trace as st
#from keras import backend as K
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM as LSTM_LAYER
#from keras.models import Sequenti... | mattweiss/public | deeplearning/networks/lstm_tf.py | lstm_tf.py | py | 11,298 | python | en | code | 0 | github-code | 36 |
3801917693 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from collections import namedtuple
import inspect
ControllableAttributeConfig = namedtuple("ControllableAttributeConfig", "driven_attribute ignored_attributes facemodel_param_name facemodel_param_value facemodel_param_value_other")
class ... | microsoft/ConfigNet | confignet/metrics/controllability_metric_configs.py | controllability_metric_configs.py | py | 4,045 | python | en | code | 104 | github-code | 36 |
27596382692 | import matplotlib.pyplot as plot
import gradientDescent as gd
import loadData as data
import numpy as np
def plotConvergence(J_history):
plot.figure()
plot.plot(range(len(J_history)), J_history, 'bo')
plot.title(r'Convergence of J($\theta$)')
plot.xlabel('Number of iterations')
plot.ylabel(r'J($\th... | mirfanmcs/Machine-Learning | Supervised Learning/Linear Regression/Linear Regression with One Variable/Python/plotConvergence.py | plotConvergence.py | py | 578 | python | en | code | 0 | github-code | 36 |
22636173430 | # scapy 패키지 import
from scapy.all import *
# Pcap 파일 읽기
def pcap_read(filiepath):
packets = rdpcap(filiepath)
data = dict()
detect = dict()
suspect = dict()
data['total_pks'] = len(packets)
try :
# filename 추출
for packet in packets:
filename = None
if pac... | Junghayeon/security_capstone_design | malware.py | malware.py | py | 1,317 | python | en | code | 0 | github-code | 36 |
38715938852 | #!/usr/bin/env python3
with open('input.txt', 'r') as f:
sizes = [int(a) for a in f.readline().strip().split(',')]
message = list(range(256))
skip = 0
loc = 0
for size in sizes:
end = loc + size
if end > len(message):
at_start = loc + size - len(message)
at_end = size - at_start
t... | lvaughn/advent | 2017/10/hash.py | hash.py | py | 735 | python | en | code | 1 | github-code | 36 |
36121022223 | import os
from pathlib import Path
from forte.data.base_pack import PackType
from forte.evaluation.base import Evaluator
from forte.data.extractor.utils import bio_tagging
from ft.onto.base_ontology import Sentence, Token, EntityMention
def _post_edit(element):
if element[0] is None:
return "O"
return... | asyml/forte | examples/tagging/evaluator.py | evaluator.py | py | 3,552 | python | en | code | 230 | github-code | 36 |
17684698502 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import biplist
import os.path
application = defines.get('app', '../dist/AYAB-Launcher.app')
appname = os.path.basename(application)
format = defines.get('format', 'UDBZ')
size = defines.get('size', None)
files = [ application ]
symlinks = { 'Applications... | Adrienne200/ayab-desktop | mac-build/dmg_settings.py | dmg_settings.py | py | 845 | python | en | code | null | github-code | 36 |
27438339817 | #!/usr/bin/env python
#coding:utf-8
from math import *
from string import *
from fractions import *
from itertools import *
def sieve(N):
primes = set()
for i in range(2,N):
primes.add(i)
for i in range(2,ceil(sqrt(N))):
if i in primes:
for j in range(i*i,N,i):
... | tomoki/project-euler | 46/main.py | main.py | py | 627 | python | en | code | 0 | github-code | 36 |
1021808135 | import cv2
import numpy as np
import os
import pyrealsense2 as rs
# Ім'я каталогу, в якому будуть зберігатися зображення
save_dir = "path/to/save/directory"
# Ініціалізація камери
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
config.enable_stream(rs.... | Roman212Koval/Dual-channel_CNN | make_dataset.py | make_dataset.py | py | 1,838 | python | uk | code | 1 | github-code | 36 |
21172342682 | from __future__ import absolute_import
import json
from keshihua.celery import app
from datetime import datetime
from demo.pachong import new_job
from demo.graph import avg_salary,lan_fre,bar_job,job_cate,jieba_count
# 数据更新
@app.task
def start_get_data():
print('正在获取并更新数据...')
count=new_job()
print('处理专业薪... | junhqin/SH-Internship-KSH | CeleryTask/task.py | task.py | py | 1,085 | python | en | code | 1 | github-code | 36 |
37215946531 | from django.core.management.base import BaseCommand
from academ.models import Apartment, Building, ImageGallery
import json
import os
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
def check_apartment(building):
"""
Проверка на наличие квартир в базе.
Если к... | pepegaFace/freedom | freedom/academ/management/commands/content_generator.py | content_generator.py | py | 4,319 | python | en | code | 1 | github-code | 36 |
21167613561 | from application import app
from flask import render_template
from application.models import *
from flask_restplus import Api, Resource, fields
from flask.ext.restplus.reqparse import RequestParser
from flask.ext.restplus.inputs import date
api = Api(app, version='1.0', title='ElesVotam API')
ns = api.namespace('elesv... | okfn-brasil/elesvotam | application/manager.py | manager.py | py | 4,853 | python | pt | code | 0 | github-code | 36 |
74050386664 | import parlai.core.build_data as build_data
import os
import subprocess
import shutil
import csv
import time
from parlai.core.build_data import DownloadableFile
from parlai.utils.io import PathManager
RESOURCES = [
DownloadableFile(
'https://github.com/deepmind/narrativeqa/archive/master.zip',
'nar... | facebookresearch/ParlAI | parlai/tasks/narrative_qa/build.py | build.py | py | 5,467 | python | en | code | 10,365 | github-code | 36 |
39610379992 | # Realizar un programa que permita ingresar el número de mes de un año (1,…,12), en base al
# valor ingresado presenta el número de días que tiene ese mes.
def main():
titulo_1 = "cantidad de días según el mes"
titulo_2 = titulo_1.upper()
print(titulo_2)
mes = int(input("Ingrese el número del mes: "))... | jeanchuqui/fp-utpl-18-evaluaciones | eval-parcial-primer-bimestre/Ejercicio6.py | Ejercicio6.py | py | 706 | python | es | code | 0 | github-code | 36 |
13617657820 | import unittest
from datetime import datetime
from pathlib import Path
from we1s_chomp import db, model
class TestModel(unittest.TestCase):
def setUp(self):
self.dirpath = Path("test/data")
def test_source(self):
# Create source.
source = model.Source(
name="we1s",
... | seangilleran/we1s_chomp | test/test_model.py | test_model.py | py | 3,618 | python | en | code | 1 | github-code | 36 |
73037188583 | # example URL(postgres): postgresql://username:password@host:port/database_name (postgresql://postgres:postgres@localhost:5432/mydatabase)
import pandas as pd
import json
import sqlalchemy as sql
from sqlalchemy import create_engine
from sqlalchemy_utils import create_database, database_exists
class DatabaseHandler:
... | Christian125px/team_project2 | src/database_handler.py | database_handler.py | py | 3,270 | python | en | code | 0 | github-code | 36 |
42939386801 | import os.path as osp
import numpy as np
import torch
import torch.utils.data as Data
from PIL import Image
__all__ = ['CUB_200_2011']
class CUB_200_2011(Data.Dataset):
def __init__(self, root_dir, phase='train', transform=None):
super(CUB_200_2011, self).__init__()
assert phase in ('train', 'va... | SmallHedgehog/ZeroShotLearning | dataset/CUB_200_2011.py | CUB_200_2011.py | py | 3,311 | python | en | code | 2 | github-code | 36 |
17561628211 | def calculaFatorial(n):
nFat = 1
while n > 0:
nFat = nFat * n
n -= 1
return nFat
def informaNumero():
n = 0
while n >= 0:
n = int(input("informe um numero inteiro: "))
if n < 0:
print("Digite um valor positivo.\n"
"Tchau.")
brea... | wpaulow/coursera-python-1 | funcao-printFatorial.py | funcao-printFatorial.py | py | 399 | python | pt | code | 0 | github-code | 36 |
43735554270 | # Chapter V problem VI by Vincenzo Scotto Di Uccio
def main():
f_g = input("Enter the total amount of fat grams: ")
c_g = input("Enter the total amount of carbohydrate grams: ")
f_g = input_valid(f_g)
c_g =input_valid(c_g)
calculate(f_g,c_g)
def calculate(fat,carb):
c... | vincenzo-scotto001/Python | chp5 problems/sco.chp5prob6.py | sco.chp5prob6.py | py | 1,203 | python | en | code | 0 | github-code | 36 |
5780964210 | from pygame import Surface, image, mixer
import os
from engine.common.validated import ValidatedDict
from engine.common.constants import LogConstants
from engine.common.logger import LogManager
class AssetManager:
'''
Asset loaders, renderers, transformers and more!
'''
asset_prefix = "./engine/assets... | Based-Games/BasedEngine | engine/common/asset.py | asset.py | py | 2,000 | python | en | code | 0 | github-code | 36 |
19139046842 | import sys
import pathlib
# base.pyのあるディレクトリの絶対パスを取得
current_dir = pathlib.Path(__file__).resolve().parent
# モジュールのあるパスを追加
sys.path.append(str(current_dir) + "/../")
import pandas as pd
import numpy as np
from mylib.address import Address
from mylib.mypandas import MyPandas as mp
import pandas as pd
import time
... | sunajpdev/estates_appsheet | tool/estate_csv_setting.py | estate_csv_setting.py | py | 1,145 | python | en | code | 0 | github-code | 36 |
1123611190 | #!/usr/bin/python3
if __name__ == "__main__":
"""Print the addition of all arguments."""
import sys
summation = 0
for fig in range(len(sys.argv) - 1):
summation += int(sys.argv[fig + 1])
print("{}".format(summation))
| Fran6ixneymar/alx-higher_level_programming | 0x02-python-import_modules/3-infinite_add.py | 3-infinite_add.py | py | 247 | python | en | code | 0 | github-code | 36 |
22861406972 | # ---------- PROBLEM ----------
# Create a random list filled with the characters H and T
# for heads and tails. Output the number of Hs and Ts
# Example Output
# Heads : 46
# Tails : 54
# Create the list
import random
flipList = []
# Populate the list with 100 Hs and Ts
# Trick : random.choice() returns a random ... | chriskok/PythonLearningWorkspace | fliplist.py | fliplist.py | py | 501 | python | en | code | 1 | github-code | 36 |
37683812851 | from django.conf.urls import url, include
from .views import TopicDetailView, QuestionDetailView, TopicListView
urlpatterns = [
url(r'^$', TopicListView.as_view(), name='topic-list'),
url(r'^(?P<pk>\d+)/', include([
url('^$', TopicDetailView.as_view(), name='topic-detail'),
url(r'^question-(?P... | unixander/TestsApp | apps/questions/urls.py | urls.py | py | 401 | python | en | code | 0 | github-code | 36 |
14416867511 |
import sys
sys.path.append("..\\..\\public")
import dunhe_public
import auto
##bat的命令参数
##python auto_ risk_data_manage
if __name__ == '__main__':
if len(sys.argv) > 1:
logger = dunhe_public.SetLog("auto_start")
auto_instance = auto.AutoStartExe(logger)
auto_instance.load_config(sys.argv[1... | matthew59gs/Projects | python/other/autoit/main.py | main.py | py | 368 | python | ja | code | 0 | github-code | 36 |
13989773677 | # -*- coding: utf-8 -*-
import time
import numpy
from ntplib import NTPClient
from .base import Utils, MultiTasks
from .task import IntervalTask
from .future import ThreadPool
from hagworm.extend.error import NTPCalibrateError
from hagworm.extend.interface import TaskInterface
class _Interface(TaskInterface):
... | wsb310/hagworm | hagworm/extend/asyncio/ntp.py | ntp.py | py | 4,131 | python | en | code | 13 | github-code | 36 |
1846177461 | from liberouterapi import app, config
from liberouterapi.dbConnector import dbConnector
from liberouterapi.modules.module import Module
# Load NEMEA configuration file if nemea section is not present in current config
if "nemea" not in config.config.sections():
config.load(path = __path__[0] + '/config.ini')
c... | zidekmat/nemea-gui | backend/__init__.py | __init__.py | py | 4,924 | python | en | code | 0 | github-code | 36 |
5743766982 | from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
class Vader:
def __init__(self):
self.analyzer = SentimentIntensityAnalyzer()
def AnalyzeSentence(self, sentence):
vs = self.analyzer.polarity_scores(sentence)
if(vs['compound'] >= 0):#.05):
return 1
... | rafaatsouza/ufmg-practical-assignments | natural-language-processing/final-assignment/source/Vader.py | Vader.py | py | 781 | python | en | code | 1 | github-code | 36 |
19102323120 | # _*_ coding: utf-8 _*_
import numpy as np
n1=30 #students in class A
x1=78.0 #average grade in class A
s1=10.0 #std dev of exam grade in class A
n2=25 #students in class B
x2=85.0 #average grade in class B
s2=15.0 #std dev of exam grade in class B
# the standard ... | ruanyangry/pycse-data_analysis-code | PYSCE-code/40.py | 40.py | py | 851 | python | en | code | 0 | github-code | 36 |
7285626466 | # -*- coding: utf-8 -*-
from datetime import datetime
from dateutil.parser import parse
import os
import json
from pyramid.view import view_config
from pyramid.security import remember
from pyramid.httpexceptions import HTTPFound
from pyramid.security import (
Allow,
Everyone,
)
from pyramid.view import... | cati-neuroimaging/casa_cloud | casa_cloud/views.py | views.py | py | 5,714 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.