seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
26994135313 | from django.urls import path
from Zoo import views
import templates
urlpatterns = [
path('login/', views.user_login, name='login'),
path('logout/',views.logout, name='logout'),
path('user_create/', views.user_create, name='user_create'),
path('index/', views.index, name='index'),
path('detail/<i... | klll2/Zoozoo1 | Zoo/urls.py | urls.py | py | 886 | python | en | code | 1 | github-code | 6 |
36647480067 | import collections
from .pybeesgrid import TAG_SIZE, NUM_CONFIGS, NUM_MIDDLE_CELLS
from .pybeesgrid import GridGenerator, BadGridArtist, BlackWhiteArtist, \
MaskGridArtist, DepthMapArtist
from .pybeesgrid import drawGrids
from .pybeesgrid import INNER_BLACK_SEMICIRCLE, CELL_0_BLACK, CELL_1_BLACK, \
CELL_2_BLA... | berleon/pybeesgrid | python/beesgrid/__init__.py | __init__.py | py | 5,325 | python | en | code | 0 | github-code | 6 |
23018030287 | import time
from openerp.report import report_sxw
from openerp.osv import osv
class report_common(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context=None):
super(report_common, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
... | QinerTech/vehicle_sales | vehicle_sales_contract_print/report/report.py | report.py | py | 2,001 | python | en | code | 0 | github-code | 6 |
11481741965 | import json
import random
while True:
inp = input("> ")
ints = {}
with open('intents.json', 'r') as f:
json.dump(f, ints)
try:
if ints[inp].type() == list:
val = random.choice(ints[inp])
else:
val = ints[inp]
print(val)
except:
print("... | poopcoder/Game | chat/code.py | code.py | py | 341 | python | en | code | 0 | github-code | 6 |
37080131599 | def solution(s):
from collections import deque
answer = ''
s = deque(s)
while s:
a = s.popleft()
if answer:
if answer[-1] == ' ':
answer += a.upper()
else:
answer += a.lower()
else:
answer += a.upper()
return... | JeonggonCho/algorithm | 프로그래머스/lv2/12951. JadenCase 문자열 만들기/JadenCase 문자열 만들기.py | JadenCase 문자열 만들기.py | py | 327 | python | en | code | 0 | github-code | 6 |
24023635631 | import sys
def parse_text(start_state, rules_for_state, fileinput_gen, file=None):
if file:
f = open(file, 'w+')
sys.stdout = f
line_number = 1
state = start_state
text = ''.join(fileinput_gen)
start_index = 0
end_index = len(text)
while start_index < end_index:
bes... | marinsokol5/ppj_lab | lab1_python/source/analizator/AnalizatorBackBone.py | AnalizatorBackBone.py | py | 1,285 | python | en | code | 0 | github-code | 6 |
8649505528 | # 10845 : 큐
import sys
n = int(sys.stdin.readline()) # n 입력받기
arr = []
for i in range(n) : # n 번만큼 반복해서 명령어 입력받기
command = sys.stdin.readline().split()
func = command[0] # func : 명령어
if len(command) == 2 : # push : 명령어와 숫자가 동시에 들어올 때
arr.append(command[... | kimhn0605/BOJ | Algorithm/자료 구조/10845.py | 10845.py | py | 1,146 | python | ko | code | 0 | github-code | 6 |
38760633775 | import netCDF4
import numpy as np
import numexpr as ne
import math
import os
import sys
import re
import tempfile
from collections import OrderedDict
from pprint import pformat
from scipy.interpolate import griddata
from geophys_utils._crs_utils import transform_coords, get_utm_wkt, get_reprojected_bounds, get_spatial_... | GeoscienceAustralia/geophys_utils | geophys_utils/_netcdf_point_utils.py | _netcdf_point_utils.py | py | 66,225 | python | en | code | 22 | github-code | 6 |
31106779539 | from datetime import datetime
import requests
import pandas as pd
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.postgres_operator import PostgresOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from psycopg2.extras import execute_v... | jorge-flores-py/rick-morty | dags/dag_carga_automatica_episodios.py | dag_carga_automatica_episodios.py | py | 2,329 | python | es | code | 0 | github-code | 6 |
72052702908 | #!/usr/bin/env python
# coding: utf-8
""" This script collects all the data in orgs and sources folders and merge them in a single json file. """
import json, pathlib, os, sys
### ENVIRONMENTAL VARIABLES
# environmental variables can be set in order to override default values
# NOTE: you can use relative or absolute... | italia/public-opendata-sources | export_all.py | export_all.py | py | 8,264 | python | en | code | 17 | github-code | 6 |
2078438087 | # -*- coding: utf-8 -*-
from django_webtest import DjangoTestApp, WebTestMixin
import pytest
from testapp.articles.factories import AuthorFactory, ArticleFactory, TeamFactory
@pytest.fixture(scope='function')
def app(request):
wtm = WebTestMixin()
wtm._patch_settings()
wtm._disable_csrf_checks()
req... | odoku/django-searchview | tests/conftest.py | conftest.py | py | 846 | python | en | code | 0 | github-code | 6 |
16314867701 | import sqlite3
import sys
import datetime
from collections import defaultdict
from stats_ui_window import Ui_StatWindow
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow_EXEC():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
... | chrisw706/examination_stats | Stats/Python/Stats.py | Stats.py | py | 7,488 | python | en | code | 0 | github-code | 6 |
33595344312 | from django.http import JsonResponse
from base.views import chekctoken
WHITE_URLS = ( '/apis/login/')
class RequestMideleware(object):
def process_request(self, request):
if request.path_info in WHITE_URLS:
return
try:
ret = chekctoken(request)
i... | Hchenwy/web | www/server/base/middleware.py | middleware.py | py | 514 | python | en | code | 0 | github-code | 6 |
24961044066 | #!/usr/bin/env python
from std_msgs.msg import String
from math import pi
from sensor_msgs.msg import PointCloud2
import rospy
import sensor_msgs.point_cloud2 as pc2
import ros_numpy
import numpy as np
import sys
import copy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
# UR Robot
robot = Non... | vincent51689453/ur3_edge_follower | src/edge_follower/ur_robot.py | ur_robot.py | py | 2,802 | python | en | code | 0 | github-code | 6 |
9137033058 | import os
import pandas as pd
from scipy.io import loadmat
def load_data():
list_of_files = os.listdir("data\\Identification\\MFCC\\")
cumulative_df = pd.DataFrame()
for file in list_of_files:
data_set = loadmat("data\\Identification\\MFCC\\" + file)
features = data_set['feat']
lab... | PGG106/ReadMat | utils.py | utils.py | py | 1,004 | python | en | code | 0 | github-code | 6 |
37188371889 | import os
import csv
import math
import numpy as np
import nltk
from nltk.corpus import stopwords
import collections
import string
import re
from sklearn.model_selection import KFold
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Emb... | arinjayakhare1/Real-Time-Tweet-Classifier-using-RLAN | test/old codes/testWithThreads/initTrainer/old Programs/initTrainer.py | initTrainer.py | py | 6,270 | python | en | code | 0 | github-code | 6 |
11706943391 | from string import ascii_lowercase, ascii_uppercase
from utils.data import read_data_as_list
characters = list(ascii_lowercase) + list(ascii_uppercase)
priority_lookup = dict(zip(characters, range(1, len(characters) + 1)))
rucksacks = read_data_as_list(day=3)
# Part 1
total = 0
for rucksack in rucksacks:
midpo... | stuartjwright/advent_of_code_2022 | day_03.py | day_03.py | py | 902 | python | en | code | 0 | github-code | 6 |
73499996027 | import numpy as np
from numpy import ma
import xarray as xr
from netCDF4 import Dataset
import struct
import sys
import os
import datetime as dt
import glob
"""
This module contains functions for reading external data
to use with LPT.
The data_read_function is called at various points in other LPT functions.
To add ... | brandonwkerns/lpt-python-public | lpt/readdata.py | readdata.py | py | 19,320 | python | en | code | 3 | github-code | 6 |
37559032301 | import numpy as np
def fitness(f, x):
"""
Supplied function f(x) returns a value for fitness so long as f(x) has a range >= 0
:param f:
:param x:
:return:
"""
# return np.exp(f(x))
# e^y made table unreadable from extremely small numbers
# return f(x) if (int(x,2) > 0 and int(x,2) ... | shottah/expert-systems | assignment-3/GA.py | GA.py | py | 2,807 | python | en | code | 0 | github-code | 6 |
5454371991 | """
Problem:
1. Two Sum
Difficulty:
Easy
URL:
https://leetcode.com/problems/two-sum
Tags:
Array, Hash Table
Date:
2022-05-10T14:00:29.877163+08:00
"""
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, num in enumerate(nums):
... | s0u0b/leetcode | solutions/a00001_two_sum.py | a00001_two_sum.py | py | 630 | python | en | code | 0 | github-code | 6 |
43954128076 | import json
import requests # see http://python-requests.org
def url_for(endpoint):
return 'http://localhost:5000/{}/'.format(endpoint)
def delete_all_people():
r = requests.delete(url_for('people'))
print("'people' deleted, server response:", r.status_code)
def post_people():
data = [
{'... | talkpython/eve-building-restful-mongodb-backed-apis-course | code/clients/client.py | client.py | py | 1,081 | python | en | code | 62 | github-code | 6 |
11250773237 | import connexion
from openapi_server import orm
from openapi_server.db import db
from openapi_server.models.error import Error # noqa: E501
from openapi_server.models.qc_result import QcResult # noqa: E501
def samples_id_qc_result_delete(id): # noqa: E501
"""samples_id_qc_result_delete
Delete the QC resu... | Mykrobe-tools/mykrobe-atlas-tracking-api | openapi_server/controllers/qc_result_controller.py | qc_result_controller.py | py | 1,810 | python | en | code | 0 | github-code | 6 |
75051529788 | import logging
import random
from typing import Set, Generator, Optional
from .location import Location
from .move import Move
from .piece import Color, Piece, Rank
from .board import Board
class MoveSet:
_brd = None # type: Board
@staticmethod
def set_board(brd: Board) -> None:
r""" Sets the b... | ZaydH/stratego | src/stratego/player.py | player.py | py | 14,932 | python | en | code | 0 | github-code | 6 |
21276696396 | import mindspore
from mindspore import Tensor, nn
from mindspore.common.initializer import Uniform, VarianceScaling
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from mindspore_rl.agent.actor import Actor
from mindspore_rl.agent.learner import Learner
from mindspore_rl.utils import... | mindspore-lab/mindrl | mindspore_rl/algorithm/ddpg/ddpg.py | ddpg.py | py | 10,399 | python | en | code | 21 | github-code | 6 |
21394429670 | import numpy as np
import statistics
from scipy import stats
dataset= [5,6,7,5,6,5,7,4,5,5,5,5,7,5,6,6,7,6,6,7,7,7,6,5,6]
#mean value
mean= np.mean(dataset)
#median value
median = np.median(dataset)
#mode value
mode= stats.mode(dataset)
#standard Deviation
Std = statistics.stdev(dataset)
#Variance
Var = statistic... | lamyanlok/FTDS | test.py | test.py | py | 447 | python | en | code | 0 | github-code | 6 |
4552178157 | # Busca Local Múltiplos Inicios
# Local Search Multiple Starts
import sys
import time
sys.path.insert(1, '../stage_01')
sys.path.insert(1, '../')
from utils import corrent_solution_size, objetive_function, read_instance, viable_solution
from local_search import local_search
from semi_greedy import semi_greedy
import c... | guilhermelange/Test-Assignment-Problem | stage_02/multiple_starts_local_search_02.py | multiple_starts_local_search_02.py | py | 1,452 | python | en | code | 0 | github-code | 6 |
35007890164 | from src.main.python.Solution import Solution
from src.main.python.datastructures.Interval import Interval
# Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
#
# You may assume that the intervals were initially sorted according to their start times.
#
# Example 1... | renkeji/leetcode | python/src/main/python/Q057.py | Q057.py | py | 1,332 | python | en | code | 0 | github-code | 6 |
72438613309 | from fastapi import APIRouter, Body, Depends, Request, status
from fastapi.responses import JSONResponse
from jarvis.db.database import DataBase, get_database
from jarvis.core import config, utils
from jarvis.lib import TwilioHelper
from typing import Dict
from twilio.rest import Client
import jarvis.crud as crud
impor... | christian-miljkovic/jarvis | jarvis/api/v1/user_endpoint.py | user_endpoint.py | py | 2,604 | python | en | code | 0 | github-code | 6 |
26420619240 | from datetime import timedelta, datetime
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from jose import jwt, JWTError
from app import database, models
from app.schemas import TokenData
from app.config ... | AdityaPunetha/FastAPI-Full-Devlopment | app/oauth2.py | oauth2.py | py | 1,771 | python | en | code | 2 | github-code | 6 |
8950963065 | import requests
from bs4 import BeautifulSoup
import pandas as pd
from os import listdir, remove
import datetime as dt
from time import sleep
from MainMethods import getInfo, showDays
from conf import INT, INF, URL, LOC, NINF, LOC2,\
chosenF, errorsF, doneF
"""
The information for saved days is checke... | Stryder-Git/Movati_Signup | Get_Reqs.py | Get_Reqs.py | py | 7,822 | python | en | code | 0 | github-code | 6 |
16704619000 | #!/usr/bin/env python
# Code property of Matteo Scanavino - matteo.svanavino@gmail.it
# Minor changes by Iris David Du Mutel
import rospy
# from std_msgs.msg import Float32MultiArray
from myrobot.msg import vect_msg
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
import cv2
# import cv2.cv
import... | IrisDuMutel/myrobot | scripts/green_ball.py | green_ball.py | py | 4,054 | python | en | code | 1 | github-code | 6 |
1346892633 | import threading
import socket
def server_echo (sock):
while True:
conn, addr = sock.accept()
while True:
data = conn.recv(1024)
if not data: break
if data == b"close":
# print ("Close connection")
break
... | gusevna/webserver | 02_webserver.py | 02_webserver.py | py | 651 | python | en | code | 0 | github-code | 6 |
30497846861 | import unittest
from main import *
class TestEveryMethodInMain(unittest.TestCase):
def test_GetContainer(self):
self.assertIsNotNone(getPricesContainer())
self.assertIsNotNone(returnListedPricesToServer())
self.assertIsNotNone(returnInOrderedPricesToServer())
#checkPriceDiffWithDataba... | rekjef/rl-tools | Price tracker/tests.py | tests.py | py | 1,698 | python | en | code | 0 | github-code | 6 |
75188708346 | # May 10, 1981 00:31
# 정보 취합
month, day, year, time = input().split()
day = int(day[:-1])
year = int(year)
hour, minute = map(int, time.split(':'))
# 윤년 여부에 따라 2월 날짜 변경
month_name_lst = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
month_days_... | zacinthepark/Problem-Solving-Notes | boj/1340.py | 1340.py | py | 765 | python | ko | code | 0 | github-code | 6 |
71567925627 | import os
while True:
info = input().split("-")
if info[0] == 'Create':
file = open(f"files/{info[1]}", "w")
file.close()
elif info[0] == 'Add':
with open(f"files/{info[1]}", "a") as file:
file.write(f"{info[2]}\n")
elif info[0] == 'Replace':
try:
... | lorindi/SoftUni-Software-Engineering | Python-Advanced/7.File Handling/3_file_manipulator.py | 3_file_manipulator.py | py | 879 | python | en | code | 3 | github-code | 6 |
18667310322 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import sublime, sublime_plugin
from os import path
class GoToPackageFileCommand(sublime_plugin.TextCommand):
def ru... | Eliga/sublime-update-package-js | GoToPackageFile.py | GoToPackageFile.py | py | 989 | python | en | code | 1 | github-code | 6 |
27099720616 | import xlwt
import numpy as np
import os
import os.path
import colour
from ..configuration.base_configuration import Filter
from ..configuration.base_configuration import TimeOfDayFilter
from ..core.status import Status
from plots import MatplotlibPlotter
from power_deviation_matrix import PowerDeviationMatrixSheet... | PCWG/PCWG | pcwg/reporting/reporting.py | reporting.py | py | 47,780 | python | en | code | 23 | github-code | 6 |
26043118086 | from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.java.target_types import JavaSourcesGeneratorTarget
from pants.backend.java.target_types import rules as target_types_rules
from pants.core.util_rules import config_files, source_files
from pants.engine.addresses import A... | pantsbuild/pants | src/python/pants/jvm/resolve/coursier_fetch_test.py | coursier_fetch_test.py | py | 4,186 | python | en | code | 2,896 | github-code | 6 |
70321394427 | import multiprocessing as mp
from skopt import Optimizer
from skopt.space import Real, Integer
import subprocess
import time
import pickle
from ID_CNN_V01 import setup_thread_environment
from _utils.ID_utils import get_convolutions, Colors, check_available_gpus
n_calls = 7
dim_learning_rate = Real(low=1e-7, high=3e-... | lorenz-h/DataRepresentationLearning | Old Experiments/ImitationDuckie_V1/_old_versions/ID_Optimizer.py | ID_Optimizer.py | py | 4,792 | python | en | code | 0 | github-code | 6 |
22176331977 | import networkx as nx
from networkx.algorithms import community
from nltk.corpus import stopwords
import re
def build_graph(text):
word_list = []
G = nx.Graph()
for line in text:
line = (line.strip()).split()
for i, word in enumerate(line):
if i != len(line)-1:
w... | michal-pikusa/topic-network | topicnetwork/__init__.py | __init__.py | py | 2,066 | python | en | code | 1 | github-code | 6 |
70820187389 | from lifxlan import *
import subprocess
import random
lights_name = {
"lit" : "Lit_haut",
"couloir" : "Couloir",
"wc" : "Wc",
"cuisine" : "Cuisine"
}
colors = {
"rouge" : [65535, 65535, 65535, 3500],
"orange" : [5525, 65535, 65535, 3500],
"jaune" : [7000, 65535, 65535, 3500],
"vert" : ... | devauxa/harriette | script/light.py | light.py | py | 3,774 | python | en | code | 0 | github-code | 6 |
42162211409 | """tilltheend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | king9799/7-1-projects | forever/urls.py | urls.py | py | 1,695 | python | en | code | 0 | github-code | 6 |
32284951119 | #!/usr/bin/env python
from sc_expwn import * # https://raw.githubusercontent.com/shift-crops/sc_expwn/master/sc_expwn.py
bin_file = './streaming'
context(os = 'linux', arch = 'amd64')
# context.log_level = 'debug'
#==========
env = Environment('debug', 'local', 'remote')
env.set_item('mode', debug = 'DEBUG', loc... | shift-crops/CTFProblemArchive | 2017/SECCON Finals/Domestic/fuchu/streaming/exploit.py | exploit.py | py | 5,229 | python | en | code | 1 | github-code | 6 |
27099804006 | from grid_box import GridBox
class PortfolioDialog:
def getInitialFileName(self):
return "portfolio"
def getInitialFolder(self):
return preferences.portfolio_last_opened_dir()
def addFormElements(self, master):
self.description = self.... | PCWG/PCWG | test-gui/gui/pcwg_ui/portfolio.py | portfolio.py | py | 10,704 | python | en | code | 23 | github-code | 6 |
32644493827 | import pymel.core as pm
from mgear.core import attribute
class customShifterMainStep(object):
'''
Main Class for shifter custom steps
'''
def __init__(self, stored_dict):
"""Constructor
"""
self._step_dict = stored_dict
@property
def mgear_run(self):
"""Return... | mgear-dev/mgear4 | release/scripts/mgear/shifter/custom_step.py | custom_step.py | py | 2,657 | python | en | code | 209 | github-code | 6 |
27551842247 | #K-Nearesst Neighbour
#importing the Librares
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#set the index value as index_col 0
data=pd.read_csv('./Dataset/Classified Data',index_col=0)
#standardize the values
from sklearn.preprocessing import StandardScaler
#Create a... | kamarajanis/Machine-Learning | K_Nearest_Neighbor/k-nearest.py | k-nearest.py | py | 2,535 | python | en | code | 0 | github-code | 6 |
21835433544 | """Labels app urls"""
from django.urls import path
from task_manager.labels.views import (
LabelsView,
LabelUpdateView,
LabelCreateView,
LabelDeleteView,
)
app_name = 'labels'
urlpatterns = [
path('', LabelsView.as_view(), name='index'),
path('<int:pk>/update/', LabelUpdateView.as_view(), nam... | GunGalla/python-project-52 | task_manager/labels/urls.py | urls.py | py | 476 | python | en | code | 0 | github-code | 6 |
20844849225 | import tensorflow.compat.v1 as tf
"""
`image` is assumed to be a float tensor with shape [height, width, 3].
It is a RGB image with pixel values in the range [0, 1].
"""
def random_color_manipulations(image, probability=0.5, grayscale_probability=0.1):
"""
This function randomly changes color of an image.
... | TropComplique/MultiPoseNet | detector/input_pipeline/color_augmentations.py | color_augmentations.py | py | 2,540 | python | en | code | 9 | github-code | 6 |
73696099389 | import os
import subprocess
from datetime import timedelta
from . import dispersion_file_utils as dfu
from .dispersiongrid import BSDispersionGrid, BSDispersionPlot, create_color_plot
class PolygonGenerator(object):
"""Generates polygon kmls from a NETCDF file representing smoke dispersion
time series.
P... | pnwairfire/blueskykml | blueskykml/polygon_generator.py | polygon_generator.py | py | 7,736 | python | en | code | 0 | github-code | 6 |
74992294908 | from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.postgres.fields import ArrayField
from udemy.apps.core.models import TimeStampedBase, Ordere... | gabrielustosa/udemy-old | udemy/apps/quiz/models.py | models.py | py | 2,272 | python | en | code | 0 | github-code | 6 |
34465989712 | import math
import numpy as np
import pandas as pd
n = 10
x = np.random.randint(0, 50, n)
y = np.random.randint(0, 50, n)
lista = []
listb = []
listc = []
for i in range(n-1):
for j in range(i+1, n):
lista.append((x[i]-x[j])*(x[i]-x[j]))
listb.append((y[i]-y[j])*(y[i]-y[j]))
for i in range(len(lista... | lmyljjljh/shujufenxi | sjcjyfx/20221111b.py | 20221111b.py | py | 587 | python | en | code | 1 | github-code | 6 |
7241271696 | ####################
# Joint distribution of Ask/Bid Qty
####################
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
data_directory = 'data/xFGBL'
img_directory = 'images/'
data_file = 'xFGBL20130702.p... | maroxe/SchoolProjects | EA/joint_distribution.py | joint_distribution.py | py | 1,286 | python | en | code | 0 | github-code | 6 |
73783427069 | '''
File containing the PlottingCalculator class
'''
import numpy as np
import math
from pyrigee.orbit import *
'''
The PlottingCalculator class contains functions that calculate coordinates for plotting
things. Used to reduce the amount of code in the OrbitPlotter class.
'''
class PlottingCalculator:
# The number... | JackCSheehan/pyrigee | pyrigee/plotting_calculator.py | plotting_calculator.py | py | 9,801 | python | en | code | 9 | github-code | 6 |
23099951540 | from random import random
def check(number,list):
if number in list:
return False
else:
return True
list =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def func(i,list):
index = int(random()*10)
if index <= len(list)-1:
cleaner = list[i]
list[i]= list[index]
list[index]=clea... | gochicus/python-learning | lesson-2/ex5.py | ex5.py | py | 382 | python | en | code | 0 | github-code | 6 |
70084638589 | from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
# X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
X = np.array(np.random.random((100, 2)))
kmeans = KMeans(n_clusters=2).fit(X)
print('Labels')
print(kmeans.labels_)
result = kmeans.predict([[0, 0], [12, 3]])
print... | bpark/ml-demos | simple_kmeans.py | simple_kmeans.py | py | 486 | python | en | code | 0 | github-code | 6 |
31624687973 | import math
import numpy as np
PSI = (math.sqrt(5) - 1) / 2
PSI_2 = 1 - PSI
TOL = 1.e-5
class Triangle:
def __init__(self, v1, v2, v3):
self.v1 = v1
self.v2 = v2
self.v3 = v3
def path(self, opacity, fill_color):
side_l, side_r = self.v2 - self.v1, self.v3 - self.v2
... | RCoanda/rosey | base.py | base.py | py | 5,459 | python | en | code | 0 | github-code | 6 |
73928012028 | import collections
import random
import unittest
import mock
from cardboard import card as c, events, zone as z
from cardboard.tests.util import GameTestCase
from cardboard.util import ANY
ENTER, LEAVE = events.ENTERED_ZONE, events.LEFT_ZONE
class ZoneTest(GameTestCase):
card = mock.Mock(spec=c.Card)
de... | Julian/cardboard | cardboard/tests/test_zone.py | test_zone.py | py | 8,874 | python | en | code | 7 | github-code | 6 |
36821141161 | from math import ceil
import time
def add_up_version1(list_numbers, number):
half = ceil(number/2)
pairs = []
for item in range(half):
temp = []
temp.append(item)
temp.append(number - item)
pairs.append(temp)
for item in pairs:
if item[0] in list_numbers and it... | analetisouza/daily-problem | day1.py | day1.py | py | 1,266 | python | en | code | 0 | github-code | 6 |
32660332596 | """
Implements the baseclasses for all Component types in Lumen.
The base classes implement the core validation logic and the ability
to dynamically resolve Source and Variable references.
"""
from __future__ import annotations
import warnings
from functools import partial
from typing import (
Any, ClassVar, Dic... | holoviz/lumen | lumen/base.py | base.py | py | 22,041 | python | en | code | 149 | github-code | 6 |
72960115387 | """def reverse(a):
while a:
#for i in a:
if a != " ":
b = a[::-1]
print("Reversed string is: ", b)
if b == a:
print("Works")
else:
print("Bummer!")
return
reverse("roor")"""
"""prefixes = 'JKLMNOPQ'
suffix = 'ack'
#i = 0
for letter in prefixes:
if letter == 'O':
letter... | derinsola01/Projects | chapter8codes.py | chapter8codes.py | py | 2,589 | python | en | code | 0 | github-code | 6 |
17334218878 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import re,os,sys
import random
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--per', dest='per', type=int, default=10, help='ratio of test set (%)')
parser.add_argument('--file', dest='file', type... | jshmjs45/data_for_chem | codes/select_file.py | select_file.py | py | 1,111 | python | en | code | 13 | github-code | 6 |
38153977020 | #if an element in an m x n matrix is 0, it's entire
#row and column are set to zero
#O(m*n) solution: loops through matrix twice,
#first time to find the rows and columns with zeros
#in them, and second time to assign each value in those
#rows cols to zero
def zero_matrix(m):
row = {}
col = {}
for i in ran... | BlakeMcMurray/Coding-Problem-Solutions | Arrays/zeroMatrix.py | zeroMatrix.py | py | 842 | python | en | code | 0 | github-code | 6 |
37616127622 | import time
import os
from richxerox import *
from tinydb import TinyDB, where
HOME_DIR = 'static/db'
# Create directory if it doesn't exist
os.system("mkdir %s" % HOME_DIR)
db = TinyDB('%s/db.json' % HOME_DIR)
currently_found_in_clipboard = paste(format='text')
while True:
time.sleep(0.1) # one tenth of a second... | pantacuzino/personalkb | script.py | script.py | py | 807 | python | en | code | 0 | github-code | 6 |
71520783227 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from detectron2.detectron2.layers import FrozenBatchNorm2d, ShapeSpec, get_norm
_NORM = 'BN'
class Conv2d_BN(nn.Module):
"""Convolution with BN module."""
def __init__(
self,
in_ch,
... | LiaoYun0x0/BiFormer | models/dila_prm.py | dila_prm.py | py | 4,008 | python | en | code | 0 | github-code | 6 |
40467207556 | def solution(box):
maxBox = max(box)
if maxBox == box[0]:
return box[0]
start, end = 0, maxBox
answer = maxBox
while start <= end:
mid = (start + end) // 2
crit = 0
for b in box:
crit += b - mid
if crit > 0:
start = mid... | Cho-El/coding-test-practice | 프로그래머스 문제/파이썬/2022 카카오 채용연계형 겨울 테크 인턴십 코딩테스트/3.py | 3.py | py | 552 | python | en | code | 0 | github-code | 6 |
30375207065 | from random import randint
de = randint(1,6)
print(de)
secret = randint(0,1000)
for essai in range(10):
print("Devinez mon nombre secret :")
nombreSaisi = int(input())
if nombreSaisi == secret:
print("Bravo, vous êtes perspicace.")
break
else:
print("Et non, bien tenté.")
| vguisse/job | 2nde/algo/entree_test/ex4.py | ex4.py | py | 318 | python | fr | code | 0 | github-code | 6 |
8772037717 | import requests,re,threading,os, sys,random,copy,random,json,httpx,hashlib
from loguru import logger
from wmi import WMI
from urllib.request import urlopen
from time import sleep
from colorama import init, Fore, Style
from urllib.parse import urlencode
from typing import Union, List
__version__ = "2-5"
H... | basautomaticaly/work | main2-5.py | main2-5.py | py | 46,695 | python | en | code | 0 | github-code | 6 |
30609616360 | import numpy as np
import os
import Tools.FilesTool as FilesTool
import imblearn.over_sampling as over_sampling
class DataSetTool:
# 08版的度量补偿
# Mij in Target = (Mij in Target * Mean(Mj in Source)) / Mean(Mj) in Target
@staticmethod
def metric_compensation(source, target):
# 遍历每一个度量... | ylxieyu/HYDRA | DataSetTool.py | DataSetTool.py | py | 3,100 | python | en | code | 5 | github-code | 6 |
70675296187 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from ..pki.migrate_data import migrate_pki_data
class Migration(migrations.Migration):
dependencies = [
('ssl_pki', '0002_default_config'),
]
operations = [
migrations.RunPython(migrate_pki... | ngageoint/exchange | exchange/sslpki/migrations/0001_migrate_pki_data.py | 0001_migrate_pki_data.py | py | 361 | python | en | code | 0 | github-code | 6 |
71087023548 | """
Tests for the server.
Before running them, the server database should be restarted.
Run as: python server/tests/test_all.py (don't use py.test as it does not pass env variables easily)
"""
import os
import shutil
from pathlib import Path
from typing import List
import pytest
from requests.exceptions import HTTPE... | molecule-one/mlinpl-23-workshops | server/tests/test_all.py | test_all.py | py | 4,995 | python | en | code | 1 | github-code | 6 |
13954857960 | par=[]
for i in range(100):
par.append(i)
def find(u):
if u==par[u]:
return u
par[u]=find(par[u]) # Path Compression, 경로 압축
return par[u]
def merge(u,v):
u,v=find(u),find(v)
if u==v:
return
par[u]=v # without Union-By-Rank
merge(1,5)
merge(2,5)
merge(4,1)
print(find(5)==f... | MilkClouds/SCSC-2019 | 서로소 집합.py | 서로소 집합.py | py | 359 | python | en | code | 0 | github-code | 6 |
38093772023 | from time import sleep
from HW_03.my_decorator import DecorTimeCrit
@DecorTimeCrit(critical_time=0.45)
class Test:
def method_1(self):
print('slow method start')
sleep(1)
print('slow method finish')
def method_2(self):
print('fast method start')
sleep(0.1)
pri... | alisa-moto/python-adnanced | HW_03/class_for_decorator.py | class_for_decorator.py | py | 616 | python | en | code | 0 | github-code | 6 |
4769452267 | #!/usr/bin/env python
import sys
import os
def deserialize_anno(parts):
# Frame name formatted as <task ID><6 digit frame ID>
frame_name = parts[0]
track_id = parts[1]
x = float(parts[2])
y = float(parts[3])
box_width = float(parts[4])
box_height = float(parts[5])
class_id = parts[7]
#print(frame_nam... | Salmon-Computer-Vision/salmon-computer-vision | utils/utils.py | utils.py | py | 455 | python | en | code | 4 | github-code | 6 |
859362304 | from __future__ import division
from vistrails.core.modules.vistrails_module import Module
from ..common import get_numpy
from ..read.read_numpy import NumPyArray
class WriteNumPy(Module):
"""Writes a list as a Numpy file.
NumPy can use one of two schemes: either 'plain' binary arrays, i.e. just
the bi... | VisTrails/VisTrails | vistrails/packages/tabledata/write/write_numpy.py | write_numpy.py | py | 4,325 | python | en | code | 100 | github-code | 6 |
10844685453 | from database import db
from flask import request
from middleware.auth import login_required, admin_only
from models.guild import Guild
from typing import Dict, Optional, Tuple
def check_request(req: request, id_only: Optional[bool] = False) -> int | Tuple[int, str, bool] | Tuple[Dict[str, str], int]:
# Check req... | jareddantis-bots/rico-backend | api/guilds.py | guilds.py | py | 4,053 | python | en | code | 0 | github-code | 6 |
29456781892 | from six.moves.urllib import parse
import tarfile
from lxml import etree
from atrope import exception
SPECS = {
'http://www.vmware.com/interfaces/specifications/vmdk.html': 'vmdk',
'https://people.gnome.org/~markmc/qcow-image-format.html': 'qcow',
}
def _get_tarfile(ova):
if not tarfile.is_tarfile(ova)... | alvarolopez/atrope | atrope/ovf.py | ovf.py | py | 1,986 | python | en | code | 2 | github-code | 6 |
30137635 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import json
url = "http://localhost:6332"
headers = {'content-type': 'application/json'}
def get_result(payload):
response = requests.post(
url, data=json.dumps(payload), headers=headers).json()
return json.dumps(response)
def get_all_address(... | taozywu/token_light | rpc.py | rpc.py | py | 1,701 | python | en | code | 0 | github-code | 6 |
25240137017 | n, f = map(int, input().split())
ciclo = list(map(int, input().split()))
PrimeiroDia = 1
UltimoDia = 10**8
while PrimeiroDia < UltimoDia:
aux = int((PrimeiroDia + UltimoDia) / 2)
total = 0
for i in range(len(ciclo)):
total = total + (aux // ciclo[i])
if total >= f:
UltimoDia = aux
... | MateusFerreiraMachado/Programas_Python | capsulas.py | capsulas.py | py | 376 | python | pt | code | 0 | github-code | 6 |
27161595951 | # Written by RF
while True:
Q=float(input("What number would you like to square? "))
H=float(input("How many times would you like to square it? "))
S=((Q)**H)
print("The", H, "square is", S)
while True:
answer = str(input('Anything else? (y/n): '))
if answer in ('y', 'n'):
... | GustavMH29/Python | Code/Math/Equations/Square.py | Square.py | py | 450 | python | en | code | 0 | github-code | 6 |
39687962974 | # Time:O(n)
# Space:O(n)
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
left_prod = [1]
for num in nums:
left_prod.append(left_prod[-1]*num)
right_prod = [1]
for num in reversed(nums):
right_prod.insert(0, right_prod[0]*num)
... | cmattey/leetcode_problems | 30DayChallenge_April/april_15_product_except_self.py | april_15_product_except_self.py | py | 446 | python | en | code | 4 | github-code | 6 |
73815074426 | from user.models import User
from rest_framework import exceptions
def get_user(username):
user = None
if "@" in username:
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
user = User.objects.create(
username=username,
... | Python-Crew/base_drf | auth_user/services.py | services.py | py | 815 | python | en | code | 1 | github-code | 6 |
9758869645 | from app import app, db
import json
from tests.lib import login
def test_get_products():
client = app.test_client()
response = client.get("/api/products")
assert len(response.json) == 27
assert response.status_code == 200
def test_get_single_product():
client = app.test_client()
response = ... | hannahakhtar/golden-shoes | server/tests/test_products.py | test_products.py | py | 454 | python | en | code | 0 | github-code | 6 |
33387732761 | import numpy as np
from sklearn.tree import DecisionTreeClassifier
from .sampler import FeatureSampler, ObjectSampler
class Bagger:
def __init__(self, base_estimator, object_sampler, feature_sampler, n_estimators=10, **params):
"""
n_estimators : int
number of base estimators
... | TotalChest/MLprograms | RandomForest/random_forest.py | random_forest.py | py | 3,665 | python | en | code | 0 | github-code | 6 |
35544157808 | import calendar
from datetime import datetime
class Util:
DATE_FORMAT = '%Y-%m-%d'
def get_month_start_date(datetime):
return datetime.date().replace(day=1)
def get_month_end_date(datetime):
year = datetime.year
month = datetime.month
monthrange = calendar.monthrange(year... | bluepostit/di-python-2019 | daily-exercises/week9/visitors/calendar.py | calendar.py | py | 3,141 | python | en | code | 1 | github-code | 6 |
5118772924 | from flask import current_app, Blueprint,request, jsonify
from vpnresolve import VPNResolve
import json
import logging
logger = logging.getLogger( "ucn_logger" )
ios_api = Blueprint('ios_api', __name__)
@ios_api.route("/viz/ios/log", methods=['POST'])
def log():
vpnres = VPNResolve(current_app.config["CIDR"], {... | ucn-eu/ucnviz | ucnserver/ios.py | ios.py | py | 1,522 | python | en | code | 0 | github-code | 6 |
5503800628 | # https://www.hackerrank.com/challenges/np-dot-and-cross/problem
import numpy
numpy.set_printoptions(legacy='1.13')
def zero(size):
return [0 for _ in range(size)]
def get_matrix(size):
matrix = []
for _ in range(size):
matrix.append(list(map(int, input().split())))
return matrix
N = int(... | Nikit-370/HackerRank-Solution | Python/dot-cross.py | dot-cross.py | py | 608 | python | en | code | 10 | github-code | 6 |
26221879462 | from pyarrow._fs import ( # noqa
FileSelector,
FileType,
FileInfo,
FileSystem,
LocalFileSystem,
SubTreeFileSystem,
_MockFileSystem,
_normalize_path,
FileSystemHandler,
PyFileSystem,
)
# For backward compatibility.
FileStats = FileInfo
_not_imported = []
try:
from pyarrow.... | ejnunn/PPE-Object-Detection | env/lib/python3.7/site-packages/pyarrow/fs.py | fs.py | py | 6,213 | python | en | code | 7 | github-code | 6 |
22919129693 | from io import TextIOWrapper
import os
import argparse
files = [
'Accurect-Pointer.txt',
'Endonasal-RII.txt',
'HeadBand-Reference.txt',
'Navigation-Pointer.txt',
'Registration-Pointer.txt'
]
def readFromOriginalFormat(file: TextIOWrapper):
lines = file.readlines()
for i, line in enumerate(... | odeaxcsh/ParsissCamera | Scripts/CovertToolPatternFilesFormat.py | CovertToolPatternFilesFormat.py | py | 1,486 | python | en | code | 0 | github-code | 6 |
3438407871 | """
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node is None:
return None
q = deque... | cuiy0006/Algorithms | leetcode/133. Clone Graph.py | 133. Clone Graph.py | py | 772 | python | en | code | 0 | github-code | 6 |
21112708622 | from .plugin import Plugin
import js2py
# 插件名称
name = '测试插件'
# 描述信息
description = """
仅供测试
"""
# 作者
author = 'kksanyu'
# 是否启用该插件
enable = True
# 演示js代码
jsAddFunc = """
function add(a, b) {
return a + b;
}
"""
class Demo(Plugin):
def run(self, options):
print('运行Demo::run', options.telephone)
... | superdashu/who_are_you | plugins/demo.py | demo.py | py | 623 | python | en | code | 5 | github-code | 6 |
28669919345 | import json
import unittest
from ..base import AsyncAPITestCase
from yiyun.models import (User, Team, TeamMember, TeamMemberGroup,
Sport, Activity,
ActivityMember, TeamOrder)
from yiyun.service.order import OrderService
class UserOrderTestCase(AsyncAPITestCase):
... | haoweiking/image_tesseract_private | PaiDuiGuanJia/yiyun/tests/rest/order.py | order.py | py | 3,424 | python | en | code | 0 | github-code | 6 |
39735696907 | class BankAccount:
# Class attributes
all_accounts = []
# Constructor for each account
def __init__(self, int_rate=0.05, balance=0):
self.int_rate = int_rate
self.balance = balance
BankAccount.all_accounts.append(self)
def deposit(self, amount):
self.balance += amo... | r-lutrick/Coding-Dojo | Python/Fundamentals/OOP/Bank_Account/bank_account.py | bank_account.py | py | 1,277 | python | en | code | 1 | github-code | 6 |
22251439419 | def dell(n):
d = 2
mas = []
while d * d < n:
if n % d == 0:
mas.append(d)
mas.append(n // d)
d += 1
if d * d == n:
mas.append(d)
if len(mas) == 2:
print(*mas)
for i in range(338472, 338494 + 1):
dell(i)
| MakinFantasy/xo | 25/10.06/1.py | 1.py | py | 285 | python | en | code | 0 | github-code | 6 |
32727491090 | import sqlite3
posts = [
{
'author': 'Dova Kin',
'title': 'First Post',
'content': 'First post.',
'date_posted': '20200301'
},
{
'author': 'Angi\'s Cabin',
'title': 'Second Post',
'content': 'Second post.',
'date_posted': '20200302'
},
... | majorgear/flask_blog | utils/populate_db.py | populate_db.py | py | 1,163 | python | en | code | 0 | github-code | 6 |
13202825418 | import datetime
menu = """
[d] Depositar
[s] Sacar
[e] Extrato
[q] Sair
=> """
saldo = 0
limite = 500
extrato = []
numero_saques = 0
total_saque_diario = 0
LIMITE_SAQUES = 3
while True:
opcao = input(menu)
if opcao == 'd':
valor = input('Valor do depósito (número inteiro e posi... | ElPablitoBR/btc-c-d-desafio1 | desafio.py | desafio.py | py | 2,754 | python | pt | code | 0 | github-code | 6 |
74843183226 | # encoding: UTF-8
from ctaStrategyTemplate import *
from ctaObject import CtaBarData
########################################################################
class DataRecorder(CtaStrategyTemplate):
"""
纯粹用来记录历史数据的工具(基于CTA策略),
建议运行在实际交易程序外的一个vn.trader实例中,
本工具会记录Tick和1分钟K线数据。
"""
#-----------... | LonelyHunter7/Backtesting_Syestem | vn.trader/ctaDataRecorder.py | ctaDataRecorder.py | py | 4,091 | python | en | code | 1 | github-code | 6 |
42104820373 | from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
class Reporter(object):
def __init__(self, project, src_files, dst_table, keyfile, config):
self.project = project
self.src_files = src_files
self.dst_table = dst_table
self.keyfile = keyfile
self.driver = config.... | ubermen/anomaly_detector | estimator/reporter/engines.py | engines.py | py | 2,795 | python | en | code | 1 | github-code | 6 |
10930434466 | import numpy as np
from os import listdir
from os.path import isfile, isdir, join
import os
import random
cwd = os.getcwd()
data_path = '/data/CUB_200_2011'
savedir = './'
dataset_list = ['base','val','novel']
#if not os.path.exists(savedir):
# os.makedirs(savedir)
folder_list = [f for f in listdir(join(data_path... | alinlab/PsCo | splits/cub200/write_cub_filelist.py | write_cub_filelist.py | py | 2,032 | python | en | code | 42 | github-code | 6 |
23135790413 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 21:16:51 2019
@author: eikivi
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy import or_
engine = create_engine('sqlite:///sales.db', echo = False)
from sqlalchemy.ext.declarative import declarative_base
Base = ... | baadam3/ICS0019_Advanced_python_solutions | Examples/Database_code/SQLAlchemyFilter7.py | SQLAlchemyFilter7.py | py | 1,137 | python | en | code | 0 | github-code | 6 |
42933813764 | import pyherc
from pyherc.aspects import log_debug
class Portal():
"""
Portal linking two levels together
"""
@log_debug
def __init__(self, icons, level_generator_name):
"""
Default constructor
:param icons: (my_icon, icon for other end)
:type icons: (integer, inte... | tuturto/pyherc | src/pyherc/data/portal.py | portal.py | py | 3,215 | python | en | code | 43 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.