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 |
|---|---|---|---|---|---|---|
temperature.py | pso-code/shiny-domotic | 0 | 12794751 | import glob
import time
import datetime
def read_temperature_file (location) :
# Opens the file containing the temperature
temperature_file = open(location)
# Reading the file...
content = temperature_file.read()
# Closing file after reading
temperature_file.close()
return content
def ext... | 3.234375 | 3 |
django_socketio_chat/utils.py | leukeleu/django-socketio-chat | 6 | 12794752 | from rest_framework.renderers import JSONRenderer
from django.utils import simplejson
def prepare_for_emit(obj):
"""
Prepare the object for emit() by Tornadio2's (too simple) JSON renderer
- render to JSON using Django REST Framework 2's JSON renderer
- convert back to _simple_ Python object using Dja... | 2.328125 | 2 |
coding-challenges/array-problems/search-insert-position/solution.py | mcqueenjordan/learning_sandbox | 1 | 12794753 | class Solution:
def searchInsert(self, nums, target):
"""
Given a sorted array and a target value, return the index if the target
is found. If not, return the index where it would be if it were
inserted in order. You may assume no duplicates in the array.
"""
return b... | 4 | 4 |
47.Replace_list_-1_0_1.py | gptakhil/Python_Practice_Beginner | 2 | 12794754 | <reponame>gptakhil/Python_Practice_Beginner
mylist = [8,4,7,6,2,3,5,-2,-1,0,1,-6,-8,5,0,-9]
print(mylist)
for i in range(len(mylist)):
if mylist[i]>0:
mylist[i]=1
elif mylist[i]<0:
mylist[i]=-1
else: mylist[i]=0
print(mylist) | 3.75 | 4 |
cwProject/cwApp/migrations/0003_car.py | cs-fullstack-2019-spring/django-models3-cw-autumn-ragland | 0 | 12794755 | <filename>cwProject/cwApp/migrations/0003_car.py<gh_stars>0
# Generated by Django 2.0.6 on 2019-02-21 17:52
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cwApp', '0002_auto_20190221_1735'),
]
operations = [
migrations.... | 1.890625 | 2 |
worker.py | mdylan2/propertyfinderscraper | 0 | 12794756 | <reponame>mdylan2/propertyfinderscraper
from rq import Connection, Worker
from dash_rq_demo import app, queue
from dash_rq_demo.core import conn
if __name__ == "__main__":
with app.server.app_context():
with Connection(conn):
w = Worker([queue])
w.work()
| 1.421875 | 1 |
src/cvdata/mask.py | edumotya/cvdata | 15 | 12794757 | <reponame>edumotya/cvdata
import argparse
import collections
import concurrent.futures
import json
import logging
import math
import os
import random
from typing import Dict
import cv2
import numpy as np
import six
import tensorflow as tf
from tensorflow.compat.v1.python_io import TFRecordWriter
from tqdm import tqdm
... | 2.453125 | 2 |
app/internal/module/video/encode.py | kuropengin/SHINtube-video-api | 0 | 12794758 | <gh_stars>0
from .filemanager import filemanager
from ..command_run import command_run
from ..logger import logger
import json
import asyncio
import os
from typing import List
from dataclasses import dataclass
class encoder_class:
def __init__(self):
# サンプル動画
self.sample_dir = "./sample"
s... | 2.171875 | 2 |
GhidraGdb.py | ArcTropics/GhidraGdb | 0 | 12794759 | from pwn import *
import sys
import os
from pathlib import Path
from threading import Thread
from clients.GhidraCommandClient import GhidraCommandClient
class GhidraGdb:
"""The main class which encapsulates the whole GhidraGdb framework
"""
def __init__(self, process=None):
self.fifo = No... | 2.546875 | 3 |
Adapter/python/AdapterPattern.py | hanmomhanda/DesignPatternStudy | 4 | 12794760 | class Target:
def print_weak(self):
raise NotImplementedError
def print_strong(self):
raise NotImplementedError
class Adaptee:
def __init__(self, message):
self.message = message
def print_paren(self):
print("(" + self.message + ")")
def print_asterisk(self):
... | 3.09375 | 3 |
Crypto-Nexus/ChatCommon.py | idnrfc/Crypto-Nexus | 1 | 12794761 | <filename>Crypto-Nexus/ChatCommon.py
"""
개발환경 : PyQt5 x64, Python 3.4.3 x64, Windows 8.1 x64
파일 : ChatCommon.py
내용 : 그냥 공통적이고 주로 쓰이는 변수만 정리
"""
class ChatCommon:
# 타입 지정을 위한 변수... 그냥 자주 쓰는거
TYPE_OF_CAESAR = 0
TYPE_OF_TRANSPOSITION = 1
TYPE_OF_AFFINE = 2
# 프로그램에서 지정한 형식의 메세지가 아닌 경우
TYPE_OF_WRO... | 2.1875 | 2 |
example_004_oop_decorator_pattern.py | s-c-23/Elements-of-Software-Design | 3 | 12794762 | <reponame>s-c-23/Elements-of-Software-Design
"""The Decorator pattern is used to dynamically add a new features/functionalities
to an object without changing its implementation. It differs from inheritance because
the new functionalities are attached to that particular object on-demand,
not to the entire subclass."""
... | 4.375 | 4 |
tests/core/specifications/test_object_of_account_specification.py | douwevandermeij/fractal | 2 | 12794763 | from dataclasses import make_dataclass
from fractal.core.specifications.object_of_account_specification import (
ObjectOfAccountSpecification,
)
def test_object_of_account_specification():
spec = ObjectOfAccountSpecification("abc", "def")
DC = make_dataclass("DC", [("id", str), ("account_id", str)])
... | 2.578125 | 3 |
benchmark/bench_dd.py | Watch-Later/recipes | 1,418 | 12794764 | <reponame>Watch-Later/recipes
#!/usr/bin/python3
import re, subprocess
bs = 1
count = 1024 * 1024
while bs <= 1024 * 1024 * 8:
args = ['dd', 'if=/dev/zero', 'of=/dev/null', 'bs=%d' % bs, 'count=%d' % count]
result = subprocess.run(args, capture_output=True)
seconds = 0
message = str(result.stderr)
... | 2.328125 | 2 |
easyPlog/__init__.py | whuhit/easyPlog | 0 | 12794765 | <reponame>whuhit/easyPlog<filename>easyPlog/__init__.py
"""
@author: yangqiang
@contact: <EMAIL>
@file: __init__.py.py
@time: 2020/4/3 14:49
"""
from .easyPlog import Plog
| 1.046875 | 1 |
models/__init__.py | theorenck/pm-bot | 0 | 12794766 | <filename>models/__init__.py
from .colors import Color, Colors
from .grid import Location, Annotation, Annotations, Grid
from .minimap import Minimap
from .astar import AStarSearch | 1.4375 | 1 |
imports/dataHandler.py | mike-tr/upass-spork | 1 | 12794767 | import json
import imports.fileReader as reader
class dataBase:
def __init__(self, path, key):
self.file = reader.efile(path, key);
if(len(self.file.data) > 0):
self.json = json.loads(self.file.data)
else:
self.json = json.loads("{}")
self.json["key"] = k... | 3.171875 | 3 |
app/controllers/main_routes.py | HungUnicorn/mssql-prom-exporter | 1 | 12794768 | """
This is where all the general routes and controllers are defined.
"""
from flask import Blueprint
from flask import current_app as app
from flask import make_response
main_blueprint = Blueprint('main_blueprint', __name__)
@main_blueprint.route('/')
def index():
return make_response()
@main_blueprint.route... | 2.625 | 3 |
trade/urls.py | RoosDaniel/Fadderjobb | 2 | 12794769 | from django.urls import path
from . import views
app_name = "trade"
urlpatterns = [
path('start/<str:receiver_username>/', views.start, name="start"),
path('<str:other_username>/', views.see_trade, name="see"),
path('change/<str:other_username>', views.change_trade, name="change"),
]
| 1.945313 | 2 |
scripts/codraw_dataset_generation/codraw_raw_to_hdf5.py | capstonecs42/GeNeVA_datasets_dev | 36 | 12794770 | <filename>scripts/codraw_dataset_generation/codraw_raw_to_hdf5.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""
Script to parse and read raw CoDraw data and save it in HDF5 format for GeNeVA-GAN
"""
from glob import glob
import json
import os
import pickle
import string
import cv2
import... | 2.484375 | 2 |
project/scripts/update_eo_version.py | polystat/c2eo | 12 | 12794771 | <gh_stars>10-100
#! /usr/bin/python3
import sys
import re as regex
# Our scripts
import tools
import settings
def main():
tools.pprint()
current_version = settings.get_setting('current_eo_version')
latest_version = settings.get_setting('latest_eo_version')
is_latest_version, latest_version = is_upd... | 2.609375 | 3 |
release-assistant/test/coverage_count.py | openeuler-mirror/release-tools | 1 | 12794772 | #!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a c... | 1.882813 | 2 |
doc/workflow/examples/example_driver1.py | PyUtilib/PyUtilib | 24 | 12794773 | <reponame>PyUtilib/PyUtilib<gh_stars>10-100
import pyutilib.workflow
import pyutilib.component.core
# @usage:
import tasks_yz
driver = pyutilib.workflow.TaskDriver()
driver.register_task('TaskZ')
driver.register_task('TaskY')
print(driver.parse_args(['TaskZ','--x=3','--y=4']))
print(driver.parse_args(['TaskY','--X=3... | 2.109375 | 2 |
AxonDataset.py | idhamari/CapsPix2Pix | 24 | 12794774 | import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch
from torch.autograd import Variable
from load_memmap import *
class AxonDataset(Dataset):
"""" Inherits pytorch Dataset class to load Axon Dataset """
def __init__(self, data_name='crops64... | 2.71875 | 3 |
dev/source/RequestClass.py | Gerard-007/deenux | 0 | 12794775 | <reponame>Gerard-007/deenux
from CustomerClass import Customer
import random
class Order:
num_of_orders = 0
def __init__(self):
self.order_ID = random.randint(00000000, 999999999)
self.customer_ID =Customer.business_ID
self.ship_to_party_ID = Customer.business_address | 2.953125 | 3 |
library/connecter/ansible/yaml/read2file.py | GNHJM/lykops | 141 | 12794776 | import os
from library.connecter.ansible.yaml import Yaml_Base
from library.utils.file import read_file
from library.utils.path import get_pathlist
class Read_File(Yaml_Base):
def router(self, this_path, this_basedir=None, yaml_tpye='main', preserve=True, together=False, name='', describe=''):
... | 2.265625 | 2 |
cvs_scrapy/pipelines.py | joehwang/auto-door | 5 | 12794777 | <reponame>joehwang/auto-door
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import redis
import re
import os
class CvsScrapyPipeline(object):
def open_spider(self,spider):
... | 2.375 | 2 |
dbHelper.py | portbusy/moneytrakerBot | 1 | 12794778 | <gh_stars>1-10
import sqlite3
class DBHelper:
def __init__(self, dbname="expenses.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def setup(self):
outcome = "CREATE TABLE IF NOT EXISTS outcome (date date, value float, comment varchar(50))"
income = "CREATE T... | 3.46875 | 3 |
tests/utils.py | chstan/autodiDAQt | 1 | 12794779 | <filename>tests/utils.py<gh_stars>1-10
from dataclasses import dataclass
from autodidaqt.instrument import LogicalAxisSpecification
from autodidaqt.mock import MockMotionController
@dataclass
class CoordinateOffsets:
x_off: float = 0
y_off: float = 0
z_off: float = 0
class LogicalMockMotionController(M... | 2.53125 | 3 |
App/utils/need_login.py | msamunetogetoge/BookRecommendationApp | 0 | 12794780 | <reponame>msamunetogetoge/BookRecommendationApp
from functools import wraps
from django.shortcuts import render
from Login.models import M_User
def need_login(redirect_field_name:str, err_msg:str, view_func=None):
"""
login が必要な場所で使う。
loginしていない時に、redirecr_field_name に{'msg':err_masg} を付与してrenderする。... | 2.171875 | 2 |
qp_search_project/searcher/services.py | enlighter/ndl-question-papers-search-hub | 1 | 12794781 | import json
from urllib import request
import requests
#for rest api
repository_url = 'http://10.3.100.22:8080'
restpath = '/rest'
xmlpath = '/xmlui'
def get_communities():
communities = request.urlopen(repository_url + restpath + '/communities')
communities_json = communities.read().decode('utf-8')
comm... | 3.0625 | 3 |
sdk/python/pulumi_azure/network/network_security_group.py | Frassle/pulumi-azure | 0 | 12794782 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class NetworkSecurityGroup(pulumi.CustomResource):
"""
Ma... | 1.875 | 2 |
SHOOTER/bullets.py | AnshDubey1999/Customized-Space-Shooter | 0 | 12794783 | <reponame>AnshDubey1999/Customized-Space-Shooter
def bullets_remove(bullets):
# checks if bullets have crossed the display. If a bullet has passed the
# current game window, remove it
#returns an empty list if the bullet list is empty
if len(bullets) == 0:
return []
else:
index = 0
while True:
if len(bu... | 3.578125 | 4 |
Python/Pandas/Inbuilt_impootant_functions.py | themohitpapneja/Code_Dump | 0 | 12794784 | X=[4.5,6,7,1,0.9,5.6,4.3,4,4.65,3,9]
summ=sum(X)
print(summ)
Y=sorted(X)
print(Y)
X.sort()
print(X) | 3.125 | 3 |
app/__init__.py | Jhustin27/Eye-of-summit-2.0 | 0 | 12794785 | """
Project Summit es un programa relacionado con el parque Nacional SUMMIT, mostrando al usuario todos los animales que hay en el parque y su taxonomía.
"""
from app import Listas
import os
def clases(opc):
"""
Clases es una función que despliega la lista de los 2 tipos de clases de animales que hay en el... | 3.796875 | 4 |
Python 3 - WebScraping/Teste2.py | Paimonz/Python-Estudos | 0 | 12794786 | <filename>Python 3 - WebScraping/Teste2.py
'''import requests
r = requests.get('https://www.investopedia.com/terms/f/forex.asp')
print(r.text)
print(r.encoding)
print(r.headers)
print(r.status_code)'''
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's stor... | 3.859375 | 4 |
silk/utils/multipleprocess.py | tzm41/silk | 1 | 12794787 | <filename>silk/utils/multipleprocess.py
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | 2.921875 | 3 |
services/src/trader/trader_v1.py | pjw960408/binance-trader-c1 | 0 | 12794788 | <filename>services/src/trader/trader_v1.py
import os
import gc
import time
import ccxt
import requests
import urllib3
import joblib
import pandas as pd
import numpy as np
from dataclasses import dataclass
from config import CFG
from trainer.models import PredictorV1
from database.usecase import Usecase
from exchange.c... | 2.046875 | 2 |
lib-other/pylib/consensus/test/test_consensus.py | endolith/Truthcoin | 161 | 12794789 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for Truthcoin's consensus functions.
Verifies that the consensus algorithm works as expected.
Check test_answers.txt for expected results.
"""
from __future__ import division, unicode_literals, absolute_import
import os
import sys
import platform
import json
impo... | 2.65625 | 3 |
happ/tests/api/admin/test_interests.py | Mafioso/happ-backend | 1 | 12794790 | from rest_framework import status
from rest_framework.test import APISimpleTestCase
from rest_framework_jwt.settings import api_settings
from happ.models import User, Interest, LogEntry
from happ.factories import (
UserFactory,
InterestFactory,
CityFactory,
)
from happ.tests import *
class Tests(APISimpl... | 2.515625 | 3 |
Basico_03.py | Emgicraft/PythonGUI_PyQt5 | 0 | 12794791 | import sys
from PyQt5 import QtGui
import PyQt5.QtWidgets as qw
class Mensaje(qw.QWidget):
def __init__(self, parent=None):
qw.QWidget.__init__(self, parent)
self.setGeometry(700, 300, 640, 640)
self.setWindowTitle("Basico 03")
self.setWindowIcon(QtGui.QIcon("Recursos/Icon-Python_P... | 2.984375 | 3 |
Paths/Re-interpolate.py | harbortype/glyphs-scripts | 23 | 12794792 | <filename>Paths/Re-interpolate.py<gh_stars>10-100
#MenuTitle: Re-interpolate
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Re-interpolates selected layers. Makes it possible to assign a keyboard shortcut to this command via Preferences > Shortcuts (in Glyphs 3) or... | 1.867188 | 2 |
mltools/libos.py | thesfinox/mltools | 0 | 12794793 | import os
import psutil
class InfoOS:
'''
This class retrieves and prints information on the current OS.
Public methods:
Attributes:
os: the current OS,
kernel: the current release,
arch: the current architecture,
threads: the number of available CPU t... | 3.359375 | 3 |
four_table.py | ChipJust/diodes | 0 | 12794794 | <filename>four_table.py
#! python3
r"""
THD = sqrt ( Sum(2, n)(Mag^2[n]) ) / Mag[1]
"""
import argparse
import re
import collections
import math
import itertools
import os
parser = argparse.ArgumentParser(description='Create fourier tables out of a collection of fourier files')
#parser.add_argument('models', nargs='+... | 2.890625 | 3 |
src/presence_analyzer/tests.py | stxnext-kindergarten/presence-analyzer-asierhej | 0 | 12794795 | <reponame>stxnext-kindergarten/presence-analyzer-asierhej
# -*- coding: utf-8 -*-
"""
Presence analyzer unit tests.
"""
from __future__ import unicode_literals
import os.path
import json
import datetime
import time
import unittest
from collections import OrderedDict
import main # pylint: disable=relative-import
impor... | 2.1875 | 2 |
bag/tests/test_views.py | keeks-mtl/go-tennis | 0 | 12794796 | <filename>bag/tests/test_views.py
from django.test import TestCase, Client
from django.urls import reverse
from products.models import Category, Product
class TestBagViews(TestCase):
def setUp(self):
self.client = Client()
self.home = reverse("home")
self.view_bag = reverse("view_bag")
... | 2.4375 | 2 |
docs/source/sample_scripts/run_vc_pipeline.py | genestack/python-client | 2 | 12794797 | <reponame>genestack/python-client<filename>docs/source/sample_scripts/run_vc_pipeline.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_libra... | 2.453125 | 2 |
topo_processor/file_system/get_fs.py | linz/topo-processor | 11 | 12794798 | from fsspec.implementations.local import LocalFileSystem
from s3fs import S3FileSystem
def is_s3_path(path: str) -> bool:
if path.startswith("s3://"):
return True
return False
def bucket_name_from_path(path: str) -> str:
path_parts = path.replace("s3://", "").split("/")
return path_parts.pop... | 2.46875 | 2 |
programmers/skill-test-lv1/get_middle_char.py | love-adela/algorithm | 3 | 12794799 | <filename>programmers/skill-test-lv1/get_middle_char.py
def solution(s):
length = len(s)
return s[length // 2] if length % 2 != 0 else s[(length // 2)-1:(length // 2)+1]
# Test
# s = 'abcde'
s = 'qwer'
print(solution(s))
#5 -> 2
#4 -> [1:3] # 1, 2
| 3.8125 | 4 |
books/models.py | oliverroick/django-tests | 0 | 12794800 | from django.db import models
from django.contrib.auth.models import User
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User)
| 2.09375 | 2 |
way/python/first_steps/zadachi/podkat/podkat_k_programmistke.py | only-romano/junkyard | 0 | 12794801 | <reponame>only-romano/junkyard
#! Подкат к программистке.
# Вариант с инпутом.
def podkat():
a = str(input("Привет, солнце, посветишь для меня сегодня ?): "))
right_answers = ("да конечно посвечу афк пошли мяф го игого"
"гоу хочу хотела красава мечтаю давай ага супер пойдём")
if a.lower(... | 3.46875 | 3 |
index.py | z0di4ckX/IP-finder | 0 | 12794802 | from flask import Flask, redirect, url_for, render_template
#import ip_finder
app = Flask(__name__)
@app.route("/<name>")
def home(name):
return render_template("index.html", content=name)
# @app.route("/<name>")
# def user(name):
# return f"Hello {name}!"
# # Working on it!
# @app.route("/<ipF>")
# def ip(i... | 2.546875 | 3 |
pingyingdict/data_clean/__init__.py | sujing863/crawler-dict | 0 | 12794803 | # -*- coding: utf-8 -*-
"""
@Time : 2021/1/9 17:28
@Author : s_jing
@File : __init__.py.py
@Software: PyCharm
"""
| 0.925781 | 1 |
src/pyglue/DocStrings/Exception.py | omenos/OpenColorIO | 7 | 12794804 |
class Exception:
"""
An exception class to throw for errors detected at runtime.
.. warning::
All functions in the Config class can potentially throw this exception.
"""
def __init__(self):
pass
| 2.21875 | 2 |
openmdao.gui/src/openmdao/gui/urls.py | OzanCKN/OpenMDAO-Framework | 3 | 12794805 | from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth import views as authviews
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# favicon
(r'^favicon\.ico$', 'django.views.generic.simp... | 1.929688 | 2 |
landscape/prerequisites.py | shaneramey/landscape-cli | 0 | 12794806 | import subprocess as sp
import platform
import os.path
import logging
def install_prerequisites(os_platform):
"""
Installs prerequisites for the landscape CLI tool
Returns: None
"""
install_gsed(os_platform)
install_minikube(os_platform)
install_lastpass(os_platform)
install_vault(os_p... | 1.984375 | 2 |
pacote-download/ex(1-100)/ex098.py | gssouza2051/python-exercicios | 0 | 12794807 | <gh_stars>0
'''Faça um programa que tenha uma função chamada contador(),
que receba três parâmetros: início, fim e passo. Seu programa tem que realizar três contagens através da função criada:
a) de 1 até 10, de 1 em 1
b) de 10 até 0, de 2 em 2
c) uma contagem personalizada'''
from time import sleep
def contador(i,f... | 3.890625 | 4 |
ikalog/ui/panel/preview.py | fetus-hina/IkaLog | 285 | 12794808 | <gh_stars>100-1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 <NAME>
#
# 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.apa... | 2.28125 | 2 |
agent.py | globocom/Tryout-agent | 0 | 12794809 | # -*- encoding: utf-8 -*-
import os
import subprocess
import settings
import git
import requests
def clone_challenge(challenge_repository, challenge_name):
try:
git.Git().clone(challenge_repository)
if not os.path.exists(challenge_name):
return "Can't download this repository", True
... | 2.5625 | 3 |
awx/main/management/commands/provision_instance.py | ziegenberg/awx | 0 | 12794810 | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved
import os
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.conf import settings
from awx.main.models import Instance
class Command(BaseCommand):
"""
Internal tower command.
Register t... | 1.90625 | 2 |
src/helpers.py | vergoh/micropython-spotify-status-display | 3 | 12794811 | # reduced from https://github.com/blainegarrett/urequests2
import binascii
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-')
def quote(s):
res = []
for c in s:
if c in always_safe:
res.append(c)
continue
... | 2.6875 | 3 |
fluent_pages/pagetypes/textfile/page_type_plugins.py | django-fluent/django-fluent-pages | 59 | 12794812 | from django.http import HttpResponse
from fluent_pages.extensions import PageTypePlugin, page_type_pool
from .models import TextFile
@page_type_pool.register
class TextFilePlugin(PageTypePlugin):
model = TextFile
is_file = True
def get_response(self, request, textfile, **kwargs):
content_type =... | 2.09375 | 2 |
Alien Invasion/sound_fx.py | rubotic1/AlienInvaders | 0 | 12794813 | <filename>Alien Invasion/sound_fx.py
import pygame
class Sound_fx:
"""Clase que controla el sonido."""
def __init__(self):
""" Inicializamos el sonido y cargamos los recursos"""
self.init_music = 'sound/01_Title Screen.mp3'
self.game_music = 'sound/12_Invader_Homeworld.mp3'
self.shot = pygame.mixer.Sound('s... | 3.1875 | 3 |
resources/lib/api/models/playback.py | MatiasStorm/plugin.video.tv2play | 0 | 12794814 | <filename>resources/lib/api/models/playback.py
class PlayBack:
def __init__(self, playback):
self.playback = playback
self.src = playback["smil"]["video"]["src"]
self.mime_type = playback["smil"]["video"]["type"]
self.license_token = playback["smil"]["securityLicense"]["token"]
... | 2.234375 | 2 |
pokemon/migrations/0002_auto_20200224_0512.py | andresRah/PokemonDjango | 0 | 12794815 | <reponame>andresRah/PokemonDjango
# Generated by Django 3.0.3 on 2020-02-24 05:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pokemon', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | 1.921875 | 2 |
src/cgen/ast/literal.py | cursedclock/swiss_water_compiler | 0 | 12794816 | import enum
import struct
from .abstract import AbstractNode
from .utils import ValuedNodeMixin, NodeContext
class PrimitiveTypes(enum.Enum):
Null = 0
Bool = 1
Int = 2
Double = 3
String = 4
# aliases
NULL = 0
BOOLEANLITERAL = 1
INTLITERAL = 2
DOUBLELITERAL = 3
STRINGLITERA... | 2.765625 | 3 |
Chapter05/01-chapter-content/filter2D_kernels.py | yaojh01/Mastering-OpenCV-4-with-Python | 2 | 12794817 | """
Comparing different kernels using cv2.filter2D()
"""
# Import required packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
def show_with_matplotlib(color_img, title, pos):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB
img_RGB = color_img[:, :, ::-1... | 3.375 | 3 |
python/src/mapreduce/api/map_job/map_job_control.py | rolepoint/appengine-mapreduce | 0 | 12794818 | <filename>python/src/mapreduce/api/map_job/map_job_control.py
#!/usr/bin/env python
"""User API for controlling Map job execution."""
from google.appengine.ext import db
from mapreduce import util
# pylint: disable=g-bad-name
# pylint: disable=protected-access
def start(job_config=None,
in_xg_transaction... | 2.140625 | 2 |
django_command_admin/apps.py | andrewp-as-is/django-admin-commands.py | 1 | 12794819 | <reponame>andrewp-as-is/django-admin-commands.py
from django.apps import AppConfig
class Config(AppConfig):
name = 'django_command_admin'
verbose_name = 'command-admin'
| 1.453125 | 1 |
mc2d/core/__init__.py | Den4200/mc2d | 0 | 12794820 | <reponame>Den4200/mc2d
from mc2d.core.generators import MapGenerator
from mc2d.core.grid import Grid
from mc2d.core.inventory import Inventory
from mc2d.core.player import Player
from mc2d.core.world import World
__all__ = (
'Grid',
'Inventory',
'MapGenerator',
'Player',
'World'
)
| 1.53125 | 2 |
cogs/running.py | Piturnah/Society-voting-bot | 0 | 12794821 | <reponame>Piturnah/Society-voting-bot<filename>cogs/running.py<gh_stars>0
# A Cog for running, and managing your run, in elections #
import traceback
from pyrankvote import Candidate
from discord.ext import commands
from cogs import helpers
class Running(commands.Cog):
# Initialisation #
def __init__(sel... | 2.546875 | 3 |
app.py | uvcloud/sample-12factor-docker-flask | 0 | 12794822 |
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/welcome")
def welcome():
return render_template("welcome.html")
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
| 2.671875 | 3 |
models/topological_sort.py | BLimmie/manga_ordering | 0 | 12794823 | from collections import defaultdict
from .metrics import calculate_metrics_list
class Graph:
"""
The code for this class is based on geeksforgeeks.com
"""
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u... | 3.3125 | 3 |
augmentation/augmentation.py | akaver/pbt-demo-mnist | 0 | 12794824 | <reponame>akaver/pbt-demo-mnist
import logging
import PIL
import random
import numpy as np
import torch
import torchvision.transforms.functional as TF
log = logging.getLogger(__name__)
# define augmentation functions
def auto_contrast(img: torch.Tensor, level: float, fill=None) -> torch.Tensor:
fill = img[0, 0... | 2.328125 | 2 |
example.py | ollieglass/sqlalchemy-pg-copy | 2 | 12794825 | import sys
from sqlalchemy import create_engine
import pg_copy
if __name__ == "__main__":
engine = create_engine(sys.argv[1])
target_table = 'example_table'
objs = [
{
'id': i,
'description': f'record description {i}'
} for i in range(100_000)
]
pg_copy.i... | 2.640625 | 3 |
Easy/Repeated String/repeatedString.py | Zealll/HackerRank | 0 | 12794826 | <reponame>Zealll/HackerRank
def repeatedString(s, n):
dictionary = {'a': 0}
length = n // len(s)
if 'a' not in s:
return 0
for i in s:
if i == 'a':
dictionary['a'] += 1
remaining = n - len(s) * length
total = int(dictionary['a'] * length)
if remaining > 0:... | 3.71875 | 4 |
nodes/remove_directory.py | iograft/iograft | 0 | 12794827 | <filename>nodes/remove_directory.py
# Copyright 2021 Fabrica Software, LLC
import os
import shutil
import iograft
import iobasictypes
class RemoveDirectory(iograft.Node):
"""
Remove the given directory.
"""
directory = iograft.InputDefinition("directory", iobasictypes.String())
remove_contents =... | 2.96875 | 3 |
otter/test/cloud_client/test_clb.py | codebyravi/otter | 20 | 12794828 | <filename>otter/test/cloud_client/test_clb.py
"""Tests for otter.cloud_client.clb"""
import json
from effect import sync_perform
from effect.testing import (
EQFDispatcher, const, intent_func, noop, perform_sequence)
import six
from twisted.trial.unittest import SynchronousTestCase
from otter.cloud_client impo... | 1.921875 | 2 |
3d-tracking/tools/visualize_kitti.py | sadjadasghari/3d-vehicle-tracking | 603 | 12794829 | import os
import re
import sys
import argparse
import json
import numpy as np
from glob import glob
import cv2
from utils.plot_utils import RandomColor
def parse_args():
parser = argparse.ArgumentParser(
description='Monocular 3D Tracking Visualizer',
formatter_class=argpa... | 2.53125 | 3 |
Decision_tree/code.py | AnurodhRaina/ga-learner-dsmp-repo | 1 | 12794830 | # --------------
#Importing header files
import pandas as pd
from sklearn.model_selection import train_test_split as tts
# Code starts here
data= pd.read_csv(path)
X= data.drop(['customer.id','paid.back.loan'],1)
y=data['paid.back.loan']
X_train, X_test, y_train, y_test = tts(X,y,random_state=0,test_size=0.3)
# C... | 2.953125 | 3 |
swift3/__init__.py | ntk148v/swift3 | 10 | 12794831 | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 required by applicable law or agre... | 2.125 | 2 |
test/single/test_task_service.py | Infi-zc/horovod | 7,676 | 12794832 | # Copyright 2021 Uber Technologies, 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/licenses/LICENSE-2.0
#
# Unless required by applica... | 2.078125 | 2 |
anchore_engine/services/policy_engine/engine/policy/gates/conditions.py | Talanor/anchore-engine | 0 | 12794833 | from collections import namedtuple
from anchore_engine.services.policy_engine.engine.policy.params import InputValidator
from anchore_engine.services.policy_engine.engine.policy.gate import Gate, GateMeta, BaseTrigger
class AttributeListValidator(InputValidator):
def __init__(self, attrs):
self.attrs = at... | 2.46875 | 2 |
wyrdin/core/backend/generic.py | RichardLitt/wyrd-django-dev | 0 | 12794834 | <filename>wyrdin/core/backend/generic.py
#!/usr/bin/python3
#-*- coding: utf-8 -*-
# This code is PEP8-compliant. See http://www.python.org/dev/peps/pep-0008/.
"""
Wyrd In: Time tracker and task manager
CC-Share Alike 2012 © The Wyrd In team
https://github.com/WyrdIn
"""
class DBObject(object):
_next_id = 0
... | 2.375 | 2 |
output/models/saxon_data/id/id011_xsd/__init__.py | tefra/xsdata-w3c-tests | 1 | 12794835 | <filename>output/models/saxon_data/id/id011_xsd/__init__.py
from output.models.saxon_data.id.id011_xsd.id011 import (
Doc,
Para,
)
__all__ = [
"Doc",
"Para",
]
| 1.21875 | 1 |
linked-lists/linked_list_test.py | jrandson/data-structures | 0 | 12794836 | <reponame>jrandson/data-structures<gh_stars>0
import unittest
from linked_list import LinkedList
class LinkListTest(unittest.TestCase):
def test_add_node(self):
ll = LinkedList()
self.assertEqual(True,ll.is_empty())
self.assertEqual('',ll.show_elements())
ll.add_node(10)
self.assertEqual(False,ll.... | 3.90625 | 4 |
cut_twist_process/cut_part.py | ericosmic/2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement | 886 | 12794837 | # -*- coding: utf-8 -*-
# @Time : 19-11-19 22:25
# @Author : <NAME>
# @Reference : None
# @File : cut_twist_join.py
# @IDE : PyCharm Community Edition
"""
将身份证正反面从原始图片中切分出来。
需要的参数有:
1.图片所在路径。
输出结果为:
切分后的身份证正反面图片。
"""
import os
import cv2
import numpy ... | 2.578125 | 3 |
bluetooth_write.py | DethCount/usb-gamepad | 0 | 12794838 | import time
import concurrent
import asyncio
import bleak
async def main():
loop = asyncio.new_event_loop()
client = bleak.BleakClient('D8:A9:8B:7E:1E:D2')
is_connected = await client.connect()
print(is_connected)
response = await client.write_gatt_char('0000ffe1-0000-1000-8000-00805f9b34fb', b'MO... | 2.5 | 2 |
finance_ml/sampling/utils.py | BTETON/finance_ml | 446 | 12794839 | <gh_stars>100-1000
import pandas as pd
def get_ind_matrix(bar_idx, t1):
ind_m = pd.DataFrame(0, index=bar_idx,
columns=range(t1.shape[0]))
for i, (t0_, t1_) in enumerate(t1.iteritems()):
ind_m.loc[t0_:t1_, i] = 1
return ind_m
def get_avg_uniq(ind_m, c=None):
if c is ... | 2.515625 | 3 |
setup.py | aozhiwei/srap | 0 | 12794840 | <reponame>aozhiwei/srap
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import sys
if sys.version_info < (2, 5):
sys.exit('Python 2.5 or greater is required.')
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import srap
with ope... | 1.84375 | 2 |
docs/source/guide/examples/test_future.py | enthought/traits-futures | 10 | 12794841 | <filename>docs/source/guide/examples/test_future.py
# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementione... | 2.328125 | 2 |
main/validating-credit-card-number/validating-credit-card-number.py | EliahKagan/old-practice-snapshot | 0 | 12794842 | #!/usr/bin/env python3
import re
CCNUM = re.compile(r'(?!.*(\d)(?:\D?\1){3})[456]\d{3}(-?)(?:\d{4}\2){2}\d{4}')
for _ in range(int(input())):
print('Valid' if CCNUM.fullmatch(input().strip()) else 'Invalid')
| 3.234375 | 3 |
tests/obj/business_test.py | ruchir594/messenger-bot-yelp-aws | 1 | 12794843 | <filename>tests/obj/business_test.py
# -*- coding: UTF-8 -*-
import io
import json
from tests.testing import resource_filename
from yelp.obj.business import Business
from yelp.obj.business import Category
def test_init_business():
with io.open(resource_filename('json/business_response.json')) as biz:
res... | 2.53125 | 3 |
src/palette.py | Guillaume227/supercoco | 2 | 12794844 | <reponame>Guillaume227/supercoco<gh_stars>1-10
from .elems import Elements, Categories
from . import elems
from . import media
import os
import pygame
from . import menu
_Selection = None
RepertoiresVrac = ['decors Vrac', 'Cap Vrac']
def DecorsVrac(repertoire):
vrac_dir = os.path.join(media.MEDIA_REP, repertoir... | 2.40625 | 2 |
m5-joyc-mp/main.py | jessevl/m5-roverc-joyc-mp | 0 | 12794845 | from m5stack import *
from m5ui import *
import espnow
import wifiCfg
import hat
joy_pos = None
paired = False
addr = None
data = None
setScreenColor(0x000000)
axp.setLDO2Volt(2.8)
hat_joyc0 = hat.get(hat.JOYC)
label0 = M5TextBox(22, 48, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label1 = M5TextBox(22, 62, "Text"... | 2.328125 | 2 |
atlas/foundations_contrib/src/test/helpers/test_lazy_redis.py | DeepLearnI/atlas | 296 | 12794846 | <filename>atlas/foundations_contrib/src/test/helpers/test_lazy_redis.py
import unittest
from mock import Mock
from foundations_contrib.helpers.lazy_redis import LazyRedis
class TestLazyRedis(unittest.TestCase):
class MockObject(object):
def __init__(self):
self.value = 5
self.nam... | 2.6875 | 3 |
src/automotive/application/panel/panel.py | philosophy912/automotive | 0 | 12794847 | # -*- coding:utf-8 -*-
# --------------------------------------------------------
# Copyright (C), 2016-2021, lizhe, All rights reserved
# --------------------------------------------------------
# @Name: gui.py.py
# @Author: lizhe
# @Created: 2021/12/15 - 21:24
# --------------------------------... | 1.898438 | 2 |
subs2cia/subzipper.py | mdVNwyRbm/subs2cia | 53 | 12794848 | <gh_stars>10-100
from subs2cia.argparser import get_args_subzipper
from subs2cia.sources import is_language
import logging
from pathlib import Path
import pycountry
from pprint import pprint
def start():
args = get_args_subzipper()
args = vars(args)
if args['verbose']:
# if args['debug']:
... | 2.578125 | 3 |
lichee/module/torch/layer/longformer_multi_headed_attn.py | Tencent/Lichee | 91 | 12794849 | <filename>lichee/module/torch/layer/longformer_multi_headed_attn.py
# -*- coding: utf-8 -*-
# _*_ conding:utf-8 _*_
# Author : Nick
# Time : 2020/9/15 3:21 下午
from typing import List, Tuple
import torch
import math
def nonzero_tuple(x):
if x.dim() == 0:
return x.unsqueeze(0).nonzero().unbind(1)
ret... | 2.34375 | 2 |
tests/cupyx_tests/scipy_tests/special_tests/test_basic.py | amanchhaparia/cupy | 0 | 12794850 | <filename>tests/cupyx_tests/scipy_tests/special_tests/test_basic.py<gh_stars>0
import math
import cupy
import numpy
import pytest
import scipy.special # NOQA
import cupyx.scipy.special
from cupy import testing
from cupy.testing import (
assert_array_equal,
assert_array_almost_equal,
)
from cupy.testing impor... | 1.890625 | 2 |