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
build_tflite.py
fazil47/UnityCharRecog
0
37100
<filename>build_tflite.py #!/usr/bin/env python3 import argparse import os import platform import shlex import subprocess PLUGIN_PATH=f'{os.getcwd()}/Assets/TensorFlowLite/Plugins' TENSORFLOW_PATH='' def run_cmd(cmd): args = shlex.split(cmd) subprocess.call(args, cwd=TENSORFLOW_PATH) def copy(from_tf, to_un...
2.15625
2
tests/trainers/test_chesapeake.py
nilsleh/torchgeo
0
37101
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os from typing import Any, Dict, Generator, cast import pytest from _pytest.fixtures import SubRequest from _pytest.monkeypatch import MonkeyPatch from omegaconf import OmegaConf from torchgeo.datamodules import Ches...
1.960938
2
src/huggingmolecules/models/models_api.py
chrislybaer/huggingmolecules
60
37102
import logging import os from typing import Generic, List, Type, Any import torch import torch.nn as nn from ..downloading.downloading_utils import from_cache from ..featurization.featurization_api import T_BatchEncoding, T_Config, PretrainedFeaturizerMixin class PretrainedModelBase(nn.Module, Generic[T_BatchEncodi...
1.921875
2
check_db.py
Yaremenko-R/python_training
0
37103
from fixture.orm import ORMFixture from fixture.db import DbFixture from model.group import Group from model.contact import Contact database = ORMFixture(host="localhost", name="addressbook", user="root", password="") try: l = database.get_contacts_in_group(Group(id="174")) # l = sorted(database.get_groups_con...
2.265625
2
meiduo_mall/meiduo_mall/apps/payment/views.py
ZHD165/Django_-
0
37104
<filename>meiduo_mall/meiduo_mall/apps/payment/views.py from django.http import JsonResponse import os from alipay import AliPay from django.views import View from django.conf import settings from orders.models import OrderInfo from payment.models import Payment class PaymentsView(View): def get(self, request, o...
2.15625
2
viewer_process/ghcc/libs/config.py
lloesche/github_commit_crawler
0
37105
import yaml class ConfigChanger(object): ''' class to read/write the config file ''' def __init__(self, location): self.loc = location # path to yaml file def config_file_ok(self): ''' returns boolean if config file is OK and contains good values, or false if config need...
2.984375
3
fourtynine.py
glennandreph/learnpython
1
37106
def my_function_with_args(username, greeting): print("Hello, %s , From My Function! I wish you %s" %(username, greeting))
2.953125
3
utils.py
josephtjohnson/Meme_Generator
0
37107
from QuoteEngine import Ingestor, QuoteModel from MemeGenerator import MemeEngine from PIL import Image import argparse import random import os import textwrap import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s') fil...
2.484375
2
mdn_ik/test.py
uenian33/Franka_Panda_IK_Sensor
0
37108
<filename>mdn_ik/test.py import torch a = torch.rand(3, 4) #a = a.unsqueeze(0) #print(a.reshape(3,4,1)) b = torch.rand(3, 4) #b = b.unsqueeze(0) print(b) c = torch.stack([a, b, b, b, b], dim=1) c = torch.rand(3, 20) print(c) c = c.reshape(3, 5, 4) print(c.shape) d = torch.rand(3, 5) d = d.reshape(3,5,1) print(d) e ...
3.09375
3
src/plugins/yiqing/data_source.py
wizardCRain/mini_jx3_bot
27
37109
<reponame>wizardCRain/mini_jx3_bot<gh_stars>10-100 from datetime import date from typing import Optional, Tuple from httpx import AsyncClient from nonebot.adapters.onebot.v11.message import MessageSegment from src.utils.browser import browser from src.utils.log import logger from .config import CITY_MAP def _get_ci...
2.25
2
server/src/sdistance.py
bepnye/brat
20
37110
#!/usr/bin/env python ''' Various string distance measures. Author: <NAME> <<NAME> se> Version: 2011-08-09 ''' from string import digits, lowercase from sys import maxint DIGITS = set(digits) LOWERCASE = set(lowercase) TSURUOKA_2004_INS_CHEAP = set((' ', '-', )) TSURUOKA_2004_DEL_CHEAP = TSURUOKA_2004_INS...
3.296875
3
expressmanage/customers/views.py
abbas133/expressmanage-free
0
37111
<gh_stars>0 from django.views import generic from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from .forms import CustomerForm from .models import Customer from .helper import CustomerSummary class Customer_IndexView(LoginRequiredMixin, generic.Lis...
2.15625
2
orbitals.py
inconvergent/orbitals_speedup
39
37112
<gh_stars>10-100 #!/usr/bin/python # -*- coding: utf-8 -*- from numpy.random import random, randint from numpy import zeros, sin, cos class Orbitals(object): def __init__(self,num,stp,farl,nearl,friendship_ratio, friendship_initiate_prob,maxfs): self.num = num self.stp = stp self.farl =...
2.9375
3
surfactant_example/micelle/micelle_factory.py
force-h2020/force-bdss-plugin-surfactant-example
0
37113
from force_bdss.api import BaseDataSourceFactory from .micelle_model import MicelleDataSourceModel from .micelle_data_source import MicelleDataSource class MicelleFactory(BaseDataSourceFactory): def get_identifier(self): return "micelle" def get_name(self): return "Micelle Aggregation Calcu...
1.71875
2
tests/test_image_upload.py
ephes/django-cast
11
37114
import pytest from django.urls import reverse class TestImageUpload: @pytest.mark.django_db def test_upload_image_not_authenticated(self, client, small_jpeg_io): upload_url = reverse("cast:api:upload_image") small_jpeg_io.seek(0) r = client.post(upload_url, {"original": small_jpeg_io...
2.328125
2
commit.py
Delostik/gitlab-statistics
0
37115
# -*- coding: utf-8 -*- import requests def get_all_commits(base_url, token, project_id, filter_author=''): res = [] next_page = 1 url_format = '{}/api/v4/projects/{}/repository/commits?ref=master&per_page=100&page={}' while next_page != '': url = url_format.format(base_url, project_id, next_p...
2.609375
3
read.py
sundeepsingh1984/openinsiderscrapper
0
37116
import pandas as pd df=pd.read_json("D:\eiaScrapper\eio.jl") print(df.info())
2.609375
3
src/adafruit_blinka/microcontroller/amlogic/s905x3/pin.py
Jcc99/Adafruit_Blinka
294
37117
"""AmLogic s905x3 pin names""" # pylint: disable=wildcard-import,unused-wildcard-import from adafruit_blinka.microcontroller.amlogic.meson_g12_common.pin import *
1.132813
1
qube/drivers/NI6733.py
ClementGeffroy/qube
1
37118
# -*- coding: utf-8 -*- """ Created on Fri Aug 21 20:00:50 2020 @author: takada """ import logging import numpy as np import functools import operator from typing import List, Dict, Callable import time import nidaqmx from nidaqmx.stream_writers import ( DigitalSingleChannelWriter, AnalogMultiChannelWriter) from...
2.15625
2
v2_trip/urls.py
ruslan-ok/ruslan
0
37119
from django.urls import path from . import views app_name = 'v2_trip' urlpatterns = [ path('', views.main, name='main'), path('<int:pk>/', views.item_form, name='item_form'), path('persons/', views.go_persons, name='go_persons'), path('trips/', views.go_trips, name='go_trips'), ...
1.820313
2
Sorting Algorithms/quick_sort.py
Divyamop/Python-DSA
13
37120
<filename>Sorting Algorithms/quick_sort.py """ Quick sort is a divide and conquer algorithm Steps: 1. We first select an element randomly which we call pivot element. We can choose any element as pivot element. But for consistency and performce purposes we select middle element of array as the pivot element. 2. Then...
3.734375
4
my_dataclasses/plays.py
GudniNatan/GSKI-PA6
0
37121
from dataclasses import dataclass from my_dataclasses.member import Member from my_dataclasses.sport import Sport @dataclass(order=True, frozen=True) class Plays(object): member: Member sport: Sport
2.4375
2
src/methods/linear_scalarization_method.py
nbingo/sMOOth
0
37122
<gh_stars>0 import time import torch from torch.distributions.dirichlet import Dirichlet from detectron2.engine.train_loop import SimpleTrainer class LinearScalarizationTrainer(SimpleTrainer): """ A simple trainer for the most common type of task: single-cost single-optimizer single-data-source iterative...
2.734375
3
test/proxyhttp_test.py
sancau/ivelum_test_task
0
37123
<filename>test/proxyhttp_test.py # -*- coding: utf-8 -*- import falcon from proxyhttp import Proxy from transformer import Transformer def test_api_runs(client): resp = client.simulate_get('/') assert resp.status == falcon.HTTP_200 def test_proxy_middleware_instance_initializes_correctly(): p = Proxy(...
2.609375
3
singletons/mail.py
kwestpharedhat/quay
0
37124
from flask_mail import Mail from singletons.app import _app mail = Mail(_app)
1.4375
1
system-test/testnet-automation-json-parser.py
Flawm/solana
7,843
37125
#!/usr/bin/env python3 import sys, json, argparse parser = argparse.ArgumentParser() parser.add_argument("--empty_error", action="store_true", help="If present, do not print error message") args = parser.parse_args() data=json.load(sys.stdin) if 'results' in data: for result in data['results']: if 'series' ...
3.125
3
perfkitbenchmarker/providers/ibmcloud/flags.py
Nowasky/PerfKitBenchmarker
3
37126
# Copyright 2020 PerfKitBenchmarker Authors. 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 appli...
1.28125
1
belleflopt/optimize.py
ucd-cws/eflows_optimization
2
37127
<reponame>ucd-cws/eflows_optimization import logging import random import collections import os from itertools import chain import numpy import pandas from platypus import Problem, Real from platypus.operators import Generator, Solution from matplotlib import pyplot as plt from belleflopt import models from belleflo...
2.65625
3
tests/test_booking.py
muthash/FlightBooking-Flask
1
37128
<reponame>muthash/FlightBooking-Flask """Test case for the booking creation functionality""" import os import json from datetime import datetime from tests.base_test import BaseTestCase class TestBookingManipulation(BaseTestCase): """Test for Booking manipulation endpoint""" def crate_flight(self): ...
3.0625
3
src/constants.py
tomasmikeska/face-identification
5
37129
import os from utils import relative_path # Hyperparams ARCFACE_M = 0.5 ARCFACE_S = 10. CENTERLOSS_ALPHA = 0.008 CENTERLOSS_LAMBDA = 0.5 EMBEDDING_SIZE = 256 MIN_FACES_PER_PERSON = 5 # Min num of samples per class - or class is removed MAX_FACES_PER_PERSON = 200 # Max num of sampl...
2.109375
2
consent/__init__.py
alekosot/django-consent
1
37130
<gh_stars>1-10 # following PEP 386, versiontools will pick it up __version__ = (0, 2, 0, "final", 0)
1.109375
1
sample_test.py
tynski/sample_package
0
37131
<reponame>tynski/sample_package import unittest from sample_package.sub_package1 import my_sum class TestSamplePackage(unittest.TestCase): def test_my_sum(self): self.assertEqual(my_sum([7,9,1]),17) if __name__ == '__main__': unittest.main()
2.484375
2
tests/test_processor.py
manslogic/rasa_core
1
37132
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_core.channels import UserMessage from rasa_core.channels.direct import CollectingOutputChannel from rasa_core.featurizers import BinaryFeaturizer from rasa_core...
2
2
metrics.py
juanmc2005/continual-cross-lingual-nlu
0
37133
import uuid from typing import Dict, List, Text, Union import pandas as pd import torch from datasets import load_metric from pytorch_lightning.metrics import Metric from seqeval.metrics import classification_report # MIT License # # Copyright (c) 2021 Université Paris-Saclay # Copyright (c) 2021 Laboratoire national...
2.171875
2
EulerFour.py
vanigupta20024/Programming-Challenges
14
37134
# Project Euler - Problem 4 # Find the largest palindrome made from the product of two 3-digit numbers. import time start = time.time() def pal(s): i = 0 j = len(s) - 1 while i < j: if s[i] != s[j]: return 0 i += 1 j -= 1 return 1 n1 = 100 n2 = 1000 # exclusive mx = 0 for i in range(n1, n2): for j in r...
3.6875
4
tests/testing/helpers/test_assert_function_call_count.py
munichpavel/tubular
0
37135
<gh_stars>0 import pytest import tubular import tubular.testing.helpers as h import tubular.testing.test_data as d def test_arguments(): """Test tubular.testing.helpers.assert_function_call_count has expected arguments.""" # use of contextmanager decorator means we need to use .__wrapped__ to get back to ori...
2.546875
3
portfolio/Python/scrapy/petsafe/petstreetmallcom.py
0--key/lib
0
37136
<reponame>0--key/lib<gh_stars>0 from csv import DictReader from petsafeconfig import CSV_FILENAME from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request from product_spiders.items import Product, ProductLoader import logging class PetstreetmallComSpider(B...
2.5
2
app.py
elben10/corona-dashboard
0
37137
<gh_stars>0 import dash from flask_caching import Cache EXTERNAL_SCRIPTS = [ "https://code.jquery.com/jquery-3.4.1.slim.min.js", "https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js", "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js", ] EXTERNAL_STYLESHEETS = [ "...
1.953125
2
scripts/active_inference.py
tud-cor/jackal_active_inference_versus_kalman_filter
4
37138
#!/usr/bin/env python ########################################################################### # Active Inference algorithm # # Execute the AI algorithm using the data from the # /filter/y_coloured_noise topic and publish the results to the # /filter/ai/output topic. # Note that only the filtering part of the AI ...
2.734375
3
alembic/versions/add66992d51f_add_user_model.py
shiroyuki/2019-cfp
0
37139
<gh_stars>0 """add user model Revision ID: add<PASSWORD> Revises: Create Date: 2018-05-29 20:47:40.890728 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### comman...
1.429688
1
scrapeMembers.py
iversc/lb-conforums-scraper
0
37140
<filename>scrapeMembers.py import forumLogin import os from bs4 import BeautifulSoup print("Logging in to conforums site...") forumLogin.doLogin() print("Creating member indexes folder...") try: os.mkdir("member-indexes") except OSError: pass members_url = forumLogin.board_url + "index.cgi?action=mlall" print("...
2.953125
3
tests/modules/idn/test_idn_update.py
bladeroot/heppy
20
37141
<reponame>bladeroot/heppy<gh_stars>10-100 #!/usr/bin/env python import unittest from ..TestCase import TestCase class TestIdnUpdate(TestCase): def test_render_idn_update_request(self): self.assertRequest('''<?xml version="1.0" ?> <epp xmlns="urn:ietf:params:xml:ns:epp-1.0"> <command> <update...
2.359375
2
Python-Basics/13.Nested Loops/06.Tower.py
Xamaneone/SoftUni-Intro
0
37142
<filename>Python-Basics/13.Nested Loops/06.Tower.py height = int(input()) apartments = int(input()) is_first = True isit = 0 for f in range(height, 0, -1): for s in range(0, apartments, 1): if is_first == True: isit += 1 print(f"L{f}{s}", end=" ") if isit == apartments: ...
3.875
4
arse/biclustering/deflation.py
marianotepper/comdet
0
37143
from __future__ import absolute_import from . import compression from . import utils class DeflationError(RuntimeError): def __init__(self, *args, **kwargs): super(DeflationError, self).__init__(*args, **kwargs) class Deflator(utils.Downdater): def __init__(self, array): super(Deflator, self...
2.390625
2
test/test.py
Trick-17/clang-build
8
37144
import os, sys import unittest import subprocess import shutil import logging import io import stat from pathlib import Path as _Path from multiprocessing import freeze_support from sys import platform as _platform import json from clang_build import cli from clang_build import toolchain from clang_build.errors impor...
2.1875
2
exoatlas/populations/curation/TransitingExoplanets.py
zkbt/exopop
4
37145
def curate(pop): pass
0.855469
1
Misc Learning/HackerRank 30 Days of Code/Additional Practice Problems/Dominator.py
hamil168/Learning-Data-Science
0
37146
""" Dominator Problem by Codility Solution by <NAME> An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. Write a function that, given an array A consisting of N integers, returns index of any element of array A in which the domi...
3.484375
3
avalon-scone/scone_worker/avalon_worker/workload/openvino.py
T-Systems-MMS/hyperledger-secure-avalon
0
37147
<gh_stars>0 #!/usr/bin/python3 # Copyright 2020 <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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
2.125
2
MLProjects/iris-machine-learning-master/irisML.py
evidawei/HacktoberFest_2021
33
37148
<reponame>evidawei/HacktoberFest_2021 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from IPython.display import Image from sklearn.externals.six import StringIO from sklearn.tree import export_graphviz from sklearn.neighbors import KNeighborsClassifier from sklearn.model_...
2.453125
2
Data Structures/Heap/JesseAndCookies.py
aibenStunner/HackerRank
2
37149
#!/bin/python3 import os import sys class minHeap: def __init__(self): self.items = [] self.size = len(self.items) def getLeftChildIndex(self, parentIndex): return 2 * parentIndex + 1 def getRightChildIndex(self, parentIndex): return 2 * parentIndex + 2 def g...
3.53125
4
submodule.py
Jaewoo97/VisualOdomtery
0
37150
<reponame>Jaewoo97/VisualOdomtery from __future__ import print_function import torch import torch.nn as nn import torch.utils.data from torch.autograd import Variable import torch.nn.functional as F import math import numpy as np def test(model, imgL,imgR,disp_true): model.eval() imgL, imgR,...
2.328125
2
parseq/scripts/geoquery_geo880_basic_nar.py
saist1993/parseq
1
37151
<filename>parseq/scripts/geoquery_geo880_basic_nar.py<gh_stars>1-10 import os import re import sys from functools import partial from typing import * import torch import qelos as q from allennlp.modules.seq2seq_encoders import PytorchSeq2SeqWrapper from nltk import PorterStemmer from torch.utils.data import DataLoad...
1.835938
2
oe_site/app/admin.py
WsinGithub/ChemECar_web
0
37152
from django.contrib import admin # django框架默认文件 # Register your models here.
1.132813
1
Queen's Attack II.py
Swagatamkar/Python_HackerranK
3
37153
''' Problem Statement: https://www.hackerrank.com/challenges/queens-attack-2/problem @Coded by TSG, 2020 ''' import math import os import random import re import sys # Complete the queensAttack function below. def queensAttack(n, k, qr, qc , obs): closet_row_obs_left = 1 closet_row_obs_right = n closet_co...
3.578125
4
full-problems/twiceCounter.py
vikas-t/DS-Algo
0
37154
#!/usr/bin/python3 # https://practice.geeksforgeeks.org/problems/twice-counter/0 def sol(words): h = {} res = 0 for word in words: h[word] = h[word] + 1 if word in h else 1 for word in h: if h[word] == 2: res+=1 return res
3.5625
4
tests/test_player.py
ssichynskyi/lotti-karotti-calc
0
37155
<filename>tests/test_player.py<gh_stars>0 # -*- coding: utf-8 -*- import unittest from logic.player import Player class TestPlayer(unittest.TestCase): """ Collection of unittests for Player class """ def setUp(self): pass def test_player_init(self): player = Player(player_id=1, ra...
3.5
4
listcord/autoposter.py
Rishiraj0100/listcord.py
0
37156
from typing import Callable, Mapping, TypedDict import asyncio, aiohttp, discord class Options(TypedDict): interval: int start: bool class AutoPoster(): token: str interval: int bot: discord.Client stopped: bool _events: Mapping[str, Callable] def __init__(self, token: str, bot: dis...
2.515625
3
sols/190.py
Paul11100/LeetCode
0
37157
<filename>sols/190.py class Solution: # Reverse Format String (Accepted), O(1) time and space def reverseBits(self, n: int) -> int: s = '{:032b}'.format(n)[::-1] return int(s, 2) # Bit Manipulation (Top Voted), O(1) time and space def reverseBits(self, n: int) -> int: ans = 0 ...
3.125
3
toolbox/database.py
AntoineOrsoni/running-to-the-moon
0
37158
<filename>toolbox/database.py import sqlite3 import contextlib import json from ast import literal_eval # Execute a single statement def execute_statement(command: str, filter: tuple): with contextlib.closing(sqlite3.connect('sqlite/statistics.db')) as db_connection: # auto-closes with db_connection: # aut...
2.859375
3
Challenge 1/solution.py
Rishit-dagli/Google-FooBar
5
37159
def count_frequency(a): freq = dict() for items in a: freq[items] = a.count(items) return freq def solution(data, n): frequency = count_frequency(data) for key, value in frequency.items(): if value > n: data = list(filter(lambda a: a != key, data)) ...
3.578125
4
tdd_busca_animal/setup/tests.py
Jefferson472/apredendo-django
0
37160
from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.chrome.options import Options from animais.models import Animal class AnimaisTestCase(LiveServerTestCase): def setUp(self): chrome_options = Options() chrome_options.add_argument('--headless') ...
2.34375
2
python/app/logconfig.py
brandond/obra-hacks
0
37161
import logging import os logging.basicConfig(level=os.environ.get('LOG_LEVEL', 'INFO'), format='[python %(name)s pid: %(process)d] %(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.info('{} imported'.format(__name__))
2.421875
2
xunit-autolabeler-v2/ast_parser/python/test_data/parser/nested_tags/nested_tags.py
GoogleCloudPlatform/repo-automation-playground
5
37162
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
1.507813
2
external/vcm/tests/test_xarray_utils.py
jacnugent/fv3net
5
37163
<reponame>jacnugent/fv3net<filename>external/vcm/tests/test_xarray_utils.py import dask import numpy as np import pytest import xarray as xr from vcm.xarray_utils import ( _repeat_dataarray, assert_identical_including_dtype, isclose, repeat, ) @pytest.mark.parametrize("use_dask", [False, True]) @pyte...
1.929688
2
Python3/Exercises/DictionaryMethods/dictionary_methods.py
norbertosanchezdichi/TIL
0
37164
<reponame>norbertosanchezdichi/TIL<filename>Python3/Exercises/DictionaryMethods/dictionary_methods.py inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1} print(f'{inventory =}') stock_list = inventory.copy() print(f'{stock_list =}') stock_list['hot cheetos'] = 25 stock_list.update({'cookie' : 18}) stoc...
3.546875
4
libs/DuckDuckGoImages.py
Valken/FenrirScreenshotManager
7
37165
<gh_stars>1-10 # # Direction modification of the original code by https://github.com/JorgePoblete/DuckDuckGoImages # - Added use_name and target_resolution # import re import io import os import json import uuid import shutil import random import requests from PIL import Image def download(query, folder='.', max_urls...
2.671875
3
Hackerrank/sherlockAndCost.py
nandani99/Hacktoberfest-1
255
37166
#!/bin/python3 import math import os import random import re import sys # Complete the cost function below. def cost(b): n=len(b) l, h = 0, 0 for i in range(1, n): l, h = (max(l, h + b[i - 1] - 1), max(l + b[i] - 1, h + abs(b[i] - b[i - 1]))) return max(l, h) if __name__ == '_...
3.265625
3
{{ cookiecutter.repo_name }}/app/config/config.py
ShilpaGopal/cookiecutter-ml-flask-serving
0
37167
import os import constants.constants as const SVC_NAME = const.SVC_NAME MODEL_CONFIG = { 'model_path': os.getenv('MODEL_PATH', 'data/model/crnn_model.h5') } LOGGER_CONFIG = { 'log_level': os.getenv('LOG_LEVEL', 'DEBUG'), 'log_handle': os.getenv('LOG_HANDLE', 'file'), 'log_path': os.getenv...
1.976563
2
archr/analyzers/datascout.py
trentn/archr
58
37168
import logging l = logging.getLogger("archr.analyzers.datascout") from ..errors import ArchrError from . import Analyzer # Keystone engine 0.9.2 (incorrectly) defaults to radix 16. so we'd better off only using 0x-prefixed integers from now. # See the related PR: https://github.com/keystone-engine/keystone/pull/382 ...
2.296875
2
main.py
Parzival32/e-Dnevnik_API
0
37169
from selenium import webdriver from selenium.webdriver.chrome.options import Options class api: def __init__(self,username, passowrd, path): self.username = username self.password = <PASSWORD> self.path = path loginFailed = 'Login failed' def auth(self): chrome_options = O...
3.125
3
tests/file_test_util.py
lyksdu/langmodels
9
37170
<reponame>lyksdu/langmodels from typing import List from unittest.mock import MagicMock def file_mock_with_lines(lines: List[str]): file_mock = MagicMock(spec=['__enter__', '__exit__']) handle1 = file_mock.__enter__.return_value handle1.__iter__.return_value = iter(map(lambda l: l + '\n', lines)) retu...
2.71875
3
capreolus/index/tests/test_index.py
AlexWang000/capreolus
1
37171
import pytest from capreolus.collection import Collection, DummyCollection from capreolus.index import Index from capreolus.index import AnseriniIndex from capreolus.tests.common_fixtures import tmpdir_as_cache, dummy_index def test_anserini_create_index(tmpdir_as_cache): index = AnseriniIndex({"_name": "anserin...
2.046875
2
noheavenbot/utils/database_config.py
Molanito13/noheaven-bot
3
37172
import logging try: from asyncpg import create_pool except ModuleNotFoundError: logging.warning('Database not set up, install asyncpg') from noheavenbot.utils.constants import EnvVariables class Database: @classmethod async def connect(cls): credentials = {'user': EnvVariables.get('DB_USER'...
2.09375
2
myapi/serializers.py
zchuhui/django-rest-framework-example
0
37173
from rest_framework import serializers from .models import Hero,Company class HeroSerializer(serializers.HyperlinkedModelSerializer): ''' 系列化 Hero model ''' class Meta: model = Hero fields = ('id','name','alias') class CompanySerializer(serializers.HyperlinkedModelSerializer): ...
2.390625
2
diplomacy/src/scripts/yamlizer.py
MaxStrange/nlp
1
37174
<filename>diplomacy/src/scripts/yamlizer.py """ This script takes a single message gathered from playdiplomacy.com as an input file and outputs a YAML version of it so that it can be used as an input file into the program. Usage: python3 yamlizer.py msg.txt (You can also feed it a list of files). NOTE: This script i...
3.46875
3
sdk/python/pulumi_alicloud/bastionhost/host_account_user_group_attachment.py
pulumi/pulumi-alicloud
42
37175
# 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 warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
2.203125
2
str10.py
ABHISHEKSUBHASHSWAMI/String-Manipulation
0
37176
<reponame>ABHISHEKSUBHASHSWAMI/String-Manipulation #Program to change a given string to a new string where the first and last chars have been exchanged. string=str(input("Enter a string :")) first=string[0] #store first index element of string in variable last=string[-1] ...
4.1875
4
setup.py
MailboxValidator/mailboxvalidator-python
9
37177
<gh_stars>1-10 import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="MailboxValidator", version="1.2.0", author="<EMAIL>", author_email="<EMAIL>", description="Email verification module for Python using MailboxValidator API. It validates if the email...
1.398438
1
tests/graphql/tasks/test_task_queries.py
kids-first/kf-api-release-coordinator
2
37178
import pytest from coordinator.api.models import Study, Task from coordinator.api.factories.release import ReleaseFactory ALL_TASKS = """ query ( $state: String, $createdBefore: Float, $createdAfter: Float, $orderBy:String ) { allTasks( state: $state, createdBefore: $createdBefore,...
2.203125
2
GuessMyNumber.py
AkeBoss-tech/GuessingGame
0
37179
import random print("\tWelcome to 'Guess My Number!'") # This stores the previous guesses and tells us whether they are right class oldGuesses(object): def __init__(self, low, high): # This is the initialization data self.guesses = [] self.low = low self.high = high ...
4.25
4
videojuegos/arcanoid/ball.py
joseluisGA/videojuegos
0
37180
<reponame>joseluisGA/videojuegos<gh_stars>0 import pygame from settings import * from pygame import Vector2 import random from brick import Brick class Ball(pygame.sprite.Sprite): def __init__(self, x, y, groups, ball_image, bounce_fx): pygame.sprite.Sprite.__init__(self, groups) #self.image = py...
3.078125
3
config/tools/export.py
ghjinlei/one_mmorpg
0
37181
#!/usr/bin/env python3 #coding:utf-8 import os, sys from sys import exit from utils.excel import read_excel_data import utils.path as utils_path from utils.logger import Logger os.chdir(utils_path.TOOLS_ROOT_PATH) key_map = { "cmd" : "string", "lang" : "string", "script" : "s...
2.5625
3
src/compiler/plans.py
fritzo/pomagma
10
37182
<gh_stars>1-10 import math from pomagma.compiler.expressions import Expression_1 from pomagma.compiler.util import log_sum_exp, memoize_make, set_with def assert_in(element, set_): assert element in set_, (element, set_) def assert_not_in(element, set_): assert element not in set_, (element, set_) def as...
2.25
2
ossim/synchro/urls.py
devil-r/Os-simulator
0
37183
from django.conf.urls import url,include from django.contrib import admin from . import views app_name = 'synchro' urlpatterns =[ url(r'^semaphores/$', views.semaphores, name='semaphores'), url(r'^socket/$', views.socket, name='socket'), url(r'^deadlocks/$', views.deadlocks, name='deadlocks'), ...
1.648438
2
pySpectralFPK/__init__.py
alanmatzumiya/Paper
2
37184
<reponame>alanmatzumiya/Paper """ Solvers define how a pde is solved, i.e., advanced in time. .. autosummary:: .. codeauthor:: <NAME> <<EMAIL>> """ from typing import List from .setup_solver import FPK_solver __all__ = [ "FPK_solver" ]
1.242188
1
style/predict/servable/base.py
imagination-ai/kerem-side-projects-monorepo
0
37185
<reponame>imagination-ai/kerem-side-projects-monorepo from abc import ABC, abstractmethod import dill class BaseServable(ABC): SCHEMA_SLUG = "schema.json" MODEL_TYPE: str MODEL_VARIANT: str def __init__(self, model): self.model = model @abstractmethod def export(self, path): ...
2.203125
2
bot/Bot.py
Facco98/TwitchBotPy
1
37186
import websocket from threading import Thread from bot.Command import Command import time class Bot: def __init__(self, username, password, host): self.__commands = dict() self._username = username self._password = password self.__host = host self.__threadStarted = False ...
2.859375
3
test_python_toolbox/test_cheat_hashing.py
hboshnak/python_toolbox
119
37187
<reponame>hboshnak/python_toolbox # Copyright 2009-2017 <NAME>. # This program is distributed under the MIT license. '''Testing module for `python_toolbox.abc_tools.AbstractStaticMethod`.''' import copy from python_toolbox.cheat_hashing import cheat_hash def test_cheat_hash(): '''Test `cheat_hash` on various o...
2.453125
2
TikiBot/dispensing_screen.py
schuetzi99/TikiBot
0
37188
try: # Python 2 from Tkinter import * # noqa except ImportError: # Python 3 from tkinter import * # noqa import time from rectbutton import RectButton from serial_connection import SerialConnection UPDATE_MS = 20 DISPLAY_MS = 125 class DispensingScreen(Frame): def __init__(self, master, recipe, amo...
2.71875
3
0.1/game/maptest.py
icefoxen/games-drewfe
0
37189
<filename>0.1/game/maptest.py import pygame from pygame.locals import * from map import * a = Map( 'test.map' ) scr = pygame.display.set_mode( (400, 300) ) a.draw( scr, 0, 0, 400, 300 ) pygame.display.flip() #a.printTileset() while True: pass
2.59375
3
lib/n_queens_csp.py
ToniRV/Constraint-Satisfaction-Notebook
8
37190
<reponame>ToniRV/Constraint-Satisfaction-Notebook from __future__ import print_function import time import copy from lib.backtracking import backtracking_search from lib.csp import CSP def queen_constraint(A, a, B, b): """Constraint is satisfied (true) if A, B are really the same variable, or if they are not i...
3.609375
4
race_service/views/race_results.py
langrenn-sprint/race-service
0
37191
<filename>race_service/views/race_results.py """Resource module for race_results resources.""" import json import logging import os from typing import List, Union from aiohttp.web import ( HTTPNotFound, HTTPUnprocessableEntity, Response, View, ) from dotenv import load_dotenv from race_s...
2.25
2
01/hierarchy/company_management.py
MayaScarlet/runestone-pythonds3
0
37192
""" Class hierarchy for company management """ class Company: def __init__(self, company_name, location): self.company_name = company_name self.location = location def __str__(self): return f"Company: {self.company_name}, {self.location}" def __repr(self): return f"Company...
3.90625
4
config.example.py
isaacnoboa/balaguer_bot
0
37193
<filename>config.example.py # Make sure to rename this file as "config.py" before running the bot. verbose=True api_token='<KEY>' # Enter the user ID and a readable name for each user in your group. # TODO make balaguer automatically collect user IDs. # But that's only useful if the bot actually gathers wid...
2.1875
2
server/src/service/image/i_image_controller_service.py
konrad2508/picgal
4
37194
from abc import ABC, abstractmethod from model.image.data.count_data import CountData from model.image.data.image_data import ImageData from model.image.data.tag_data import TagData from model.image.data.virtual_tag_data import VirtualTagData from model.image.request.image_modification_request import ImageModification...
2.390625
2
Common/if_else.py
Heisenberg710/Python_Crash_Course
0
37195
# if语句 games = ['CS GO', 'wow', 'deathStranding'] for game in games: if game == 'wow': # 判断是否相等用'==' print(game.upper()) # 检查是否相等 sport = 'football' if sport == 'FOOTBALL': print('yes') else: print('No') # 此处输出结果为No说明大小写不同不被认同是同一string、转化为小写在进行对比 for game in games: if game.lower() == 'cs ...
4.125
4
src/favorites_crawler/itemloaders.py
RyouMon/FavoritesCrawler
2
37196
<reponame>RyouMon/FavoritesCrawler from itemloaders import ItemLoader from itemloaders.processors import Join, Compose, MapCompose from favorites_crawler import items from favorites_crawler.processors import take_first, identity, get_nhentai_id, original_url_from_nhentai_thumb_url from favorites_crawler.processors imp...
2.3125
2
preprocessed_data/RGHS/Code/LabStretching.py
SaiKrishna1207/Underwater-Image-Segmentation
0
37197
<gh_stars>0 import cv2 from skimage.color import rgb2hsv,hsv2rgb import numpy as np from skimage.color import rgb2lab, lab2rgb from global_StretchingL import global_stretching from global_stretching_ab import global_Stretching_ab def LABStretching(sceneRadiance): sceneRadiance = np.clip(sceneRadiance, 0, 255)...
2.25
2
cursecreatortests.py
kushtrimh/curse-of-tenebrae
0
37198
import unittest import mock import Tkinter from cursecreator import Application class TestNPCCreator(unittest.TestCase): def setUp(self): root = Tkinter.Tk() self.app = Application(root) def test_attribute_fixer(self): self.assertTrue(self.app.attribute_fixer("health", 0)) self.assertFalse(self.app.attribut...
2.859375
3
tools/check_encrypted_hash.py
airladon/ThisIGet
5
37199
<filename>tools/check_encrypted_hash.py import sys sys.path.insert(0, './app/app') from tools import decrypt, check_hash # noqa # sys.argv[1] = plain text # sys.argv[2] = hash to compare print(check_hash(sys.argv[1], decrypt(sys.argv[2])))
2.453125
2