max_stars_repo_path
stringlengths
3
269
max_stars_repo_name
stringlengths
4
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.05M
score
float64
0.23
5.13
int_score
int64
0
5
ml-framework/main.py
SANER22-ERA/extract-method-experiments
0
53100
from src.trainer import train_by_config, test_by_config import os # train_by_config(os.path.join('settings', 'training_settings_7.ini')) # test_by_config(os.path.join('test_settings', 'test_settings.ini'))
1.523438
2
cainiao1/test_deque.py
relax-space/python-base
0
53101
from collections import deque from itertools import islice def test_1(): list = ['a', 'b', 'c'] d = deque(list) assert 'a' == d[0] and 'b' == d[1] and 'c' == d[2], 'queue error' def test_2(): data = islice(['a', 'b', 'c'],None) d = deque(data) assert 'a' == d[0] and 'b' == d[1] and 'c' == d[...
3.140625
3
lecture_10/task_tracker/tracker_rest/api_v1/schemas.py
darinabird/python_developer
20
53102
<filename>lecture_10/task_tracker/tracker_rest/api_v1/schemas.py import re import inspect from datetime import datetime from marshmallow import fields, ValidationError, pre_dump, post_load, validates_schema from flask_marshmallow import Marshmallow from flask.helpers import url_for from task_tracker.tracker_rest.api_v1...
2.28125
2
binaryTree/226_invert_binary_tree.py
weilincheng/LeetCode-practice
0
53103
<gh_stars>0 class Solution: # Iterative def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return None stack = [root] while len(stack) > 0: currentNode = stack.pop() currentNode.left, currentNode.right = curren...
3.703125
4
argos/apps/common/management/commands/clear_cache.py
daedafusion/django-argos
0
53104
<gh_stars>0 from django.conf import settings from django.core.cache import cache from django.core.management import BaseCommand, CommandError __author__ = 'mphilpot' class Command(BaseCommand): help= 'Clear your cache' def handle(self, *args, **options): try: assert settings.CACHES ...
2.21875
2
bentoctl_aws_ec2/update.py
jjmachan/aws-ec2-deploy
0
53105
<filename>bentoctl_aws_ec2/update.py<gh_stars>0 from .deploy import deploy def update(bento_bundle_path, deployment_name, ec2_json): """ The deployment operation can also be used for updation since we are using AWS Sam cli for managing deployments. """ deploy(bento_bundle_path, deployment_name, ec...
1.796875
2
classification/CNN.py
lejinghu/Online-courses-subtitles-topic-classification
0
53106
<filename>classification/CNN.py # encoding=utf-8 #from __future__ import print_function import os import numpy as np import pandas as pd np.random.seed(1337) import random from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils.np_utils import to_categoric...
2.75
3
Dato/test2.py
crazyacking/ted-in-spark
0
53107
import numpy as np import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'inline') sns.set() def gl_confmatrix_2_confmatrix(sf,number_label=3): Nlabels=max(len(sf['target_label'].unique()),len(sf['predicted_label']....
2.78125
3
xml-server/migrations/versions/86697f03e85b_add_session_type_col.py
sopherrmann/SoDaMap
0
53108
<reponame>sopherrmann/SoDaMap """Add session type col Revision ID: 86697f03e85b Revises: 6c7b56b35fa5 Create Date: 2019-11-16 00:06:01.590734 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '86697f03e85b' down_revision ...
1.460938
1
backend/util/response/search_products_results/search_products_results_response.py
willrp/willstores-ws
4
53109
from flask_restplus import fields from ..models.product import ProductResponse from .search_products_results_schema import SearchProductsResultsSchema class SearchProductsResultsResponse(object): @staticmethod def get_model(api, name): return api.model( name, { ...
2.25
2
migrations/versions/2d70b2b7f421_.py
moahmed-arafa/Borsa
0
53110
"""empty message Revision ID: 2d70b2b7f421 Revises: <PASSWORD> Create Date: 2017-01-07 15:40:46.326596 """ # revision identifiers, used by Alembic. revision = '2d70b2b7f421' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - plea...
1.390625
1
src/p023-non-abundant-sums.py
gergelynagyvari/euler
0
53111
#!/usr/bin/env python # -*- coding: utf-8 -*- # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # A number n is called deficient if the sum...
4.125
4
base-part1/rest_api/api/serializers.py
AETT-UA/ws_deployment
4
53112
<reponame>AETT-UA/ws_deployment from rest_framework import serializers from api.models import Attendance, CourseUnit, Department, Student class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() class UserSerializer(serializers.Serializer): emai...
2.140625
2
source/vsm/vsm/db/sqlalchemy/migrate_repo/versions/026_remove_foreign_key.py
ramkrsna/virtual-storage-manager
172
53113
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2014 Intel Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lice...
1.976563
2
CATBOSS_detectChanges.py
ysl-lab/CATBOSS
2
53114
import argparse parser = argparse.ArgumentParser(description='This script takes a dihedral trajectory and detects change points using SIMPLE (simultaneous Penalized Likelihood Estimation, see Fan et al. P. Natl. Acad. Sci, 2015, 112, 7454-7459). Two parameters alpha and lambda are controlling the extent of simultaneous...
2.703125
3
tests/test_user.py
alliedtelesis/py-networking
4
53115
import pytest from pynetworking.Device import Device def setup_dut(dut): dut.reset() dut.add_cmd({'cmd': 'show version', 'state': -1, 'action': 'PRINT', 'args': [""" AlliedWare Plus (TM) 5.4.2 09/25/13 12:57:26 Build name : x600-5.4.2-3.14.rel Build date : Wed Sep 25 12:57:26 NZST 2013 Build type : RELEASE ...
2.109375
2
tests/test_definitionlist.py
al3xandru/html2md
8
53116
import unittest from context import html2md from assertions import assertEq class DefinitioListTests(unittest.TestCase): def test_basic(self): in_html = u''' <dl> <dt>Apple</dt> <dd>Pomaceous fruit of plants of the genus Malus in the family Rosaceae.</dd> <dt>Orange</dt> <dd>The fruit of an evergreen tr...
3.109375
3
models/build.py
zhigangjiang/LGT-Net
11
53117
<reponame>zhigangjiang/LGT-Net """ @Date: 2021/07/18 @description: """ import os import models import torch.distributed as dist import torch from torch.nn import init from torch.optim import lr_scheduler from utils.time_watch import TimeWatch from models.other.optimizer import build_optimizer from models.other.criter...
1.9375
2
project1/utils/sgd.py
itslwg/epflml-projects
0
53118
import numpy as np from helpers import * from gradients import * from costs import * def stochastic_gradient_descent(y, tx, initial_w, batch_size, max_iters, gamma, verbose = False): """ Stochastic gradient descent for linear regression with mse ...
3.21875
3
pytorchrl/agent/env/env_wrappers.py
PyTorchRL/pytorchrl
20
53119
import gym from gym.spaces.box import Box class TransposeImagesIfRequired(gym.ObservationWrapper): """ When environment observations are images, this wrapper transposes the axis. It is useful when the images have shape (W,H,C), as they can be transposed "on the fly" to (C,W,H) for PyTorch convolutions...
3.25
3
class-6/01-guess.py
dlech/lu-fall-2019-python-class
0
53120
# File: guess.py # Author: <NAME> # Date: 11/21/2019 '''A guessing game. This is the classic game where someone thinks of a secret number and someone else tries to guess it. In this case, the computer thinks of the number and we (the user) have to guess what it is. ''' # LEARN: Python has a standard module for deali...
4.5
4
ietf/group/views_stream.py
wpjesus/codematch
1
53121
<filename>ietf/group/views_stream.py # Copyright The IETF Trust 2008, All Rights Reserved from django.shortcuts import render_to_response, get_object_or_404, redirect from django.template import RequestContext from django.http import Http404, HttpResponseForbidden from django import forms from ietf.doc.views_search i...
1.867188
2
digraphillion/test/test_digraphillion.py
ComputerAlgorithmsGroupAtKyotoU/digraphillion
1
53122
# Copyright (c) 2021 ComputerAlgorithmsGroupAtKyotoU # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, mer...
2.296875
2
tests/unit/test_parser.py
luiscape/hdxscraper-ifpri-dataverse
0
53123
<gh_stars>0 #!/usr/bin/python # -*- coding: utf-8 -*- ''' Unit tests for the dataset parser. ''' import unittest from scraper.parser import parse_dataset from scraper.classes.dataset import Dataset from scraper.classes.dataverse import Dataverse class TestParser(unittest.TestCase): ''' Performs unit tests on the...
2.90625
3
Utility/draw_stat.py
jeorjebot/kp-anonymity
1
53124
from pathlib import Path import matplotlib import matplotlib.pyplot as plt import numpy as np with open(Path('tmp.txt'), 'r') as f: lines_read = f.readlines() lines = list() for line in lines_read: lines.append(line.split()) labels = list() naive_time = list() kapra_time = list() for index, line in enumerat...
2.921875
3
scripts/differential_drive.py
mzahana/zlac8030l_ros
0
53125
<reponame>mzahana/zlac8030l_ros """ BSD 3-Clause License Copyright (c) 2022, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice...
1.367188
1
src/lamuda/date/common_date.py
hanadumal/lamud
0
53126
from datetime import date from datetime import datetime from datetime import timedelta from datetime import timezone class CommonDate(object): DEFAULT_ZONE = timezone(offset=timedelta(hours=8)) @staticmethod def today(tz=DEFAULT_ZONE): return date.today() @staticmethod def today_time(tz=...
3.53125
4
example_bot.py
XDwightsBeetsX/discord-bots
0
53127
<filename>example_bot.py """ An example python discord-bot with some template methods. """ import discord from utils.parsing import parseKeychainFromFile class DiscordBot(object): """ An example python discord-bot with some template methods. """ def __init__(self, keychain): """ - Ini...
3.546875
4
autotrade/account_manager.py
rezabmirzaei/tradebot
0
53128
<reponame>rezabmirzaei/tradebot import logging from typing import List from autotrade.session_handler import SessionHandler log = logging.getLogger('tradebot.log') class AccountManager: def __init__(self, config: dict, session_handler: SessionHandler) -> None: self.session_handler: SessionHandler = ses...
2.765625
3
PyScraper/server/models/project.py
nikan1996/PyScraper
0
53129
#!/usr/bin/env python # encoding: utf-8 """ @author:nikan @file: project.py @time: 2018/5/14 下午4:20 """ import datetime from sqlalchemy import text from sqlalchemy.dialects import mysql from PyScraper.server.extensions import db class Project(db.Model): __tablename__ = "project" project_id = db.Column(d...
2.34375
2
services/greenhouse/rest/greenhouse_rest.py
dvcorreia/greenscale
7
53130
<reponame>dvcorreia/greenscale import cherrypy from schemas import Greenhouse import requests class GreenhouseREST(object): def __init__(self): pass exposed = True @cherrypy.tools.json_out() def GET(self, **params): # Find user greenhouse the required id try: gh =...
2.40625
2
app/returnHazards.py
Pulotum/BattleSnake2019
0
53131
<reponame>Pulotum/BattleSnake2019<filename>app/returnHazards.py def returnHazards(map): hazards = [] for x_index, x in enumerate(map): for y_index, y in enumerate(x): if y == 'x': hazards.append({"x":x_index,"y":y_index}) return hazards
2.765625
3
refresh_dynspec_files.py
jackievilladsen/dynspec
2
53132
''' refresh_dynspec_files.py Purpose: Re-run the step of going from tbavg.ms to tbavg.ms.dynspec for all observations. This is useful because I found a bug in dyn_spec (which reads the dynspec out of tbavg.ms) and so want to redo just this step. ''' import dynspec.ms2dynspec reload(dynspec.ms2dynspec...
2.171875
2
data/agriculture/FAOSTAT_livestock_product_produced/viz/generate.py
ilopezgp/human_impacts
4
53133
<gh_stars>1-10 #%% import numpy as np import pandas as pd import altair as alt # Load the production data. data = pd.read_csv('../processed/FAOSTAT_livestock_and_product.csv') data['year'] = pd.to_datetime(data['year'], format='%Y') # Generate JSON vis for subcategories for g, d in data.groupby('subcategory'): ...
2.53125
3
poolink_backend/apps/board/admin.py
jaethewiederholen/Poolink_backend
0
53134
<gh_stars>0 from django.contrib import admin from poolink_backend.apps.board.models import Board @admin.register(Board) class BoardAdmin(admin.ModelAdmin): list_display = ("user", "id", "name", "bio", "scrap_count")
1.648438
2
stacking/2.regression/config_params.py
huseinzol05/Machine-Learning-Data-Science-Reuse
26
53135
<gh_stars>10-100 import numpy as np import pandas as pd xgb_params_level1 = { 'objective': 'reg:linear', 'metric': 'rmse', 'max_depth' : 5, 'subsample': 0.8, 'colsample_bytree': 0.8, 'learning_rate': 0.05, 'seed': 0, 'nthread': -1, 'verbose':0 } lgb_params_re...
2.359375
2
homeassistant/components/trafikverket_train/util.py
MrDelik/core
30,023
53136
<gh_stars>1000+ """Utils for trafikverket_train.""" from __future__ import annotations from datetime import time def create_unique_id( from_station: str, to_station: str, depart_time: time | str | None, weekdays: list ) -> str: """Create unique id.""" timestr = str(depart_time) if depart_time else "" ...
2.390625
2
1711_count_good_meal_power_of_two.py
ojhaanshu87/LeetCode
0
53137
<reponame>ojhaanshu87/LeetCode ''' A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​...
3.84375
4
examples/cross_origin/web.py
benthomasson/gevent-socketio
625
53138
import os from bottle import Bottle, static_file, run HERE = os.path.abspath(os.path.dirname(__file__)) STATIC = os.path.join(HERE, 'static') app = Bottle() @app.route('/') @app.route('/<filename:path>') def serve(filename='index.html'): return static_file(filename, root=STATIC) if __name__ == '__main__': ...
2.46875
2
tests/test_session.py
launchableinc/cli
19
53139
<gh_stars>10-100 import os import shutil import tempfile from unittest import TestCase, mock from launchable.utils.session import (SESSION_DIR_KEY, clean_session_files, parse_session, read_build, read_session, remove_session, ...
2.453125
2
questions/q28_chef_and_price_control/q28.py
aadhityasw/Competitive-Programs
0
53140
# Codechef June2020 # PRICECON # https://www.codechef.com/problems/PRICECON # Chef and Price Control """ Chef has N items in his shop (numbered 1 through N); for each valid i, the price of the i-th item is Pi. Since Chef has very loyal customers, all N items are guaranteed to be sold regardless of their price. Howe...
3.46875
3
src/__init__.py
LeRyc/Robust-Robotic-Manipulation
1
53141
"""Collects all defined and implemented observer modules.""" from src.observer.base_observer import BaseObserver __all__ = ["BaseObserver"]
1.109375
1
simulation/python2/three_d_net.py
mgualti/PickAndPlace
12
53142
<gh_stars>10-100 '''A class for managing 3DNet objects.''' # python import os # scipy from numpy.random import rand, randint class ThreeDNet: def __init__(self): '''TODO''' self.dir = "/home/mgualti/Data/3DNet/Cat10_ModelDatabase" # 3D Net objects all have height of 1m self.classes = ["bottle...
2.875
3
1stRound/Easy/389 Find the Difference/Xor.py
ericchen12377/Leetcode-Algorithm-Python
2
53143
<reponame>ericchen12377/Leetcode-Algorithm-Python from functools import reduce class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ return chr(reduce(lambda x, y : x ^ y, map(ord, s + t))) s = "abcd" t = "abcde" p = ...
3.65625
4
example/app/main.py
eHealthAfrica/aether-consumer-quickstart
0
53144
<filename>example/app/main.py #!/usr/bin/env python # Copyright (C) 2018 by eHealth Africa : http://www.eHealthAfrica.org # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use ...
1.992188
2
model/test_game.py
AndreasHae/tictactoe-py
1
53145
import unittest from model.game import Game class GameTest(unittest.TestCase): def setUp(self): self.game = Game() def test_next_player(self): first_player = self.game.next_player self.game.turn(0, 0) second_player = self.game.next_player self.game.turn(1, 0) ...
3.671875
4
wf_blog/wf_blog/__init__.py
mutoulbj/wf_blog
0
53146
# -*-coding:utf-8 -*- import pymongo from pyramid.config import Configurator from pyramid.events import subscriber from pyramid.events import NewRequest from pyramid.request import Request from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from wf_b...
1.90625
2
src/balancing_robot/main.py
magnusoy/SelfBalancingRobot
0
53147
# #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2019 magnusoy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including with...
2.5
2
week3/problem3.py
aishdharan/week3
1
53148
import os import sys import random """ Notes: - Excellent attempt """ def main(): x = random.choices(range(5), k=20) x0 = x.count(0) x1 = x.count(1) x2 = x.count(2) x3 = x.count(3) x4 = x.count(4) print(f'x = {x}') print(f'no. of zeroes = {x0}, no. of ones = {x1}, no. of twos = {x2}, ...
3.171875
3
pysyrenn/frontend/fullyconnected_layer.py
95616ARG/SyReNN
36
53149
<filename>pysyrenn/frontend/fullyconnected_layer.py """Methods for describing a Fully-Connected layer. """ import numpy as np import torch from pysyrenn.frontend.layer import NetworkLayer import syrenn_proto.syrenn_pb2 as transformer_pb class FullyConnectedLayer(NetworkLayer): """Represents a fully-connected (arbi...
2.90625
3
review_heatmap/activity.py
kb1900/Anki-Addons
1
53150
# -*- coding: utf-8 -*- # Review Heatmap Add-on for Anki # # Copyright (C) 2016-2018 <NAME>. <https//glutanimate.com/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3...
1.351563
1
main.py
kalDima1218/schet-drevnih-shizov
0
53151
chislo = input() chislo_na_schote_drevnih_shizov = "" cifri_scheta_drevnih_shizov = "ноль, целковый, чекушка, порнушка, пердушка, засирушка, жучок, мудачок, хуй на воротничок, дурачок, ВСЕ".split(", ") for i in chislo: chislo_na_schote_drevnih_shizov+=cifri_scheta_drevnih_shizov[int(i)] print(chislo_na_schote_drevnih_s...
3.296875
3
autofingering/fingering.py
thegreatkwanghyeon/autofingering
2
53152
import os import pandas as pd import numpy as np from collections import Counter, defaultdict def train_from_file(dir_path, leap_limit=15): file_list = os.listdir(dir_path) pig_format = [ "id", "onset", "offset", "pitch", "onsetvel", "offsetvel", "hand"...
2.296875
2
views.py
halflings/terrasim
0
53153
import cocos import pyglet from world import Terrain TERRAIN_TEXTURES = {Terrain.GRASS: 'grass.png', Terrain.DIRT: 'dirt.png', Terrain.WATER: 'water.png', Terrain.MOUNTAIN: 'mountain.png'} CELL_SIZE = 32 DEFAULT_CHARACTER = pyglet.resource.image('res/img/dummy.png') class WorldMap(cocos.tiles.Re...
2.625
3
web/app/syzygy/view_history/__init__.py
aaronSchanck/SepTech
1
53154
<reponame>aaronSchanck/SepTech """/web/app/syzygy/view_history/__init__.py Author: <NAME> (<EMAIL>), <NAME> (<EMAIL>) [Description] Classes: [ClassesList] Functions: [FunctionsList] """ import logging from .model import ViewHistory from .schema import ViewHistorySchema BASE_ROUTE = "view_histo...
2.015625
2
Tutoriales/locust/test.py
edaral3/so1-course
25
53155
from locust import HttpUser, task, between class LoadTest(HttpUser): @task def test(self): self.client.get('/')
1.835938
2
model_training/mongo_dataset.py
tennessejoyce/Stack-Exchange-Title-Generator
2
53156
import pymongo import numpy as np from tqdm import tqdm from datetime import datetime, timedelta def mongo_query(**kwargs): """Create a MongoDB query based on a set of conditions.""" query = {} if 'start_date' in kwargs: if not ('CreationDate' in query): query['CreationDate'] = {} ...
2.6875
3
rbb_server/src/rbb_swagger_server/models/file_store.py
SK4P3/rbb_core
55
53157
<reponame>SK4P3/rbb_core # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from rbb_swagger_server.models.base_model_ import Model from rbb_swagger_server import util class FileStore(Model): """NOTE: This class i...
1.960938
2
src/webserver/oauth/login_required.py
f0lg0/gelata
0
53158
<reponame>f0lg0/gelata from flask import session, render_template from functools import wraps def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): user = dict(session).get('profile', None) if user: return f(*args, **kwargs) return render_template("logi...
2.34375
2
setup.py
nicolargo/TextBlob
1
53159
import sys import os import subprocess import text try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup from distutils.util import convert_path def _find_packages(where='.', exclude=()): """Return a list all Python packages found within director...
2.109375
2
immutable/tests.py
theengineear/immutable
3
53160
from __future__ import absolute_import, unicode_literals import warnings from unittest import TestCase from immutable import Immutable, ImmutableFactory warnings.filterwarnings("ignore") class TestImmutableObjectFactory(TestCase): def test_create_empty(self): # unlike a namedtuple, you don't even nee...
2.859375
3
detectors/center_detector.py
Guanghan/mxnet-centernet
19
53161
<reponame>Guanghan/mxnet-centernet import cv2 import numpy as np import time import sys sys.path.insert(0, "/Users/guanghan.ning/Desktop/dev/CenterNet-Gluon/") from external.nms import soft_nms from models.tensor_utils import flip_tensor from utils.image import get_affine_transform from detectors.base_detector impor...
1.984375
2
train.py
sebastianbujwid/drl-atari
0
53162
<gh_stars>0 #!/usr/bin/env python3 import argparse import logging import yaml import gym import os import shutil import tensorflow as tf import numpy as np from drl_atari.models import A2C, DQN from drl_atari import utils from drl_atari.multiple_sync_env import MultipleSyncEnv from drl_atari.experience_replay import ...
1.867188
2
Util.py
a523/obscmdbench
27
53163
<filename>Util.py # -*- coding:utf-8 -*- import random import string import base64 import hmac import hashlib import logging import sys import time import os TIME_FORMAT = '%a, %d %b %Y %H:%M:%S GMT' ISO8601 = '%Y%m%dT%H%M%SZ' ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ' RFC1123 = '%a, %d %b %Y %H:%M:%S %Z' class InitSSHRem...
2.796875
3
children/migrations/0002_remove_child_ssn.py
City-of-Helsinki/kukkuu
0
53164
# Generated by Django 2.2.6 on 2019-10-15 19:17 import uuid from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("children", "0001_initial")] operations = [ migrations.RenameField(model_name="child", old_name="uuid", new_name="id"), migrations.Rem...
1.914063
2
python/network/Foundations-of-Python-Network-Programming/foundations-of-python-network-programming-14/source/chapter17/recursedl.py
bosserbosser/codetest
0
53165
#!/usr/bin/env python3 # Foundations of Python Network Programming, Third Edition # https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter17/recursedl.py from ftplib import FTP, error_perm def walk_dir(ftp, dirpath): original_dir = ftp.pwd() try: ftp.cwd(dirpath) except error_perm: ret...
3.1875
3
geolocation/admin.py
suselrd/django-geolocation
0
53166
<filename>geolocation/admin.py<gh_stars>0 # coding=utf-8 from django.contrib.gis.admin import site, GeoModelAdmin from .models.places import Place from .models.areas import GeoPolygon site.register(Place, GeoModelAdmin) site.register(GeoPolygon, GeoModelAdmin)
1.242188
1
geonode/geonode/people/templatetags/socialaccount_extra.py
ttungbmt/BecaGIS_GeoPortal
0
53167
from allauth.socialaccount import providers from django import template register = template.Library() @register.simple_tag def get_user_social_providers(user): user_providers = set() for account in user.socialaccount_set.all(): user_providers.add(account.get_provider()) return list(user_providers...
2.203125
2
uninas/methods/asap.py
cogsys-tuebingen/uninas
18
53168
from uninas.utils.args import Argument from uninas.register import Register from uninas.methods.abstract import AbstractBiOptimizationMethod from uninas.methods.strategies.manager import StrategyManager from uninas.methods.strategies.differentiable import DifferentiableStrategy @Register.method(search=True) class Asa...
2.625
3
aula9/aula9.py
jessicsous/Curso_Python
1
53169
<reponame>jessicsous/Curso_Python ''' Entrada de dados ''' nome = input('qual o seu nome? ') idade = input('qual a sua idade? ') ano_nascimento = 2021-int(idade) print() print(f'{nome}, tem {idade} anos. ' f'{nome} nasceu em {ano_nascimento}.') print(f'O usuário digitou {nome} e o tipo da variável é' f' {...
3.921875
4
src/django_rest_form_fields/fields.py
roveil/django-rest-form-fields
0
53170
<gh_stars>0 """ This file contains a number of custom fields to validate data with django forms """ import datetime import json from typing import Any, Optional, Union import jsonschema import os import pytz import re import six from django import forms from django.core.exceptions import ValidationError from django.c...
2.609375
3
src/maps.py
raulorteg/SearchAlgs
0
53171
<filename>src/maps.py """ Example Maps for Simulated Annealing: Circle Map, Random Map. @author <NAME> Created 26/06/2021 """ import matplotlib.pyplot as plt from math import sqrt, log, cos, sin import numpy as np import os, glob, math from PIL import Image class Circle_Map: def __init__(self, num_cities=20, radiu...
4
4
Task/Variadic-function/Python/variadic-function-4.py
LaudateCorpus1/RosettaCodeData
5
53172
>>> def printargs(*positionalargs, **keywordargs): print "POSITIONAL ARGS:\n " + "\n ".join(repr(x) for x in positionalargs) print "KEYWORD ARGS:\n " + '\n '.join( "%r = %r" % (k,v) for k,v in keywordargs.iteritems()) >>> printargs(1,'a',1+0j, fee='fi', fo='fum') POSITIONAL ARGS: 1 'a' (1+0j) KEYWORD A...
3.5625
4
l10n_ar_ux/models/account_tax.py
odoo-mastercore/odoo-argentina
1
53173
<filename>l10n_ar_ux/models/account_tax.py ############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import fields, model...
1.929688
2
web_app2/routes/stats_routes.py
geraldm24/twitoff14g
0
53174
from flask import Blueprint, render_template, request from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from .models import User from .basilica_service import connection as basilica_c...
2.6875
3
rjgtoys/cli/__init__.py
bobgautier/rjgtoys-cli
0
53175
<reponame>bobgautier/rjgtoys-cli<gh_stars>0 """ .. automodule:: rjgtoys.cli._base """ from rjgtoys.cli._base import *
1.117188
1
tiff/resize.py
anatoliy-kuznetsov/terrain
0
53176
<filename>tiff/resize.py from datetime import datetime import json import numpy from osgeo import gdal from osgeo import osr from scipy import ndimage # __CACHE_SCALED_TIF__ is where we put the scaled GeoTiff after we're done working on it __CACHE_SCALED_TIF__ = "scaled.tif" # __CACHE_RASTER_INFO__ is where we store c...
3.078125
3
Section 7/7.4/code.py
PacktPublishing/-Data-Wrangling-with-Python-3.x
16
53177
import pandas as pd dataset = pd.read_csv('iris.csv') dataset.boxplot(column = 'sepal_width',by = 'species') import matplotlib.pyplot as plt hours_slices = [8,16] activities = ['work','sleep'] colors = ['g','r'] plt.pie(hours_slices,labels=activities,colors=colors,startangle=90,autopct='%.1f%%') plt.show() ...
2.953125
3
neupre/backend/onlinemlp_backend.py
horvathpeter/neural_prediction
0
53178
<gh_stars>0 from .base_backend import BaseBackend class MlpBackend(BaseBackend): def __init__(self, inpmulti, hidmulti, outmulti, learning_rate, inp96, hid96, out96, path, buffsize, mean, std, statspath): from neupre.misc.builders import build_model_mlp super(MlpBackend, self).__init__(int(buffsiz...
2.1875
2
migrations/versions/d09db0106be9_.py
CSCfi/pebbles
4
53179
<filename>migrations/versions/d09db0106be9_.py<gh_stars>1-10 """remove cost multipliers. Revision ID: d09db0106be9 Revises: <PASSWORD> Create Date: 2016-11-14 15:12:37.972365 """ # revision identifiers, used by Alembic. revision = 'd09db0106be9' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy ...
1.40625
1
src/cogs/botcontroller.py
TheORC/HermesBot
1
53180
# -*- coding: utf-8 -*- ''' Copyright (c) 2021 <NAME>. This file is part of HermesBot. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless requir...
2.484375
2
learners/histogram.py
crm416/online_boosting
56
53181
<filename>learners/histogram.py """ Based on Saffari's "Online Random Forests". Assumes features are in [-1, 1]. """ from math import log from collections import defaultdict from random import random import numpy as np class Histogram(object): def __init__(self): self.range = [-1, 1] sel...
3.171875
3
src/test.py
davidkimolo/simple_image_editor
0
53182
from PIL import Image my_image = Image.open("assets/images/splashscreen_background.png") width, height = my_image.size print(height)
2.53125
3
maze_traversal/csbw2.py
CoinQuest-Alpha/CoinQuest
0
53183
<gh_stars>0 import time import json import requests from collections import defaultdict import hashlib class Stack(): def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): if self.size() > 0: return self.stack.pop() ...
2.796875
3
src/cz_urnnbn_api/api_structures/digital_instance.py
edeposit/urn-nbn-api
1
53184
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== import xmltodict from odictliteral import odict from kwargs_obj import KwargsObj from tools import both_set_and_different # Functions & classes ========...
2.8125
3
PiCN/Layers/ChunkLayer/Chunkifyer/test/test_SimpleContentChunkifyer.py
NikolaiRutz/PiCN
0
53185
"""Test for Simple Content Chunkifyer""" import unittest from PiCN.Layers.ChunkLayer.Chunkifyer import SimpleContentChunkifyer from PiCN.Packets import Content, Name class test_SimpleContentChunkifyer(unittest.TestCase): def setUp(self): self.chunkifyer = SimpleContentChunkifyer() def tearDown(sel...
2.796875
3
gosubl/utils.py
charlievieth/GoSubl
0
53186
<filename>gosubl/utils.py try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping from threading import Lock class Counter: """Counter provides a thread-safe counter.""" __slots__ = "_lock", "_value" def __init__(self, value: int = 0) -> None: ...
2.71875
3
lambda/src/medication_diary_bot.py
angelarw/voice-enabled-patient-dairy-1
3
53187
<gh_stars>1-10 import logging from data_access.user_profile import get_current_time_for_user from lex_bot_handler import LexBotHandler from common.lex_config import LOG_LEVEL, SLOT_MED_TIME, SLOT_MED_TIME_OF_DAY, INTENT_MEDICATION_TIME, \ INTENT_YES_MEDICATION, INTENT_NO_MEDICATION, BOT_MEDICATION_NAME from commo...
2.25
2
mathgenerator/funcs/fibonacciSeriesFunc.py
furins/mathgenerator
0
53188
<filename>mathgenerator/funcs/fibonacciSeriesFunc.py from .__init__ import * def fibonacciSeriesFunc(minNo=1): n = random.randint(minNo,20) def createFibList(n): l=[] for i in range(n): if i<2: l.append(i) else: val = l[i-1]+l[i-2] ...
4.0625
4
wntr/tests/test_times.py
yejustme/WNTR
0
53189
<filename>wntr/tests/test_times.py<gh_stars>0 import unittest from os.path import abspath, dirname, join testdir = dirname(abspath(str(__file__))) test_datadir = join(testdir,'networks_for_testing') ex_datadir = join(testdir,'..','..','examples','networks') #class TestNetworkTimeWarnings(unittest.TestCase): # # @c...
2.375
2
pyspawn/_graph/table.py
Tsanton/pyspawn
0
53190
from typing import TYPE_CHECKING if TYPE_CHECKING: from pyspawn._graph.relationship import Relationship from dataclasses import dataclass from typing import Set @dataclass(frozen=False) class Table: """Table class""" schema: str table_name: str def __post_init__(self): self.relationship...
2.90625
3
snownlp/seg/seg.py
wuxqing/snownlp
1
53191
<filename>snownlp/seg/seg.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs from ..utils.tnt import TnT class Seg(object): def __init__(self): self.segger = TnT() def save(self, fname): self.segger.save(fname) def load(self, fname): self.segger....
2.765625
3
workflow/scripts/helpers/__init__.py
IMS-Bio2Core-Facility/polya_liftover
2
53192
<reponame>IMS-Bio2Core-Facility/polya_liftover # -*- coding: utf-8 -*- """Helper modules for analysis scripts."""
0.789063
1
rules.py
Dakta/OttoModerator
2
53193
<filename>rules.py # # set up logging # from config import logging # logger = logging.getLogger(__name__) # import re class Criterion: """A set of conditions for matching Actions against PRAW objects""" def __init__(self, values): # convert the dict to attributes self.conditions = values ...
3.03125
3
src/workshop_comp_speeds/Functions.py
eliasmateo95/Workshop_comp_speeds
0
53194
<reponame>eliasmateo95/Workshop_comp_speeds from brian2 import * def visualise(S): Ns = len(S.source) Nt = len(S.target) figure(figsize=(10, 4), dpi= 80, facecolor='w', edgecolor='k') subplot(121) plot(zeros(Ns), arange(Ns), 'ok', ms=10) plot(ones(Nt), arange(Nt), 'ok', ms=10) for i, j in z...
2.828125
3
src/main/resources/pip-inspector.py
antontroshin/synopsys-detect
91
53195
# pylint: disable=fixme, line-too-long, import-error, no-name-in-module # # Copyright (c) 2020 Synopsys, Inc. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownersh...
1.695313
2
Day_02/part1.py
Uklusi/AdventOfCode2018
0
53196
result = 0 boxIds = [] with open("input.txt", "r") as input: for line in input: line = line.strip() boxIds.append(line) count2 = 0 count3 = 0 for boxId in boxIds: flag2 = True flag3 = True for c in set(boxId): n = boxId.count(c) if n == 2 and flag2: count2 +...
2.8125
3
armyknife_src/on_aw.py
actingweb/armyknife
0
53197
import json import logging import hashlib from actingweb import on_aw from armyknife_src import webexrequest from armyknife_src import webexbothandler from armyknife_src import webexmessagehandler from armyknife_src import fargate PROP_HIDE = [ "email", "oauthId" ] PROP_PROTECT = PROP_HIDE + [ "service_st...
2.09375
2
tests/test_imports.py
JunCEEE/hummingbird
14
53198
import os, sys import warnings __thisdir__ = os.path.dirname(os.path.realpath(__file__)) # Testing the import of the numpy package def test_import_numpy(): try: import numpy as np except ImportError as e: assert(1 == 0), "Numpy could not be imported:\n %s" %e sys.path.pop(0) # Testing the ...
2.375
2
typical90/bo/main.py
KATO-Hiro/AtCoder
2
53199
# -*- coding: utf-8 -*- def convert_decimal_to_n_ary_number(n: int, m_ary_number: int = 2) -> int: '''Represents conversion from decimal number to n-ary number. Args: n: Input number (greater than 1). m_ary_number: m-ary number (from 2 to 10). Returns: values of m-ary number. L...
4.09375
4