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 |
|---|---|---|---|---|---|---|
simple_parser.py | galaxyChen/dl4ir-webnav | 14 | 12785351 | <reponame>galaxyChen/dl4ir-webnav
'''
Simple parser that extracts a webpage's content and hyperlinks.
'''
import urllib2
import re
class Parser():
def __init__(self):
pass
def parse(self, url):
f = urllib2.urlopen(url)
text = f.read() # get page's contents.
#use re.fin... | 3.390625 | 3 |
tests/test_comment.py | muze-interviews/muze-lark-interview | 0 | 12785352 | <filename>tests/test_comment.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
from lark.lark import Lark
def DynamicEarleyLark(grammar, **kwargs):
return Lark(grammar, lexer='dynamic', parser='earley', **kwargs)
class TestParserComments(unittest.TestCase):
def make_test_parse... | 2.9375 | 3 |
test/cpu/test_flip.py | HiroakiMikami/benchmarks-of-deep-learning-libraries | 0 | 12785353 | <filename>test/cpu/test_flip.py
import json
import os
import subprocess
import tempfile
import pytest
import torch
@pytest.mark.parametrize("env", ["pytorch", "torchscript", "albumentations"])
def test_lcs(env: str) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
img = (
torch.arange(1... | 1.96875 | 2 |
raspagem/random/exemplo01.py | sslppractice/propython | 0 | 12785354 | import urllib.request
url = 'http://www.ifce.edu.br'
# Obter o conteúdo da página
pagina = urllib.request.urlopen(url)
texto1 = pagina.read().decode('utf-8')
# Outra forma de fazer a mesma coisa ..
import requests
page = requests.get(url)
texto2 = page.content.decode('utf-8')
# Verificamos que todas as linhas são i... | 3.34375 | 3 |
catalog/bindings/csw/title_1.py | NIVANorge/s-enda-playground | 0 | 12785355 | from dataclasses import dataclass, field
__NAMESPACE__ = "http://www.opengis.net/ows"
@dataclass
class Title1:
"""
Title of this resource, normally used for display to a human.
"""
class Meta:
name = "Title"
namespace = "http://www.opengis.net/ows"
value: str = field(
de... | 2.734375 | 3 |
test4~6.py | songgiwoo/python1 | 0 | 12785356 | # *을 1부터 5까지 출력 하세요.
a = "*"
#for i in range(1, 6, 1):
# for j in range(1, i+1, 1):
# print(a, end="")
# print()
#for i in range(5, 0, -1):
# for j in range(i-1, 0, -1):
# print(a, end="")
# print()
#line = int(input("Diamond 의 길이를 입력하세요(2~30) : "))
#for x in range(1, line * 2, 2):
# ... | 3.875 | 4 |
project/user/inputs.py | jasmine95dn/flask_best_worst_scaling | 0 | 12785357 | # -*- coding: utf-8 -*-
"""
Inputs
#################
*Module* ``project.user.inputs``
This module defines routes to manage input new inputs of projects from users.
"""
import re, boto3, string
from flask import render_template, redirect, url_for, Response, current_app
from flask_login import login_required, current... | 3.09375 | 3 |
openpnm/integrators/_scipy.py | lixuekai2001/OpenPNM | 2 | 12785358 | <gh_stars>1-10
from scipy.integrate import solve_ivp
from openpnm.integrators import Integrator
from openpnm.algorithms._solution import TransientSolution
__all__ = ['ScipyRK45']
class ScipyRK45(Integrator):
"""Brief description of 'ScipyRK45'"""
def __init__(self, atol=1e-6, rtol=1e-6, verbose=False, linso... | 2.890625 | 3 |
wk1_functions.py | RitRa/Programming-for-Data-Analysis | 0 | 12785359 | # <NAME> 21/09/18 week 1
# function for the Greatest Common Divisor
def gcd(a, b):
while b > 0:
a, b = b, a % b
return(a)
print(gcd(50, 20))
print(gcd(22, 143)) | 3.90625 | 4 |
splat/helpers/purgeUser.py | samskivert/splatd | 0 | 12785360 | # purgeUser.py vi:ts=4:sw=4:expandtab:
#
# LDAP User Purging Helper.
# Author:
# <NAME> <<EMAIL>>
#
# Copyright (c) 2006 Three Rings Design, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are... | 1.632813 | 2 |
python/physical/unit/statute.py | afrl-quantum/physical | 1 | 12785361 | from ..const import const
class statute(const):
def __init__(self,prefix,unit):
const.__init__(self,prefix + 'statute')
self.mile = 5280.0*unit.feet
self.miles = self.mile
self.mi = self.mile
self.league = 3.0*self.miles
self.leagues = self.league
| 2.921875 | 3 |
scripts/helm-version.py | mapster/k8ssandra | 0 | 12785362 | #!/usr/bin/env python3
import subprocess
from ruamel.yaml import YAML
import glob
import re
import argparse
class Semver:
def __init__(self, major: int, minor: int, patch: int):
self.major = major
self.minor = minor
self.patch = patch
def incr_major(self):
self.major = self.maj... | 2.40625 | 2 |
src/dugulib/sort.py | Peefy/CLRS_dugu_code-master | 3 | 12785363 | <filename>src/dugulib/sort.py
'''
排序算法集合
First
=====
冒泡排序 `O(n^2)` ok
鸡尾酒排序(双向冒泡排序) `O(n^2)`
插入排序 `O(n^2)` ok
桶排序 `O(n)` ok
计数排序 `O(n + k)` ok
合并排序 `O(nlgn)` ok
原地合并排序 `O(n^2)` ok
二叉排序树排序 `O(nlgn)` ok
鸽巢排序 `O(n+k)`
基数排序 `O(nk)` ok
Gnome排序 `O(n^2)`
图书馆排序 `O(nlgn)`
Se... | 3.25 | 3 |
src/sagemaker_huggingface_inference_toolkit/serving.py | oconnoat/sagemaker-huggingface-inference-toolkit | 46 | 12785364 | <reponame>oconnoat/sagemaker-huggingface-inference-toolkit
# Copyright 2021 The HuggingFace Team, Amazon.com, Inc. or its affiliates. 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... | 1.757813 | 2 |
0055.jump_game/solution.py | WZMJ/Algorithms | 5 | 12785365 | <filename>0055.jump_game/solution.py
from typing import List
class Solution:
def can_jump(self, nums: List[int]) -> bool:
last = len(nums) - 1
for i in range(len(nums) - 1, -1, -1):
if i + nums[i] >= last:
last = i
return last == 0
| 3.484375 | 3 |
board.py | adri326/ia41-project | 0 | 12785366 | <reponame>adri326/ia41-project<filename>board.py<gh_stars>0
class Board:
def __init__(self, width, height):
self.cars = []
self.width = width
self.height = height
self.exit_y = 2
# Finds and returns the car at (x, y). If there isn't any, returns None
def get_car(self, x, y):... | 3.640625 | 4 |
threedi_modelchecker/simulation_templates/laterals/extractor.py | nens/threedi-modelchecker | 0 | 12785367 | <filename>threedi_modelchecker/simulation_templates/laterals/extractor.py<gh_stars>0
from typing import List
from threedi_modelchecker.simulation_templates.exceptions import SchematisationError
from threedi_modelchecker.threedi_model.models import Lateral1d, Lateral2D
from sqlalchemy.orm import Query
from threedi_api_c... | 2.171875 | 2 |
tests/preprocessors/test_variables_preprocessor.py | swquinn/hon | 0 | 12785368 | <filename>tests/preprocessors/test_variables_preprocessor.py
import pytest
from hon.preprocessors.variables import (
VariablesPreprocessor
)
| 1.21875 | 1 |
alipay/aop/api/domain/SceneOrder.py | articuly/alipay-sdk-python-all | 0 | 12785369 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MallDiscountDetail import MallDiscountDetail
class SceneOrder(object):
def __init__(self):
self._buyer_user_id = None
self._discount... | 2.125 | 2 |
fetch/api.py | andrewhead/tutorial-data | 2 | 12785370 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
import logging
import time
import re
logger = logging.getLogger('data')
USER_AGENT = "<NAME> (for academic research) <<EMAIL>>"
default_requests_session = requests.Session()
default_requests_session.headers['User... | 2.9375 | 3 |
04/script.py | has-ctrl/advent-of-code-2021 | 0 | 12785371 | import numpy as np
with open("data.txt") as f:
draws = np.array([int(d) for d in f.readline().split(",")])
boards = np.array([[[int(n) for n in r.split()] for r in b.split("\n")] for b in f.read()[1:].split("\n\n")])
def bingo(data: np.ndarray, fill: int):
"""
Returns horizontal (rows) and vertical ... | 3.515625 | 4 |
manage.py | FuzzyTraderExercise/Backend | 0 | 12785372 | <reponame>FuzzyTraderExercise/Backend
from flask.cli import FlaskGroup
from src import create_app, db
app = create_app()
cli = FlaskGroup(create_app=create_app)
# Run Flask
if __name__ == '__main__':
cli() | 1.695313 | 2 |
backend/apps/projects/efficiency/urls.py | wuchaofan1654/tester | 0 | 12785373 | <reponame>wuchaofan1654/tester<filename>backend/apps/projects/efficiency/urls.py
# -*- coding: utf-8 -*-
"""
Create by sandy at 16:34 09/12/2021
Description: ToDo
"""
from django.urls import re_path
from rest_framework.routers import DefaultRouter
from apps.projects.efficiency.views import EfficiencyModelViewSet, Modu... | 1.914063 | 2 |
galaxy/main/migrations/0041_auto_20160207_2148.py | maxamillion/galaxy | 1 | 12785374 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0040_auto_20160206_0921'),
]
operations = [
migrations.AlterUniqueTogether(
name='repository',
... | 1.492188 | 1 |
big_screen/utils/re_format.py | 15653391491/black-broadcast-back-end | 0 | 12785375 | # 正则验证格式
DATE_FORMATTER_RE = "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}" # 时间
DATE_FORMATTER_RE_PHONE = "[0-9]{8}.[0-9]{6}" # 设备时间格式
LNGLAT_FORMATTER_RE_PHONE = "[0-9]+.[0-9]+-[0-9]+.[0-9]+" # 坐标格式
PHONEID_FORMATTER_RE = "[0-9]{15}"
IDCARD_FORMATTER_RE = "[0-9]{18}"
INT_FORMATTER_RE = "[0-9]+" # 是否为整数
I... | 1.671875 | 2 |
test/data/generic_acceptance_poe.py | hung135/pythoscope | 78 | 12785376 | from module import main
main()
| 1.257813 | 1 |
Sipros/Scripts/configure_subdb.py | xyz1396/Projects | 0 | 12785377 | <filename>Sipros/Scripts/configure_subdb.py
import getopt, sys
from urllib import urlencode
import cookielib, urllib2, os, re, copy, string, operator
def NewSearchName(currentLine, fileId) :
allInfo = currentLine.split("=")
sSearchName = allInfo[1]
sSearchName = sSearchName.strip()
if ((sSearchName ==... | 2.5625 | 3 |
myria/test/test_workers.py | BrandonHaynes/myria-python | 7 | 12785378 | <filename>myria/test/test_workers.py
from httmock import urlmatch, HTTMock
from json import dumps as jstr
import unittest
from myria import MyriaConnection
@urlmatch(netloc=r'localhost:12345')
def local_mock(url, request):
global query_counter
if url.path == '/workers':
return jstr({'1': 'localhost:12... | 2.53125 | 3 |
scripts/vim/bin/generate_kinds.py | n13l/OpenAAA | 10 | 12785379 | #!/usr/bin/env python2
#-*- coding: utf-8 -*-
import re
import sys
import os.path
import clang.cindex
# you can use this dictionary to map some kinds to better
# textual representation than just the number
mapping = {
1 : 't' , # CXCursor_UnexposedDecl (A declaration whose specific kind is not
# e... | 2.578125 | 3 |
slot/w/bow.py | qwewqa/dl | 0 | 12785380 | <filename>slot/w/bow.py
from slot import WeaponBase
from slot.w import agito_buffs
class HDT1_Valkyries_Blaze(WeaponBase):
ele = ['flame']
wt = 'bow'
att = 734
s3 = {
"dmg" : 3*3.16 ,
"sp" : 6750 ,
"startup" : 0.1 ,
"recovery" : 2.73 ,
... | 2.15625 | 2 |
automatic_design_program.py | joaocarvalhoopen/Design_Asymmetrical_Inverted_Schmitt_Trigger_Single_Supply_program | 1 | 12785381 | ##############################################################
# #
# Automatic design of an #
# Asymmetrical Inverted Schmitt-Trigger with Single Supply #
# for E24 resistors scale #
# ... | 2.40625 | 2 |
Python/IWannaBeTheGuy.py | Zardosh/code-forces-solutions | 0 | 12785382 | <filename>Python/IWannaBeTheGuy.py
n = int(input())
px = list(map(int, input().split()))
py = list(map(int, input().split()))
x = px[1:]
y = py[1:]
x.extend(y)
if len(set(x)) == n:
print('I become the guy.')
else:
print('Oh, my keyboard!') | 3.609375 | 4 |
Binary_conv.py | arunbutte/Python_Codes | 0 | 12785383 | def toBinary(n):
# Check if the number is Between 0 to 1 or Not
if(n >= 1 or n <= 0):
return "ERROR"
answer = ""
frac = 0.5
answer = answer + "."
# Setting a limit on length: 32 characters.
while(n > 0):
# Setting a limit on length: 32 character... | 3.828125 | 4 |
contrib/report_builders/json_report_builder.py | berndonline/flan | 3,711 | 12785384 | import json
from typing import Any, Dict, List
from contrib.descriptions import VulnDescriptionProvider
from contrib.internal_types import ScanResult
from contrib.report_builders import ReportBuilder
class JsonReportBuilder(ReportBuilder):
def __init__(self, description_provider: VulnDescriptionProvider):
... | 2.5 | 2 |
apps/network/tests/database/test_role.py | AmrMKayid/PyGrid | 0 | 12785385 | import pytest
from src.users.role import Role
from .presets.role import role_metrics
@pytest.mark.parametrize(
("name, can_edit_settings, can_create_users," "can_edit_roles, can_manage_roles"),
role_metrics,
)
def test_create_role_object(
name,
can_edit_settings,
can_create_users,
can_edit_ro... | 2.203125 | 2 |
app.py | JixunMoe/pi-cctv | 2 | 12785386 | # -*- coding: utf-8 -*-
import time, os, io, picamera, threading
from flask import Flask, request, session, url_for, redirect, render_template, g, Response, send_file
# configuration
DATABASE = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'minitwit.db')
DEBUG = False
SECRET_KEY = 'This is a very secrey k... | 2.375 | 2 |
setup.py | vnrvjietlab/vnrlab | 1 | 12785387 | <filename>setup.py
from setuptools import setup
setup(
name='vnrlab',
version='0.1.0',
packages=['vnrlab'],
license='MIT',
include_package_data=True,
package_data={
"": ['Data/*.bin']
},
install_requires=[
'pycryptodome'
],
) | 1.1875 | 1 |
quasimodo/tests/test_google_patterns.py | Aunsiels/CSK | 16 | 12785388 | <gh_stars>10-100
import unittest
from quasimodo.data_structures.subject import Subject
from quasimodo.patterns.pattern_google import PatternGoogle
class TestGooglePatterns(unittest.TestCase):
def test_get_str(self):
pattern = PatternGoogle("how are <SUBJS>")
self.assertEqual(pattern.to_str_subje... | 2.625 | 3 |
src/pyxsys/storage.py | lmmx/pyx-sys | 1 | 12785389 | import pickle
from pathlib import Path
from datetime import datetime as dt
def storage_timestamp(t=dt.now(), storage_dir=Path.home() / ".pyx_store", ext="p"):
"""
Return a timestamp now suitable to create a file path as:
yy/mm/dd/hh-mm-ss
By default under `~/.pyx_store/` (`storage_dir`) with ... | 2.96875 | 3 |
fugue_spark/__init__.py | gityow/fugue | 0 | 12785390 | <gh_stars>0
# flake8: noqa
from fugue.workflow import register_raw_df_type
from fugue_version import __version__
from pyspark.sql import DataFrame
from fugue_spark.dataframe import SparkDataFrame
from fugue_spark.execution_engine import SparkExecutionEngine
register_raw_df_type(DataFrame)
| 1.367188 | 1 |
lib/assembler/assemblerLibrary.py | DimitarYordanov17/jack-compiler | 5 | 12785391 | # A library file to include the machine language and dictionariy specifications of the Hack language. @DimitarYordanov17
class AssemblerLibrary:
'''
Main class to map the Hack syntax to internal machine language bytecode
'''
def get_jump(jump: str):
'''
Return bytecode of jump commands
'''
byt... | 3.171875 | 3 |
lib/eco/renderers.py | softdevteam/eco | 54 | 12785392 | # Copyright (c) 2013--2014 King's College London
# Created by the Software Development Team <http://soft-dev.org/>
#
# 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, inclu... | 1.703125 | 2 |
scraper/views.py | jazzify/newsify_back | 0 | 12785393 | <filename>scraper/views.py
from rest_framework import viewsets, mixins
from rest_framework.response import Response
from scraper.models import Post
from scraper.serializers import PostSerializer
class PostViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
queryset = Post.objects.... | 2.328125 | 2 |
abstractions.py | Koruption/CSV-Dataset-Generator | 0 | 12785394 | <gh_stars>0
from random_username.generate import generate_username
from random_address import real_random_address
from typing import Any, Dict, List, Tuple
from prettytable import PrettyTable
from datetime import timedelta
from datetime import datetime
from json import load
import random
import names
import uuid
import... | 3.09375 | 3 |
mysuper/users/forms.py | oreon/mysuper | 0 | 12785395 | <gh_stars>0
from django import forms
class ActorSearchForm(forms.Form):
name = forms.CharField(
required = False,
label='Search name or surname!',
widget=forms.TextInput(attrs={'placeholder': 'search here!'})
)
search_cap_ex... | 2.421875 | 2 |
teleband/submissions/api/views.py | JMU-CIME/CPR-Music-Backend | 2 | 12785396 | from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewS... | 1.914063 | 2 |
app/users/models.py | prapeller/blackemployer_api | 0 | 12785397 | <gh_stars>0
import datetime
import hashlib
from random import random
from django.conf import settings
from django.contrib import auth
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, AbstractUser
from django.core.mail import send_mail
from dj... | 2.25 | 2 |
app/main.py | Tehsurfer/image-history | 0 | 12785398 | import json
import base64
import requests
from flask import Flask, abort, jsonify, request
from app.config import Config
import os
import schedule
import threading
import time
from pathlib import Path
app = Flask(__name__)
# set environment variable
app.config["ENV"] = Config.DEPLOY_ENV
times = []
image_counter ... | 2.421875 | 2 |
plan/tests.py | 18892021125/NWU-ACM-MIS-backend | 5 | 12785399 | from django.test import TestCase, Client
from plan.models import Announcement
class AnnouncementTestCase(TestCase):
def setUp(self):
self.client = Client()
Announcement.objects.create(title='test1', content='test content1')
Announcement.objects.create(title='test2', content='test content2... | 2.390625 | 2 |
Desafios/Desafio 015 (Aluguel de carros).py | Kimberly07-Ernane/Pythondesafios | 0 | 12785400 | <filename>Desafios/Desafio 015 (Aluguel de carros).py
#Desafio15
# Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado
#e a quantidade de dias pelos quais ele foi alugado
#Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
dias=int(input('A quantida... | 3.890625 | 4 |
BGWpy/core/task.py | GkAntonius/BGWpy | 27 | 12785401 | <reponame>GkAntonius/BGWpy
from __future__ import print_function
import sys
import os
import warnings
import subprocess
import pickle
import contextlib
from ..config import default_mpi
from .util import exec_from_dir, last_lines_contain
from .runscript import RunScript
# Public
__all__ = ['Task', 'MPITask', 'IOTask']... | 2.25 | 2 |
rabbitai/db_engine_specs/hana.py | psbsgic/rabbitai | 0 | 12785402 | from datetime import datetime
from typing import Optional
from rabbitai.db_engine_specs.base import LimitMethod
from rabbitai.db_engine_specs.postgres import PostgresBaseEngineSpec
from rabbitai.utils import core as utils
class HanaEngineSpec(PostgresBaseEngineSpec):
engine = "hana"
engine_name = "SAP HANA"
... | 2.234375 | 2 |
oop12/lesson12h.py | ay1011/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | 0 | 12785403 | import math
import time
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
temp = math.sqrt(last)
for p in primes:
if p<temp:
if last % p == 0 :
break
else:
... | 3.59375 | 4 |
ros_compatibility/src/ros_compatibility/exceptions.py | SebastianHuch/ros-bridge | 314 | 12785404 | #!/usr/bin/env python
#
# Copyright (c) 2021 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
#
from ros_compatibility.core import get_ros_version
ROS_VERSION = get_ros_version()
if ROS_VERSION == 1:
import rospy
class... | 2.234375 | 2 |
src/irm_undirected.py | FreeTheOtter/BNP-Net | 0 | 12785405 | import igraph as ig
import numpy as np
from scipy.special import betaln
g = ig.Graph.Read_GML('karate.txt')
X = np.array(g.get_adjacency().data)
def irm(X, T, a, b, A, random_seed = 42):
N = len(X)
z = np.ones([N,1])
Z = []
np.random.seed(random_seed)
for t in range(T): # for T iterations
... | 2.140625 | 2 |
python-fastapi/api/app.py | duijf/boilerplates | 0 | 12785406 | from __future__ import annotations
import logging
import typing as t
from fastapi import APIRouter, FastAPI
from fastapi.param_functions import Depends
from starlette.responses import (
JSONResponse,
Response,
)
from api.config import get_config
from api.postgres import Connection, Postgres, connect_and_migr... | 2.328125 | 2 |
authors/apps/comments/signals.py | andela/ah-backend-summer | 1 | 12785407 | <reponame>andela/ah-backend-summer<gh_stars>1-10
from django.db.models.signals import (
post_save, m2m_changed as model_field_changed_signal)
from django.dispatch import receiver, Signal
from authors.apps.comments.models import Comment
# custom signal we shall send when a comment is published
# the rationale for... | 2.265625 | 2 |
rastervision/evaluation/object_detection_evaluation.py | ValRat/raster-vision | 4 | 12785408 | <gh_stars>1-10
from rastervision.evaluation import ClassEvaluationItem
from rastervision.evaluation import ClassificationEvaluation
class ObjectDetectionEvaluation(ClassificationEvaluation):
"""Evaluation for object detection.
Requires TensorFlow Object Detection to be available as it utilizes
some of it... | 2.46875 | 2 |
src/Solu9.py | wsdmakeup/codePractice | 0 | 12785409 | # -*- coding:utf-8 -*-
'''
Determine whether an integer is a palindrome. Do this without extra space.
'''
'''
不可以使用转换str的方法。
将自然对比转换为每次对比最左边和最右边,然后掐头去尾,就是数字除以100,
'''
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
re... | 3.734375 | 4 |
NetworkX/Example_2_Drawing.py | Farhad-UPC/Zero-Touch_Network_Slicing | 0 | 12785410 | import networkx as nx
import matplotlib.pyplot as plt
G=nx.cubical_graph() #Return the 3-regular Platonic Cubical graph.
plt.subplot(121) #subplot(nrows, ncols, index)
nx.draw(G) # default spring_layout
plt.subplot(122)
nx.draw(G, pos=nx.circular_layout(G), nodecolor='r', edge_color='b')
| 3.40625 | 3 |
airflow/migrations/versions/c2091a80ac70_create_scheduler_state_table.py | TriggerMail/incubator-airflow | 1 | 12785411 | <reponame>TriggerMail/incubator-airflow<gh_stars>1-10
#
# 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 a... | 1.421875 | 1 |
prajwal/__init__.py | Ishita-Sharma1/Prajwal | 1 | 12785412 | from flask import Flask
from flask import render_template
app = Flask(__name__)
# main routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/home')
def home():
return render_template('home.html') | 2.46875 | 2 |
algorithms/implementation/taum_and_bday.py | avenet/hackerrank | 0 | 12785413 | <gh_stars>0
t = int(
input().strip()
)
for a0 in range(t):
b, w = input().strip().split(' ')
b, w = [int(b),int(w)]
x, y, z = input().strip().split(' ')
x, y, z = int(x), int(y), int(z)
min_black_price = min(b*x, b*(y+z))
min_white_price = min(w*y, w*(x+z))
print(min_black_price + mi... | 2.96875 | 3 |
AbstractSearchEngine/utils/stemmer.py | canuse/arXiv_explorer | 0 | 12785414 | <gh_stars>0
from Stemmer import Stemmer
from AbstractSearchEngine.db.StemHistory import update_stem_history, query_origin_word
from functools import lru_cache
stemmer = Stemmer('porter')
def stem(term, record=False):
"""
stem word
"""
stemmed_word = stemmer.stemWord(term)
if record:
updat... | 2.453125 | 2 |
api.py | ignaloidas/savetheplanet-backend | 0 | 12785415 | <filename>api.py<gh_stars>0
from datetime import datetime
import pytz
from firebase_admin import auth
from flask import Blueprint, abort, jsonify, request
from flask_login import login_user
from app import db
from models import User, FirebaseSubscription
from utils import generate_random_string, require_authenticatio... | 2.515625 | 3 |
data_processing/study_constants.py | calico/catnap | 0 | 12785416 | import datetime
END_DATE = datetime.date(2019, 4, 25)
STATE2DESCRIPTOR = {0: 'REST', 1: 'SLEEP', 2: 'ACTIVE', 3: 'RUN', 4: 'EAT&DRINK', 5: 'EAT'}
DAY_NIGHTS = ['day', 'night']
STATES = list(STATE2DESCRIPTOR.values())
STATE_AGG_BASE_FEATURES = ['VO2', 'VCO2', 'VH2O', 'KCal_hr', 'RQ', 'Food', 'PedMeters', 'AllMeters']
... | 2.0625 | 2 |
setup.py | stuwilkins/antplus | 1 | 12785417 | import os
import re
import sys
import platform
import subprocess
import versioneer
from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion
cpus = os.cpu_count()
here = os.path.abspath(os.path.dirname(__file__))
with open(os.... | 2 | 2 |
examples/auth/app.py | Alma-field/twitcaspy | 0 | 12785418 | # Twitcaspy
# Copyright 2021 Alma-field
# See LICENSE for details.
from twitcaspy import API, AppAuthHandler
# The client id and/or secret can be found on your application's Details page
# located at select app in https://twitcasting.tv/developer.php
# (in "details" tab)
CLIENT_ID = ''
CLIENT_SECRET = ''
auth = AppA... | 2.65625 | 3 |
libs/http.py | BreakUnrealGod/TanTan | 1 | 12785419 | from django.conf import settings
from django.http import JsonResponse
from common import errors
def render_json(code=errors.OK, data=None):
"""
自定义 json 输出
:param code:
:param data:
:return:
"""
result = {
'code': code
}
if data:
result['data'] = data
if set... | 2.203125 | 2 |
src/GTV/Gtv.py | ErnstKapp/postchain-client | 0 | 12785420 | """
This class contains the Merkleroot-Hash which will be used
for chaining blocks together
"""
class GTV:
def __init__(self):
merkleRoot = bytearray(0)
| 1.757813 | 2 |
utils.py | jiahuei/bottom-up-attention-tf | 0 | 12785421 | <reponame>jiahuei/bottom-up-attention-tf<filename>utils.py
import errno
import os
import numpy as np
from PIL import Image
EPS = 1e-7
def assert_eq(real, expected):
assert real == expected, '%s (true) vs %s (expected)' % (real, expected)
def assert_array_eq(real, expected):
assert (np.abs(real - expected) ... | 2.34375 | 2 |
train.py | oumayb/NeighConsensus | 1 | 12785422 | import sys
sys.path.append('./model')
import argparse
import torch
import numpy as np
from model.model import NCNet
import torchvision.transforms as transforms
from dataloader import TrainLoader, ValLoader
from loss import WeakLoss
import torch.optim as optim
import json
import os
## Parameters
parser = argparse.... | 2.078125 | 2 |
lang/Python/loops-for-1.py | ethansaxenian/RosettaDecode | 0 | 12785423 | import sys
for i in range(5):
for j in range(i+1):
sys.stdout.write("*")
print()
| 2.828125 | 3 |
run_concat.py | folguinch/GoContinuum | 1 | 12785424 | <reponame>folguinch/GoContinuum
#!casa -c
import argparse
def main():
# Command line options
parser = argparse.ArgumentParser()
parser.add_argument('-c', nargs=1,
help='Casa parameter.')
parser.add_argument('concatvis', nargs=1, type=str,
help='Concatenated ms name')
parse... | 2.453125 | 2 |
Spark_AccessCodeLog_Sort.py | MLSTS/SparkRDD | 0 | 12785425 | <reponame>MLSTS/SparkRDD
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext
lines = sc.textFile("/home/student/CSS333/dataset/accesslog.csv",4)
codes = lines.map(lambda str: (str.split(",")[7],1))
... | 3.078125 | 3 |
src/abaqus/Interaction/IncidentWaveState.py | Haiiliin/PyAbaqus | 7 | 12785426 | from abaqusConstants import *
from .InteractionState import InteractionState
class IncidentWaveState(InteractionState):
"""The IncidentWaveState object stores the propagating data of an IncidentWave object in a
step. One instance of this object is created internally by the IncidentWave object for
each st... | 2.609375 | 3 |
aiohttp_swagger3/swagger_route.py | grandmetric/aiohttp-swagger3 | 0 | 12785427 | import cgi
import json
from types import FunctionType
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, cast
import attr
from aiohttp import web
from .context import COMPONENTS
from .swagger import Swagger
from .validators import MISSING, Validator, ValidatorError, schema_to_validator, securit... | 2.1875 | 2 |
big_screen/redisOpration/AllOpration.py | 15653391491/black-broadcast-back-end | 0 | 12785428 | from django_redis import get_redis_connection
import json
from .BaseOpration import BaseOpration
from big_screen.utils import tools as t
from big_screen.serialization.allSerialization import serMobile
from big_screen.utils import re_format as f
class defaultOp(BaseOpration):
def __init__(self):
BaseOprat... | 2.109375 | 2 |
mapnik-tiler.py | eyeNsky/mapnik-tiler | 0 | 12785429 | #!/usr/bin/env python
'''
Based on:
https://trac.openstreetmap.org/browser/applications/rendering/mapnik/generate_tiles_multiprocess.py
With snippet from:
http://www.klokan.cz/projects/gdal2tiles/gdal2tiles.py
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person... | 1.789063 | 2 |
sciencebeam_gym/preprocess/blockify_annotations.py | elifesciences/sciencebeam-gym | 25 | 12785430 | import logging
from collections import deque
from abc import ABC, abstractmethod
import math
from lxml import etree
from pyqtree import Index as PqtreeIndex
from PIL import Image, ImageDraw, ImageColor
from sciencebeam_gym.structured_document.svg import (
SVG_NSMAP,
SVG_DOC,
SVG_RECT,
)
DEFAULT_NEARBY_TO... | 2.515625 | 3 |
closure/2.py | janusnic/py-21v | 0 | 12785431 | # -*- coding:utf-8 -*-
def attribution(name):
return lambda x: x + ' -- ' + name
pp = attribution('John')
print pp('Dinner is in the fridge') | 3.296875 | 3 |
time_calculator.py | trsilva32/TimeCalculator | 0 | 12785432 | import datetime
def add_time(start, duration, weekday_name = ' '):
start = datetime.datetime.strptime(start,'%I:%M %p')
h_duration,m_duration = duration.split(':')
t_duration = int(h_duration)*60 + int(m_duration)
calc_time = start + datetime.timedelta(minutes=int(t_duration))
day = calc_time.day
... | 3.4375 | 3 |
home/migrations/0001_initial.py | MarkJaroski/aho-dev-dct | 0 | 12785433 | <reponame>MarkJaroski/aho-dev-dct
# Generated by Django 2.1.2 on 2020-07-23 04:37
from django.db import migrations, models
import django.db.models.deletion
import parler.fields
import parler.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migr... | 1.632813 | 2 |
certbot-dns-dnspod/certbot_dns_dnspod/dns_dnspod_test.py | realkcn/certbot | 0 | 12785434 | <reponame>realkcn/certbot
"""Tests for certbot_dns_dnspod.dns_dnspod."""
import os
import unittest
import mock
from certbot import errors
from certbot.plugins import dns_test_common
from certbot.plugins.dns_test_common import DOMAIN
from certbot.tests import util as test_util
ID = 1201
TOKEN = 'a-token'
class Auth... | 2.234375 | 2 |
pdm/retriever.py | trollfist20/python-download-manager | 0 | 12785435 | import time
from pdm.constants import BUFFER
from urllib.request import (
build_opener,
urlopen,
Request
)
from http.client import HTTPResponse, HTTPMessage
from threading import Thread, Event
from pdm.utils import get_filename
from concurrent.futures import Future
from pdm.hooker import ProgressDownloadHoo... | 2.6875 | 3 |
analyzer.py | Chibbluffy/TwitterKeywordPerceptionAnalysis | 0 | 12785436 | <filename>analyzer.py
import sys
import pandas as pd
import json
df_list = []
with open(sys.argv[1], 'r') as f:
for line in f:
loaded = json.loads(line)
label = loaded["label"]
text = loaded["text"]
df_list.append({'text': text, 'label': label})
df = pd.DataFrame(df_list)
from skle... | 2.859375 | 3 |
clipper-cli/src/test/resources/lubm-ex-20/execQuery.py | ghxiao/clipper | 5 | 12785437 | import os
univs = 100
ndeparts = 15
q = 2
shcmd = r'''
dlv -filter=ans
'''
#shcmd += "q" + q + ".dlv "
#for univ in range(univs):
shcmd += '''
q2.dlv LUBM-ex-20.owl.dl University0_0.owl.dl University0_1.owl.dl University0_2.owl.dl \
University0_3.owl.dl University0_4.owl.dl University0_5.owl.dl University0_6.owl... | 1.570313 | 2 |
menu_definitions.py | mheydasch/graph_app | 0 | 12785438 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 12:06:05 2019
@author: max
Holds the menu definition, such as buttons and dropdown menus
"""
import dash_core_components as dcc
import dash_html_components as html
import dash_table
#%% data
def Upload_data():
return dcc.Uplo... | 1.953125 | 2 |
pymarkdown/plugins/rule_md_004.py | scop/pymarkdown | 0 | 12785439 | <filename>pymarkdown/plugins/rule_md_004.py
"""
Module to implement a plugin that looks for hard tabs in the files.
"""
from pymarkdown.plugin_manager import Plugin, PluginDetails
class RuleMd004(Plugin):
"""
Class to implement a plugin that looks for hard tabs in the files.
"""
__consistent_style = ... | 2.65625 | 3 |
tests/unit/cartography/intel/gsuite/test_api.py | sckevmit/cartography | 2,322 | 12785440 | from unittest import mock
from unittest.mock import patch
from cartography.intel.gsuite import api
def test_get_all_users():
client = mock.MagicMock()
raw_request_1 = mock.MagicMock()
raw_request_2 = mock.MagicMock()
user1 = {'primaryEmail': '<EMAIL>'}
user2 = {'primaryEmail': '<EMAIL>'}
use... | 2.640625 | 3 |
apple/AppleOAuth2.py | rajeshwariC/WeVoteServer | 0 | 12785441 | <reponame>rajeshwariC/WeVoteServer
import jwt
import requests
from config.base import get_environment_variable
from datetime import timedelta
from django.utils import timezone
from social_core.backends.oauth import BaseOAuth2
from social_core.utils import handle_http_errors
class AppleOAuth2(BaseOAuth2):
"""apple... | 2.1875 | 2 |
pyschism/outputs/stations.py | pmav99/pyschism | 17 | 12785442 | <reponame>pmav99/pyschism<gh_stars>10-100
from datetime import datetime, timezone, timedelta
import pathlib
from typing import Union, List
import warnings
import f90nml
import matplotlib.pyplot as plt
import numpy as np
from pyschism.utils.coops import CoopsDataCollector
from pyschism.enums import StationOutputIndex,... | 2.5 | 2 |
notifications/notifications.py | uktrade/directory-api | 2 | 12785443 | from django.conf import settings
from notifications import constants, email, helpers
def verification_code_not_given():
verification_code_not_given_first_reminder()
verification_code_not_given_seconds_reminder()
def verification_code_not_given_first_reminder():
days_ago = settings.VERIFICATION_CODE_NOT... | 2.046875 | 2 |
SDKs/Aspose.Imaging-Cloud-SDK-for-Python/asposeimagingcloud/models/JpegProperties.py | naeem244/Aspose.Imaging-for-Cloud | 0 | 12785444 | <reponame>naeem244/Aspose.Imaging-for-Cloud
#!/usr/bin/env python
class JpegProperties(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is att... | 2.140625 | 2 |
ffa/webapp/api.py | kschweizer/fresnofieldarchers | 0 | 12785445 | <gh_stars>0
from rest_framework import permissions, viewsets
from rest_framework.permissions import BasePermission, IsAdminUser, SAFE_METHODS
from django.http import HttpResponse
from django.core import serializers
from webapp.models import Blogpost, Image, Album, Event, About, PinnedEvent
from knox.auth import TokenAu... | 2.046875 | 2 |
data/transforms/build.py | moranxiachong/PersonReID-VAAL | 2 | 12785446 | # encoding: utf-8
"""
@author: liaoxingyu
@contact: <EMAIL>
"""
import torchvision.transforms as T
import random
import numpy as np
import PIL
from .transforms import RandomErasing
class AddGaussianNoise(object):
def __call__(self, img):
std = random.uniform(0, 1.0)
if std > 0.5:
retu... | 2.375 | 2 |
tutorial/2 - Design Optimization/2 - Wing Drag Minimization, with Aerostructures.py | askprash/AeroSandbox | 0 | 12785447 | <reponame>askprash/AeroSandbox
"""
In our last example, we had a cautionary tale about using bad models and assumptions, and how you can easily find
yourself with nonsensical solutions if you throw together models without thinking about how they can be exploited.
Let's try doing another wing drag minimization problem... | 2.75 | 3 |
python_basics/string_manipulation.py | Cristobalz2/pythonLearning | 0 | 12785448 | # print("var=10\nif var > 10:\vprint('la casa esta vacia')\nfin del programa" )
def mix_up(a, b):
# +++your code here+++\
# a[0] = b[0]
strA = a.replace(a[:2],b[:2])
strB = b.replace(b[:2],a[:2])
return strA + " " + strB
a= 'mix'
b= 'pod'
print(mix_up(a,b))
def fix_start(s):
# +++your code here+++
... | 3.65625 | 4 |
main.py | MarcelloEdocia/cellphone_purchase | 0 | 12785449 | import tkinter
import sys
import time
import json
from config import Config
from login_page import LoginPage
from menu import MenuPage
from register import Register
from admin import Admin
from purchases import Purchase
from add_purchase import AddPurchase
class Window(tkinter.Tk):
def __init__(se... | 2.625 | 3 |
modules/scripts/align_getMapStats.py | baigal628/CHIPS | 10 | 12785450 | <gh_stars>1-10
#!/usr/bin/env python
"""Script to collect the mapping statistics from across all samples.
outputs to stdout:
Sample,Mapped,Total,Percentage
"""
import os
import sys
from optparse import OptionParser
def main():
usage = "USAGE: %prog -f [FPKM FILE_1] -f [FPKM FILE_2] ...-f [FPKM FILE_N]"
optpa... | 2.34375 | 2 |