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 |
|---|---|---|---|---|---|---|
src/help/text/chsh.py | Hamzah-z/user-scripts | 1 | 44200 | <filename>src/help/text/chsh.py
"""chfn help text"""
CHSH = dict(
text="""chsh changes your "shell" on Redbrick.
** WARNING - Do not use this command if you are unsure
** of what you are doing! :-)
A "Shell" is the style of command line environment on RedBrick.
It is essentially, the 'prompt' and set of commands... | 2.625 | 3 |
Cluster/k-means_tutorial.py | MarkWh1te/MLAlgorithms | 0 | 44201 | <gh_stars>0
# -*- coding: utf-8 -*-
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
def initialize_clusters(points, k):
"""Initializes clusters as k randomly selected points from points."""
return points[np.random.randint(points.shape[0], size=k)]
... | 3.453125 | 3 |
test/test_server.py | gomezportillo/apolo | 1 | 44202 | import unittest
import requests
import json
class TestServer(unittest.TestCase):
@classmethod
def setUpClass(self):
self.port = 80
self.URL_BASE = 'http://localhost:{}'.format( self.port )
self.URL_USERS = self.URL_BASE + '/rest/users'
self.URL_USERS_ALL = self.URL_USE... | 3.015625 | 3 |
modulo_7/src/4_diferencia_antipodas.py | SRendonn/analisis-diseno-algoritmos | 0 | 44203 | def partition(lista: list[int], low: int, high: int) -> int:
i = low
pivot = lista[high]
for j in range(low, high):
if lista[j] <= pivot:
# swap
lista[i], lista[j] = lista[j], lista[i]
i += 1
lista[i], lista[high] = lista[high], lista[i]
return i
def f... | 3.109375 | 3 |
avx512-cnnopt/TileLoopGenerator/solver/main.py | Mastli/ASPLOS_artifact | 7 | 44204 | from SymbolPool import *
from Tensor import *
from LoopStacker import *
from Test import *
def main():
test_modgen()
if __name__ == "__main__":
main() | 1.226563 | 1 |
step3_upload_to_s3.py | OpenKBC/deg-pipeline-batch-image | 0 | 44205 | __author__ = "<NAME>"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
"""
Description: This is batch job for uploading result file to S3.
"""
import os
import argparse
from libraries.botoClass import botoHandler
## argparse setting
parser = argparse.ArgumentParser(prog='step3_upload_to_s3.py')
... | 2.109375 | 2 |
algorithms/2.1_add_two_numbers.py | ycpeng7/leetcode_challenges | 0 | 44206 | #-------------------------------------------------------------------------------
# Add Two Numbers
#-------------------------------------------------------------------------------
# By <NAME>
# https://leetcode.com/problems/add-two-numbers/
# Completed 12/3/20
#-------------------------------------------------------... | 3.109375 | 3 |
backend/api/viewsets/vehicle.py | amichard/zeva | 0 | 44207 | <reponame>amichard/zeva
from rest_framework import mixins, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from api.models.model_year import ModelYear
from api.models.vehicle import Vehicle, VehicleDefinitionStatuses
fro... | 2.015625 | 2 |
timelight_ai_python_api_client/models/__init__.py | timelight-ai/python-api-client | 0 | 44208 | # coding: utf-8
# flake8: noqa
"""
timelight
This is the timelight api. # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from timelight_ai_python_api_client.mo... | 1.085938 | 1 |
Chapter03/plot_convolution.py | arifmudi/Advanced-Deep-Learning-with-Python | 107 | 44209 | import matplotlib.pyplot as plt
import numpy as np
def plot_convolution(f, g):
fig, (ax1, ax2, ax3) = plt.subplots(3, 1)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
ax1.plot(f, color='blue', label='f')
ax1.legend()
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.plot(g, color=... | 3.09375 | 3 |
materialist/commonconstants.py | srungta/i-materialist | 0 | 44210 | DATA_FOLDER = './materialist/data'
TEST_FOLDER = './materialist/data/test'
TRAIN_FOLDER = './materialist/data/train'
VALIDATION_FOLDER = './materialist/data/validation'
TEST_FILE = './materialist/data/test.json'
TRAIN_FILE = './materialist/data/train.json'
VALIDATION_FILE = './materialist/data/validation.json'
TEST_... | 1.296875 | 1 |
vision/src/VisionROS/dialogConfigROS.py | victoriapc/HockusPockus | 0 | 44211 | import threading
import copy
import time
from VisionROS.ROS_CONSTANTS import *
from VisionUtils.TableDimensions import TableDimensions
try:
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Point
from std_msgs.msg import Int32... | 2.203125 | 2 |
todo/bucketlist/tests/test_models.py | NdagiStanley/not-by-might | 1 | 44212 | <reponame>NdagiStanley/not-by-might<filename>todo/bucketlist/tests/test_models.py<gh_stars>1-10
import datetime
from django.test import TestCase
from django.core.urlresolvers import reverse
from ..models import Bucketlist, BucketlistItem, User
class UserModelTest(TestCase):
"""Test User Model"""
def setUp(se... | 2.609375 | 3 |
skyportal/facility_apis/__init__.py | steveschulze/skyportal | 0 | 44213 | from .interface import FollowUpAPI, Listener
from .sedm import SEDMAPI, SEDMListener
from .lt import IOOAPI, IOIAPI, SPRATAPI
| 1.03125 | 1 |
etsy_convos/convos/filters.py | jessehon/etsy-convos | 2 | 44214 | <filename>etsy_convos/convos/filters.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from rest_framework import filters
class ActiveForUserFilter(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.active_for(request.user)
class ThreadFolderFilter(filters.BaseFilterBac... | 2 | 2 |
rocAL/rocAL_pybind/example/tf_mnistTrainingExample/tf_mnist_classification_rali.py | asalmanp/MIVisionX | 153 | 44215 |
from __future__ import print_function
from amd.rali.plugin.tf import RALIIterator
from amd.rali.pipeline import Pipeline
import amd.rali.ops as ops
import amd.rali.types as types
import sys
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
############################### HYPER PARAMETERS F... | 2.484375 | 2 |
src/cnpj/seek/__init__.py | pedromxavier/cnpj | 1 | 44216 | <gh_stars>1-10
from .seek import seek | 1.179688 | 1 |
youtube_mp3/main.py | ewenchou/youtube-mp3 | 0 | 44217 | # coding=utf8
# Main executable for download
import sys, traceback
import pprint
from youtube_mp3 import YouTubeMP3
if __name__ == '__main__':
if len(sys.argv) != 2:
raise ValueError("Missing URL argument")
yt = YouTubeMP3()
url = sys.argv[1]
data_list = yt.download(url)
print(data_list)
... | 3.1875 | 3 |
tests/test_backup.py | RSabet/rolling-backup | 0 | 44218 | import random
import pytest
from rolling_backup import backup
CONTENT = "Hello"
def create_backups(image_file, num: int):
for i in range(num):
image_file.write(f"{CONTENT} - {i}")
assert backup(str(image_file), num_to_keep=num)
d = image_file.dirpath()
should = d / f... | 2.453125 | 2 |
post/views.py | agiledesign2/drf-blog-post | 0 | 44219 | from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from .models import Post, Category
from taggit.models import Tag
from .forms import AddPostForm
#from .validator import group_required
# complex lookups (for searching)
from django.db.models import Q
from django.urls ... | 1.984375 | 2 |
examples/classifier_compression/main.py | wanshanhsieh/distiller | 0 | 44220 | <filename>examples/classifier_compression/main.py<gh_stars>0
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torchvision
import torchvision.transforms as tran... | 2.359375 | 2 |
src/python/tests/unittests/test_controller/test_scan/test_remote_scanner.py | annihilatethee/seedsync | 0 | 44221 | <gh_stars>0
# Copyright 2017, <NAME>, All rights reserved.
import unittest
import logging
import sys
from unittest.mock import patch, call, ANY
import tempfile
import os
import pickle
import shutil
from controller.scan import RemoteScanner
from ssh import SshcpError
from common import AppError
from common import Loca... | 2.359375 | 2 |
python/snippet_utils.py | emory-irlab/Mouse2Gaze | 0 | 44222 | <reponame>emory-irlab/Mouse2Gaze<gh_stars>0
# -- Writtenb by dsavenk
import psycopg2
from os import path
import re
import urllib2
#import emu_load_snippets
from BeautifulSoup import BeautifulSoup
#from html_resource_save import resource_extractor
import urllib
import httplib
import socket
#prefix = emu_load_snippets.p... | 2.484375 | 2 |
nertivia/bot.py | Nertivia-PY/Nertivia.py | 2 | 44223 | <reponame>Nertivia-PY/Nertivia.py<filename>nertivia/bot.py
import json
import logging
import nertivia.events
import websockets
import asyncio
class Bot(object):
def __init__(self,
logger: logging.Logger = False,
request_timeout=5,
max_retries=3,
... | 2.3125 | 2 |
vedastr_cstr/vedastr/models/heads/transformer_head.py | bsm8734/formula-image-latex-recognition | 13 | 44224 | import logging
import math
import torch
import torch.nn as nn
from vedastr.models.bodies import build_sequence_decoder
from vedastr.models.utils import build_torch_nn
from vedastr.models.weight_init import init_weights
from .registry import HEADS
logger = logging.getLogger()
@HEADS.register_module
class Transforme... | 2.171875 | 2 |
a5dev/transfersh.py | ankitsainidev/a5dev | 0 | 44225 | <filename>a5dev/transfersh.py
import os
import sys
import zipfile
import requests
import datetime
import wget
def get_date_in_two_weeks():
"""
get maximum date of storage for file
:return: date in two weeks
"""
today = datetime.datetime.today()
date_in_two_weeks = today + datetime.timedelta(d... | 3.28125 | 3 |
utils/isa.py | skilkis/GENX | 2 | 44226 | from constants import Constants
import numpy as np
# TODO finish implementing all regions of the atmosphere
class ISA(Constants):
def __init__(self, altitude=0):
""" Calculates International Standard Atmosphere properties for the specified geo-potential altitude
:param float altitude: Geo-potent... | 3.171875 | 3 |
hello-world/hello_world/__init__.py | pyodide/pyodide-examples | 1 | 44227 | print("Initializing hello world module")
from .some_funcs import say_hello, repeat_string
__all__ = ["say_hello", "repeat_string"]
| 1.851563 | 2 |
IEX_29id/mda/__init__.py | kellyjelly0904/macros_29id | 0 | 44228 | <gh_stars>0
# This file is here to make this folder a package
| 1.28125 | 1 |
d2matchdb.py | andrewlin16/d2matchdb | 1 | 44229 | <filename>d2matchdb.py
# Dota 2 match scraper/local DB
# WebAPI info: http://dev.dota2.com/showthread.php?t=47115
# API details (may be old?): https://wiki.teamfortress.com/wiki/WebAPI#Dota_2
# imports
from functools import reduce
import d2mdb_const as const
import json
import os.path
import random
import requests
imp... | 2.75 | 3 |
Online_Search_Module.py | LuJunru/My_QA_Robot | 19 | 44230 | <reponame>LuJunru/My_QA_Robot
# -*- coding: utf-8 -*-
# @Author : Junru_Lu
# @File : Online_Search_Module.py
# @Software: PyCharm
# @Environment : Python 3.6+
# 网页和服务请求相关包
from bs4 import BeautifulSoup
from urllib.parse import quote
import requests
# 基础包
import re
import os
# 编码相关包
import importlib, sys
importli... | 2.875 | 3 |
invoicer/_units/forms.py | mtik00/invoicer | 0 | 44231 | <filename>invoicer/_units/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, FloatField
from wtforms.validators import DataRequired
class UnitForm(FlaskForm):
description = StringField(u'Description', validators=[DataRequired()])
unit_price = FloatField(u'Unit Price', validators=[DataRe... | 2.578125 | 3 |
django_cbtools/sync_gateway.py | smarttradeapp/django_couchbase | 6 | 44232 | import json
import logging
import requests
from requests.auth import HTTPBasicAuth
from django.conf import settings
logger = logging.getLogger(__name__)
class SyncGatewayException(Exception):
pass
class SyncGatewayConflict(SyncGatewayException):
pass
class SyncGateway(object):
@staticmethod
def ... | 2.21875 | 2 |
data/test/python/68d4db48cd7efced20080ca32fe6dc3a1aa6264dfiles.py | harshp8l/deep-learning-lang-detection | 84 | 44233 | from django.db import models
__all__ = ('PostSaveImageField',)
class PostSaveImageField(models.ImageField):
def __init__(self, *args, **kwargs):
kwargs['null'] = True
kwargs['blank'] = True
super(PostSaveImageField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls,... | 2.140625 | 2 |
tests/test_casefold_migration.py | clmnin/sydent | 220 | 44234 | <gh_stars>100-1000
import json
import os.path
from unittest.mock import patch
from twisted.trial import unittest
from scripts.casefold_db import (
calculate_lookup_hash,
update_global_associations,
update_local_associations,
)
from sydent.util import json_decoder
from sydent.util.emailutils import sendEma... | 2.125 | 2 |
app/services/interface.py | izconcept/Turnt | 4 | 44235 | import time
import pyautogui
def typer(command):
pyautogui.typewrite(command)
pyautogui.typewrite('\n')
def open_valve(axis, step):
typer("G91G0" + axis + "-" + str(step))
def close_valve(axis, step):
typer("G91G0" + axis + str(step))
def give_me_some_white_bottle(duration):
if duration == 0:... | 2.765625 | 3 |
test_soundcard.py | bastibe/pysound | 490 | 44236 | import sys
import soundcard
import numpy
import pytest
skip_if_not_linux = pytest.mark.skipif(sys.platform != 'linux', reason='Only implemented for PulseAudio so far')
ones = numpy.ones(1024)
signal = numpy.concatenate([[ones], [-ones]]).T
def test_speakers():
for speaker in soundcard.all_speakers():
ass... | 2.265625 | 2 |
migrations/versions/c0e8d68e84fa_added_anomaly_config_to_kpi.py | eltociear/chaos_genius | 320 | 44237 | <gh_stars>100-1000
"""added anomaly config to kpi
Revision ID: c0e8d68e84fa
Revises: <PASSWORD>
Create Date: 2021-09-02 09:08:21.174195
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c0e8d68e84fa'
down_revision = '<PASSWORD>0d4ab3bc9'
branch_labels = None
dep... | 1.234375 | 1 |
puzzler/puzzles/polyominoes45.py | tiwo/puzzler | 0 | 44238 | <reponame>tiwo/puzzler
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
# Author: <NAME> <<EMAIL>>
# Copyright: (C) 1998-2015 by <NAME>
# License: GPL 2 (see __init__.py)
"""
Concrete pentomino & tetromino (polyominoes of order 4 & 5) puzzles.
"""
from puzzler.puzzles.polyominoes import Polyominoes45, OneSidedPo... | 2.84375 | 3 |
panacea/panacea_app/urls.py | Panacea-4-U/Panacea | 0 | 44239 | <filename>panacea/panacea_app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home,name='web-home'),
path('patient/<int:pk>/',views.pat_home,name='pat-home'),
path('landing', views.landingpage,name='landing-page'),
path('login-register', views.login_register,name... | 1.804688 | 2 |
wxPython/wxGlade-0.9.1/tests/testsupport_new.py | DarkShadow4/python | 0 | 44240 |
"""
@copyright: 2012-2016 <NAME> (as file __init__.py)
@copyright: 2016-2018 <NAME>
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import os, sys
sys.path.insert(1, os.path.dirname(sys.path[0]))
import errno, fnmatch, glob, shutil, re
import unittest, difflib, logging, imp
import gettext... | 2.21875 | 2 |
cherrypicker/cli.py | Spacerat/cherrypicker | 0 | 44241 | #! /usr/bin/env python3
import sh
import click
import re
def real_git(*args, **kwargs):
mock_git(*args, **kwargs)
return sh.git(*args, **kwargs)
def mock_git(*args, **kwargs):
click.echo(sh.git.bake(*args, **kwargs), err=True)
return ""
def branch_exists(name):
try:
get_commit_hash(na... | 2.6875 | 3 |
space_manager/branches/migrations/0011_branch_minimap_img.py | yoojat/Space-Manager | 0 | 44242 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-03 14:34
from __future__ import unicode_literals
from django.db import migrations, models
import space_manager.branches.models
class Migration(migrations.Migration):
dependencies = [
('branches', '0010_branch_lounge_img_cabinet'),
]
... | 1.460938 | 1 |
Source/sobrevivente.py | wesferr/Zombicide | 1 | 44243 | <reponame>wesferr/Zombicide
# Copyright (c) 2018 by <NAME>. All Rights Reserved.
from pygame import *
from pygame.locals import *
from spritesGame import *
from math import *
class Sobrevivente(object):
def __init__(self, area, nome, imgPlayer = None):
self.area = area
self.grid = self.area.grid
... | 3.015625 | 3 |
cv/migrations/0003_auto_20200826_1142.py | Shuhao99/2020Bridging-Coursework | 0 | 44244 | # Generated by Django 2.2.15 on 2020-08-26 03:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cv', '0002_experience_experience_name'),
]
operations = [
migrations.AlterField(
model_name='experience',
name='exp... | 1.53125 | 2 |
foo.py/bar.py | conradstorz/Sunset-Village-River-Bot | 0 | 44245 | <filename>foo.py/bar.py
print(f'This is the python code file bar.py and my name currently is:{__name__}')
if __name__ == 'bar':
print(f'I was imported as a module.')
print(f'bar.py __file__ variable:{__file__}')
print('If the slashes in the file path lean to the right then I am __main__')
| 3.40625 | 3 |
otter/json_schema/__init__.py | codebyravi/otter | 20 | 44246 | <filename>otter/json_schema/__init__.py
"""
Draft 3 JSON schemas (http://tools.ietf.org/html/draft-zyp-json-schema-03)
of data that will be transmitted to and from otter.
"""
import functools
from jsonschema import Draft3Validator, validate, FormatChecker
# This is there since later modules need to add specific forma... | 1.898438 | 2 |
wikidump/wikidump/__init__.py | foxsquad/wikidump | 0 | 44247 | """Wikidump reader and processor module.
"""
import os
with open(os.path.join(
os.path.dirname(__file__),
'scripts',
'DUMP_VERSION')) as f:
DUMP_VERSION = f.readline().strip()
with open(os.path.join(
os.path.dirname(__file__),
'scripts',
'TORRENT_HASH')) as f:
... | 2.5 | 2 |
hirearefugee/userclass/migrations/0003_auto_20200812_1803.py | maximilianharr/hirearefugee | 1 | 44248 | # Generated by Django 3.1 on 2020-08-12 18:03
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('userclass', '0002_auto_20200812_1731'),
]
operations = [
... | 1.726563 | 2 |
eeglib/tests/test_auxFunctions.py | Xiul109/eeglib | 20 | 44249 | <reponame>Xiul109/eeglib
import unittest
import numpy as np
from itertools import product
import eeglib.auxFunctions as aux
class TestAuxFuncs(unittest.TestCase):
dictToFlat = {"asd":1, "lol":[2,3], "var":{"xd":4, "XD":5}}
listToFlat = [0, 1, 2, [3, 4], [5, [6, 7]]]
simpleDict = {"a":0, "b":1}
... | 2.921875 | 3 |
vathos/trainer/tpu_trainer.py | satyajitghana/ProjektDepth | 2 | 44250 | from .base_trainer import BaseTrainer
import torch
import os
class TPUTrainer(BaseTrainer):
r"""TPUTrainer: Trains the vathos model on TPU
"""
def __init__(self, *args, **kwargs):
super(TPUTrainer, self).__init__(*args, **kwargs)
import torch_xla
import torch_xla.core.xla_model ... | 2.46875 | 2 |
chromecast/tools/build/package_test_deps.py | zealoussnow/chromium | 14,668 | 44251 | #!/usr/bin/env python
#
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Packages test dependencies as tar.gz file."""
import argparse
import json
import logging
import os
import sys
import tarfile
pa... | 2.734375 | 3 |
AtC_Beg_Con_071-080/ABC076/C.py | yosho-18/AtCoder | 0 | 44252 | import copy as cp
s = input()
t = input()
u = list(s)
v = list(t)
w = cp.deepcopy(u)
p = 0
q = 0
for h in range(len(u) - 1, -1, -1):
if q == 1:
break
if v[-1] == u[h]:
#w[i] = v[0]
for j in range(len(v)):
if (v[-1 - j] == u[h - j]) and h - j >= 0:
pass
... | 2.859375 | 3 |
hls4ml/backends/fpga/fpga_types.py | jaemyungkim/hls4ml | 380 | 44253 | <reponame>jaemyungkim/hls4ml
import numpy as np
from hls4ml.model.types import CompressedType, NamedType, ExponentType, FixedPrecisionType, IntegerPrecisionType, XnorPrecisionType, ExponentPrecisionType, TensorVariable, PackedType, WeightVariable
#region Precision types
class PrecisionDefinition(object):
def def... | 2.359375 | 2 |
tripleo_common/tests/actions/test_swifthelper.py | AllenJSebastian/tripleo-common | 2 | 44254 | <reponame>AllenJSebastian/tripleo-common
# Copyright 2016 Red Hat, 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... | 1.789063 | 2 |
misty/ca.py | b1tninja/misty | 1 | 44255 | <reponame>b1tninja/misty
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import io
import json
import logging
import os
import os.path
import pprint
import sys
import zipfile
from contextlib import closing
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(os.path.basename(__file__))
EN... | 2.265625 | 2 |
personalcrm/quote/migrations/0007_auto_20210131_1508.py | carlossgv/personalcrm-repo | 2 | 44256 | <reponame>carlossgv/personalcrm-repo
# Generated by Django 3.1.5 on 2021-01-31 15:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quote', '0006_quotedproducts_hidden'),
]
operations = [
migrations.AddField(
model_name='qu... | 1.640625 | 2 |
Algorithms/Easy/1154. Day of the Year/answer.py | KenWoo/Algorithm | 0 | 44257 | <reponame>KenWoo/Algorithm
from typing import List
class Solution:
def dayOfYear(self, date: str) -> int:
d = date.split('-')
year, month, day = int(d[0]), int(d[1]), int(d[2])
isLeap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
months = [31, 28, 31, 30, 31, 30, 31, 31,... | 3.46875 | 3 |
lab2/CmdView.py | YevhenKhomenko/crossplatform_labs | 0 | 44258 | <filename>lab2/CmdView.py<gh_stars>0
class View:
@staticmethod
def show_message(message):
print(message)
@staticmethod
def get_input():
return input()
| 1.8125 | 2 |
solutions/day2.py | alanahanson/adventofcode2017 | 0 | 44259 | <reponame>alanahanson/adventofcode2017
from unittest import TestCase
def checksum(data, operator):
rows = [[int(num) for num in row.strip().split()] for row in data.strip().split("\n")]
return sum(operator(rows))
def difference(rows):
return [max(row) - min(row) for row in rows]
def quotients(rows):
... | 3.796875 | 4 |
test/lisa/qemu_test.py | rf972/lisa-qemu | 2 | 44260 | import logging
import os
from lisa.trace import FtraceCollector, Trace
from lisa.utils import setup_logging
from lisa.target import Target, TargetConf
from lisa.wlgen.rta import RTA, Periodic
from lisa.datautils import df_filter_task_ids
import pandas as pd
setup_logging()
target = Target.from_one_conf('conf/lisa/qemu... | 1.914063 | 2 |
tests/test_core.py | netMedi/hl7apy | 0 | 44261 | <reponame>netMedi/hl7apy
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018, CRS4
#
# 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 righ... | 1.195313 | 1 |
olea/models/mango.py | Pix-00/olea | 2 | 44262 | <reponame>Pix-00/olea<filename>olea/models/mango.py<gh_stars>1-10
__all__ = ['Mango']
from sqlalchemy_ import BaseModel, Column, ForeignKey, UniqueConstraint, relationship
from sqlalchemy_.types import JSONB, DateTime, Integer, String
class Mango(BaseModel):
__tablename__ = 'mango'
id = Column(String, prima... | 2.28125 | 2 |
vc3/model.py | ta1fukawa/vc-beta | 0 | 44263 | <filename>vc3/model.py<gh_stars>0
import torch
class NoActivation(torch.nn.Module):
def forward(self, x):
return x
def get_activation(name, **kwargs):
if name == 'linear':
return NoActivation()
elif name == 'relu':
return torch.nn.ReLU(**kwargs)
elif name == 'sigmoid':
... | 2.546875 | 3 |
tests/test_spider.py | TeamHG-Memex/domain-discovery-crawler | 16 | 44264 | <reponame>TeamHG-Memex/domain-discovery-crawler<filename>tests/test_spider.py
import json
from urllib.parse import quote
import pytest
from sklearn.externals import joblib
from twisted.web.resource import Resource
from twisted.web.util import redirectTo
from dd_crawler.spiders import DeepDeepSpider
from .mockserver i... | 2.296875 | 2 |
src/client.py | AntonioFuziy/VR_Robot | 0 | 44265 | <filename>src/client.py
import io
import socket
import struct
import time
import picamera
from IP import IP_ADDRESS
client_socket = socket.socket()
client_socket.connect((IP_ADDRESS, 8000))
connection = client_socket.makefile("wb")
try:
camera = picamera.PiCamera()
camera.vflip = True
camera.resolution = (500,... | 2.90625 | 3 |
processing/un_wpp/inputs/download.py | fieldmaps/population-stats | 1 | 44266 | <filename>processing/un_wpp/inputs/download.py
import requests
import pandas as pd
from .utils import DATA_URL, ADM0_URL, cwd, logging
logger = logging.getLogger(__name__)
data = cwd / '../../../inputs/un_wpp'
def download_file(url):
data.mkdir(parents=True, exist_ok=True)
file = data / url.split('/')[-1]
... | 2.84375 | 3 |
15/02/0.py | pylangstudy/201709 | 0 | 44267 | import bisect
breakpoints = [60, 70, 80, 90]
grades = 'FDCBA'
scores = [33, 99, 77, 70, 89, 90, 100]
def grade(score, breakpoints=breakpoints, grades=grades):
i = bisect.bisect(breakpoints, score)
return grades[i]
print('breakpoints:', breakpoints)
print('grades:', grades)
print('scores:', scores)
print([grade... | 3.546875 | 4 |
python/exfiles_similarity.py | unmtransinfo/Exfiles | 0 | 44268 | <reponame>unmtransinfo/Exfiles<gh_stars>0
#!/usr/bin/env python3
"""exfiles_similarity.py
Expression profiles similarity computation.
- Author: <NAME>
- Required: Python3, Pandas 0.22+
- Input expression profiles format expected: TSV, 2 columns of identifiers (ENSG, SEX) followed by multiple columns of expression... | 2.1875 | 2 |
main/networkmanager/update.py | RoastVeg/cports | 0 | 44269 | pkgname = "NetworkManager"
| 1.0625 | 1 |
cogandmem/text.py | aemacdermid/cogandmem | 0 | 44270 | """
Functions for displaying text to the screen.
Text rendering in pygame does not allow for line breaks. This can lead to
issues when attempting to render text, particularly if one is unsure of the
width and height of a to-be-rendered string in a given font. The functions
here handle these difficulties.
This module ... | 3.984375 | 4 |
scrape.py | GP-20/telegram_news_bot | 0 | 44271 | <reponame>GP-20/telegram_news_bot
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import requests
import datetime
import time
options = Options()
options.headless = True
def scrape_diario(url="http://diario.mx"):
driver = webdriver.Firefox(option... | 2.875 | 3 |
msp/datasets/__init__.py | bilalsp/msp | 2 | 44272 | """
The :mod:`mps.datasets` module includes utility to generate sample data.
"""
from msp.datasets._samples_generator import make_sparse_data
__all__ = ['make_sparse_data'] | 1.203125 | 1 |
humidor/sensors.py | sittingfrog/humidor | 0 | 44273 | <filename>humidor/sensors.py
import os
import json
import yaml
from datetime import datetime
from inkbird import InkbirdIBSTH
class Sensors():
def __init__(self, config_yaml='sensors.yaml'):
print(f'{self._timestamp()} Initializing Sensors...')
with open(config_yaml) as f:
yaml_conten... | 2.84375 | 3 |
tabular_ml_toolkit/preprocessor.py | psmathur/tabular_ml_toolkit | 1 | 44274 | # AUTOGENERATED! DO NOT EDIT! File to edit: 01_preprocessor.ipynb (unless otherwise specified).
__all__ = ['PreProcessor']
# Cell
from .dataframeloader import *
from .logger import *
# Cell
# hide
from sklearn.compose import ColumnTransformer, make_column_transformer
from sklearn.pipeline import Pipeline
from sklear... | 2.609375 | 3 |
lstm_as_approximation.py | iitis/qcontrol_lstm_approx | 5 | 44275 | import os
from sys import argv, stdout
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import tensorflow as tf
import numpy as np
import scipy
import scipy.io
from itertools import product as prod
import time
from tensorflow.python.client import timeline
import cProfile
from sys import argv, stdout
from get_data import *
impo... | 2.015625 | 2 |
blue_green_assets/release_health_check.py | DNXLabs/docker-beanstalk-bluegreen | 3 | 44276 | from __future__ import print_function
import os
from time import strftime, sleep
import requests
import time
def main(BLUE_ENV_NAME, boto_authenticated_client):
beanstalkclient = boto_authenticated_client.client('elasticbeanstalk')
wait_until_env_be_ready(beanstalkclient, BLUE_ENV_NAME)
if os.getenv("RELEASE_H... | 2.609375 | 3 |
Python/code case/code case 79.py | amazing-2020/pdf | 3 | 44277 | class Test:
def ptr(self):
print(self)
print(self.__class__)
class Test2:
def ptr(baidu):
print(baidu)
print(baidu.__class__)
class people:
name = ''
age = 0
__weight = 0
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__w... | 3.765625 | 4 |
text_tokenizers.py | kotikkonstantin/convasr | 17 | 44278 | <filename>text_tokenizers.py
import re
import sentencepiece
import typing
from collections import defaultdict
class CharTokenizerLegacy:
def __init__(self, alphabet: str):
self.alphabet = alphabet
self.unk_token = '*'
self.punkt_token = '.'
self.repeat_token = '2'
self.spac... | 2.9375 | 3 |
services/api-server/src/simcore_service_api_server/api/dependencies/services.py | colinRawlings/osparc-simcore | 25 | 44279 | """ Dependences with any other services (except webserver)
"""
from typing import Callable, Type
from fastapi import HTTPException, Request, status
from ...utils.client_base import BaseServiceClientApi
def get_api_client(client_type: Type[BaseServiceClientApi]) -> Callable:
"""
Retrieves API client fro... | 2.015625 | 2 |
pycoin/symbols/mona.py | jaschadub/pycoin | 1,210 | 44280 | from pycoin.networks.bitcoinish import create_bitcoinish_network
network = create_bitcoinish_network(
network_name="Monacoin", symbol="MONA", subnet_name="mainnet",
wif_prefix_hex="b0", sec_prefix="MONASEC:", address_prefix_hex="32", pay_to_script_prefix_hex="37",
bip32_prv_prefix_hex="0488ade4", bip32_pu... | 2.28125 | 2 |
C Project Files/py/postscriptNameMap.py | colinmford/font-production-project-template-glyphs | 1 | 44281 | def generatePostscriptNameMap(glyphList):
"""
Generate a PostScript Name Map to be stored in the "public.postscriptNames" lib.
Used to rename glyphs during generation, like so:
{"indianrupee.tab": "uni20B9.tab"}
Args:
glyphList (list): A list of Glyph objects or a Font object (Defcon or F... | 3.4375 | 3 |
android_test_inspector/latex_correlations_matrix.py | luiscruz/android_test_inspector | 6 | 44282 | import csv
import argparse
def get_striked_header_pairs(strikethrough):
if strikethrough is not None:
return [pair.split('--') for pair in strikethrough]
else:
return []
def build_colored_str(v, cancelled):
if (v < 0.20):
return '\\textcolor{cor-very-weak}{' + str(cancelled) + "}... | 2.96875 | 3 |
ripiu/djangocms_aoxomoxoa/admin/options/grid_panel.py | ripiu/djangocms_aoxomoxoa | 0 | 44283 | <filename>ripiu/djangocms_aoxomoxoa/admin/options/grid_panel.py
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class GridPanelUniteOptionsAdmin(admin.ModelAdmin):
'''
Grid theme
'''
fieldsets = (
(_('Strip panel options'), {
'classes': ('co... | 1.648438 | 2 |
test/__init__.py | Cazoo-uk/py-logger | 1 | 44284 | <filename>test/__init__.py
class LambdaContext(object):
def __init__(
self,
request_id="request_id",
function_name="my-function",
function_version="v1.0",
):
self.aws_request_id = request_id
self.function_name = function_name
self.function_version = functi... | 2.234375 | 2 |
DL_Models/torch_models/Modules.py | Zensho/CS91-Proj | 0 | 44285 | <reponame>Zensho/CS91-Proj
import torch.nn as nn
import math
class Pad_Pool(nn.Module):
"""
Implements a padding layer in front of pool1d layers used in our architectures to achieve padding=same output shape
Pads 0 to the left and 1 to the right side of x
"""
def __init__(self, left=0, right=1, ... | 3.65625 | 4 |
raspberrypy/motor/L289N.py | slipstreamJumper/RaspberryPy | 1 | 44286 | from ..utils.GPIO_utils import setup_output, output, GPIO_Base
from time import sleep
import random
def keep_decorate(func):
def func_wrapper(self, keep=None):
func(self, keep)
if keep is None: keep = self.keep
if keep > 0:
sleep(keep)
self._stop()
return func_wrapper
class L289N(GPIO_Base... | 2.953125 | 3 |
Lecture_01/hw_01_05_.py | YouWatanabe/fp | 0 | 44287 | from matplotlib import pyplot as plt
def leibniz(n):
lz = 0
ret = list()
for i in range(n + 1):
lz += ((-1) ** i) * (4 / (2 * i + 1))
ret.append(lz)
return lz, ret
lz, ret = leibniz(1000)
plt.plot(ret)
plt.show()
| 3.421875 | 3 |
CHEFADV.py | akashsuper2000/codechef-archive | 0 | 44288 | for i in range(int(input())):
n,m,x,y = [int(j) for j in input().split()]
if((n-1)%x==0 and (m-1)%y==0):
print('Chefirnemo')
elif(n-2>=0 and m-2>=0):
if((n-2)%x==0 and (m-2)%y==0):
print('Chefirnemo')
else:
print('Pofik')
else:
print('Pofik')
| 3.296875 | 3 |
shopcloud_django_toolbox/views.py | Talk-Point/shopcloud-django-toolbox | 0 | 44289 | from django.http import HttpResponse
from django.views.decorators.http import require_GET
@require_GET
def security_txt(request):
"""
securit.tyt
---
add to the path
path(".well-known/security.txt", core_views.security_txt),
"""
lines = [
"Contact: mailto:<EMAIL>",
"Expir... | 1.96875 | 2 |
fsm.py | Tattos/TOC-Project-2017 | 0 | 44290 | <reponame>Tattos/TOC-Project-2017
# -- coding: UTF-8 --
from transitions.extensions import GraphMachine
global name
global reserve
class TocMachine(GraphMachine):
def __init__(self, **machine_configs):
self.machine = GraphMachine(
model = self,
**machine_configs
)
#state 1(... | 2.890625 | 3 |
header_common.py | invisiblebob395/awefawe | 0 | 44291 | ###################################################
# header_common.py
# This file contains common declarations.
# DO NOT EDIT THIS FILE!
###################################################
server_event_preset_message = 0
server_event_play_sound = 1
server_event_scene_prop_p... | 1.320313 | 1 |
tests/resources/my_dummy_handlers/dummy_handler_multiple_args_too_few.py | stude1/robotframework-oxygen | 13 | 44292 | <filename>tests/resources/my_dummy_handlers/dummy_handler_multiple_args_too_few.py<gh_stars>10-100
from oxygen import BaseHandler
class MyDummyHandler(BaseHandler):
'''
A test handler that throws mismatch argument exception because
parse_results expects too many arguments
'''
def run_my_dummy_han... | 2.40625 | 2 |
clase2/primos.py | Jhoselyn-Carballo/computacion_para_ingenieria | 0 | 44293 | <filename>clase2/primos.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 09:38:18 2022
@author: JHOSS
"""
#CONTAR LOS NUMEROS PRIMOS DEL 1 AL 100
num = 1
while num <=100:
cont =1
x=0
while cont <= num:
if num % cont == 0:
x=x+1
cont = cont +1
if x==2:
print(num)... | 3.1875 | 3 |
src/utils.py | AdamRuddGH/crypto_get_latest_coins_lambda | 0 | 44294 | <reponame>AdamRuddGH/crypto_get_latest_coins_lambda<gh_stars>0
"""
Shared utilities. Mostly for time
"""
import arrow
import json
import re
def datetime_now():
"""
returns UTC now time
add .format('YYYY-MM-DD HH:mm:ss ZZ') to convert to ISO
add .format()
"""
return arrow.utcnow()
def epoch_to... | 2.5 | 2 |
deep_qa-master/deep_qa/data/instances/sequence_tagging/tagging_instance.py | RTHMaK/RPGOne | 1 | 44295 | from typing import Dict, List, Any
import numpy
from overrides import overrides
from ..instance import TextInstance, IndexedInstance
from ...data_indexer import DataIndexer
class TaggingInstance(TextInstance):
"""
A ``TaggingInstance`` represents a passage of text and a tag sequence over that text.
The... | 3.484375 | 3 |
day01_part1.py | jkbockstael/adventofcode-2020 | 1 | 44296 | <filename>day01_part1.py
# Advent of Code 2020 - Day 1 - Report Repair
# https://adventofcode.com/2020/day/1
import sys
def parse_input(lines):
return [int(line.strip()) for line in lines]
def part1(expenses):
return [a * b for a in expenses for b in expenses if a + b == 2020][0]
if __name__ == "__main__":
... | 3.0625 | 3 |
readFromWrite.py | openNuke/toolkit | 36 | 44297 | #<NAME>
# todo mov not working
import nuke
from PySide import QtGui
def run(node):
clipboard = QtGui.QApplication.clipboard()
filename = node['file'].evaluate()
filesplit = filename.rsplit('.',-2)
filesplit[1] = '%0'+str(len(filesplit[1]))+'d'
filep = '.'.join(filesplit)
filenameFrame = nuke.getFileN... | 2.109375 | 2 |
pyutil/iterators/intersection.py | SSouik/pyutil | 0 | 44298 | <gh_stars>0
"""
Author <NAME>
License MIT.
intersection.py
"""
from itertools import islice
def intersection(*seqs):
"""
Description
----------
Creates a generator containing values found in all sequences.
Parameters
----------
*seqs : (list or tuple) - sequences to pull common values ... | 3.671875 | 4 |
src/settings.py | psykzz/st3-gitblame | 28 | 44299 | import sublime
def pkg_settings():
# NOTE: The sublime.load_settings(...) call has to be deferred to this function,
# rather than just being called immediately and assigning a module-level variable,
# because of: https://www.sublimetext.com/docs/3/api_reference.html#plugin_lifecycle
return sublime.loa... | 2.046875 | 2 |