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 |
|---|---|---|---|---|---|---|
iotest/case.py | gwk/iotest | 1 | 20400 | # Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.
import ast
import os
import re
import shlex
from itertools import zip_longest
from string import Template
from typing import *
from .pithy.fs import *
from .pithy.io import *
from .pithy.types import * # type: ignore
fro... | 2.125 | 2 |
aiophotoprism/__init__.py | zhulik/aiophotoprism | 4 | 20401 | <reponame>zhulik/aiophotoprism<filename>aiophotoprism/__init__.py
"""Asynchronous Python client for the Photoprism REST API."""
from .photoprism import API, Photoprism # noqa
| 1.046875 | 1 |
xen/xen-4.2.2/tools/python/scripts/test_vm_create.py | zhiming-shen/Xen-Blanket-NG | 1 | 20402 | #!/usr/bin/python
vm_cfg = {
'name_label': 'APIVM',
'user_version': 1,
'is_a_template': False,
'auto_power_on': False, # TODO
'memory_static_min': 64,
'memory_static_max': 128,
#'memory_dynamic_min': 64,
#'memory_dynamic_max': 128,
'VCPUs_policy': 'credit',
'VCPUs... | 1.640625 | 2 |
portfolyo/core/pfline/tests/test_single_helper.py | rwijtvliet/portfolyo | 0 | 20403 | <reponame>rwijtvliet/portfolyo<filename>portfolyo/core/pfline/tests/test_single_helper.py
from portfolyo import testing, dev
from portfolyo.core.pfline import single_helper
from portfolyo.tools.nits import Q_
from portfolyo.tools.stamps import FREQUENCIES
import pandas as pd
import pytest
def assert_w_q_compatible(fr... | 2.234375 | 2 |
gomill/mcts_tuners.py | BenisonSam/goprime | 0 | 20404 | """Competitions for parameter tuning using Monte-carlo tree search."""
from __future__ import division
import operator
import random
from heapq import nlargest
from math import exp, log, sqrt
from gomill import compact_tracebacks
from gomill import game_jobs
from gomill import competitions
from gomill import competi... | 2.578125 | 3 |
Leetcoding-Actions/Explore-Monthly-Challenges/2021-02/25-shortestUnsortedContinuousSubarray.py | shoaibur/SWE | 1 | 20405 | <reponame>shoaibur/SWE<filename>Leetcoding-Actions/Explore-Monthly-Challenges/2021-02/25-shortestUnsortedContinuousSubarray.py
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
'''
T: O(n log n) and S: O(1)
'''
n = len(nums)
sorted_nums = sorted... | 3.46875 | 3 |
endoscopic_ai.py | dennkitotaichi/AI_prediction_for_patients_with_colorectal_polyps | 0 | 20406 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import codecs
import lightgbm as lgb
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
# Read data
image_file_path = './simulated_dpc_d... | 2.65625 | 3 |
open-hackathon-tempUI/src/hackathon/config-sample.py | SpAiNiOr/LABOSS | 0 | 20407 | # "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# oauth constants
HOSTNAME = "http://hackathon.chinacloudapp.cn" # host name of the UI site
QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA
HACkATHON_API_ENDPOINT = ... | 1.695313 | 2 |
marocco/first.py | panos1998/Thesis_Code | 0 | 20408 | #%%
import sys
import numpy as np
from typing import Any, List
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
sys.path.append('C:/Users/panos/Documents/Διπλωματική/code/fz')
from arfftocsv import function_labelize
import csv
colnames =['age', 'sex', 'cp', 'trestbps', 'chol',
'fbs', 'restecg', 'thal... | 2.796875 | 3 |
matlab2cpp/datatype.py | emc2norway/m2cpp | 28 | 20409 | """
The follwing constructor classes exists here:
+------------------------------------------+---------------------------------------+
| Class | Description |
+==========================================+=======================================+
| :py:class:`~... | 1.875 | 2 |
src/the_impossible/live/migrations/newsletter/migrations/0002_auto_20200514_1518.py | micha31r/The-Impossible | 0 | 20410 | <gh_stars>0
# Generated by Django 2.2.7 on 2020-05-14 03:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('newsletter', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Newsletter',
new_name='Subscrib... | 1.554688 | 2 |
resident/views.py | felipeue/SmartBuilding | 0 | 20411 | <gh_stars>0
from django.views.generic import TemplateView
from main.permissions import ResidentLoginRequiredMixin
class DashboardView(ResidentLoginRequiredMixin, TemplateView):
template_name = "index_dashboard.html"
| 1.28125 | 1 |
src/awspfx/awspfx.py | exfi/awspfx | 1 | 20412 | #!/usr/bin/env python3
"""awspfx
Usage:
awspfx.py <profile>
awspfx.py [(-c | --current) | (-l | --list) | (-s | --swap)]
awspfx.py token [(-p | --profile) <profile>]
awspfx.py sso [(login | token)] [(-p | --profile) <profile>]
awspfx.py -h | --help
awspfx.py --version
Examples:
awspfx.py ... | 2.25 | 2 |
test/test_contacts_info_from_main_page.py | OlgaZtv/python_training | 0 | 20413 | <reponame>OlgaZtv/python_training<filename>test/test_contacts_info_from_main_page.py
import re
from model.contact import Contact
def test_contact_info_from_home_page(app, db):
app.navigation.open_home_page()
contact_from_home_page = sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
def clean(... | 3.1875 | 3 |
Leetcode/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/solution1.py | asanoviskhak/Outtalent | 51 | 20414 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or not... | 3.609375 | 4 |
benchmark.py | raonyguimaraes/machinelearning | 1 | 20415 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Writing Our First Classifier - Machine Learning Recipes #5
#https://www.youtube.com/watch?v=AoeEHqVSNOw&list=PLOU2XLYxmsIIuiBfYad6rFYQU_jL2ryal&index=1
from scipy.spatial import distance
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accu... | 2.875 | 3 |
process_frames.py | w-garcia/video-caption.pytorch | 4 | 20416 | """
Re-tooled version of the script found on VideoToTextDNN:
https://github.com/OSUPCVLab/VideoToTextDNN/blob/master/data/process_frames.py
"""
import sys
import os
import argparse
import time
from multiprocessing import Pool
def main(args):
src_dir = args.src_dir
dst_dir = args.dst_dir
start = int(args.s... | 2.359375 | 2 |
plaintext_password/checks.py | bryanwills/django-plaintext-password | 0 | 20417 | from django.contrib.auth.hashers import get_hashers_by_algorithm
from django.core import checks
@checks.register(checks.Tags.security, deploy=True)
def check_for_plaintext_passwords(app_configs, **kwargs):
if "plaintext" in get_hashers_by_algorithm():
yield checks.Critical(
"Plaintext module s... | 1.859375 | 2 |
city.py | cromermw/gen_pop | 0 | 20418 | <reponame>cromermw/gen_pop
class City:
name = "city"
size = "default"
draw = -1
danger = -1
population = [] | 1.28125 | 1 |
code/preprocess/data_generation.py | hms-dbmi/VarPPUD | 0 | 20419 | <reponame>hms-dbmi/VarPPUD
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 17:19:39 2021
@author: rayin
"""
import os, sys
import numpy as np
import pandas as pd
import torch
import warnings
import random
import torchvision.models as models
from sdv.tabular import CTGAN
from sdv.evaluation i... | 1.765625 | 2 |
app/user/models.py | briankaemingk/streaks-with-todoist | 3 | 20420 | from app.extensions import db
from flask import current_app
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
access_token = db.Column(db.String())
jit_feature = db.Column(db.Boolean())
recurrence_resch_feature = db.Column(db.Boolean())
streaks_feature ... | 2.203125 | 2 |
output/models/boeing_data/ipo4/ipo_xsd/address.py | tefra/xsdata-w3c-tests | 1 | 20421 | from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
from output.models.boeing_data.ipo4.ipo_xsd.ipo import AddressType
__NAMESPACE__ = "http://www.example.com/IPO"
class Usstate(Enum):
AK = "AK"
AL = "AL"
AR = "AR"
CA = "CA"
PA = "PA"
@dataclass
class Ukad... | 2.796875 | 3 |
Invaders/Displays/animation_display.py | JaredsGames/SpaceInvaders | 0 | 20422 | # <NAME>
# CPSC 386-01
# 2021-11-29
# <EMAIL>
# @JaredDyreson
#
# Lab 00-04
#
# Some filler text
#
"""
This module contains the Intro display class
"""
import pygame
import functools
import sys
import pathlib
import typing
import os
import dataclasses
import random
from pprint import pprint as pp
import time
from In... | 2.859375 | 3 |
ledger/checkout/models.py | jawaidm/ledger | 59 | 20423 | from oscar.apps.checkout.models import * # noqa
| 1.03125 | 1 |
api/serializers.py | mariomtzjr/podemos_test | 0 | 20424 | <filename>api/serializers.py
from rest_framework import serializers
from apps.calendarioPago.models import CalendarioPago
from apps.cliente.models import Cliente
from apps.cuenta.models import Cuenta
from apps.grupo.models import Grupo
from apps.miembro.models import Miembro
from apps.transaccion.models import Transac... | 2.328125 | 2 |
emmet/markup/format/html.py | emmetio/py-emmet | 29 | 20425 | <reponame>emmetio/py-emmet
import re
from .walk import walk, WalkState
from .utils import caret, is_inline_element, is_snippet, push_tokens, should_output_attribute
from .comment import comment_node_before, comment_node_after, CommentWalkState
from ...abbreviation import Abbreviation, AbbreviationNode, AbbreviationAttr... | 2.359375 | 2 |
secant_method.py | FixingMind5/proyecto_metodos_I | 0 | 20426 | <gh_stars>0
"""Secant Method module"""
from numeric_method import NumericMethod
class SecantMethod(NumericMethod):
"""Secant method class"""
def secant_method(self, previous_value, value):
"""The secant method itself
@param previous_value: first value of interval
@param previous_valu... | 3.671875 | 4 |
variables.py | bestend/korquad | 1 | 20427 | import os
import re
MODEL_FILE_FORMAT = 'weights.{epoch:02d}-{val_loss:.2f}.h5'
MODEL_REGEX_PATTERN = re.compile(r'^.*weights\.(\d+)\-\d+\.\d+\.h5$')
LAST_MODEL_FILE_FORMAT = 'last.h5'
TEAMS_WEBHOOK_URL = os.environ.get('TEAMS_WEBHOOK_URL', '') | 2.015625 | 2 |
svm.py | sciencementors2019/Image-Processer | 0 | 20428 | <filename>svm.py<gh_stars>0
import numpy as np
import pandas as pd
from sklearn import svm
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
# Create arbitrary dataset for example
df = pd.DataFrame({'Planned_End': np.random.uniform(low=-5, high=5, size=50),
'Actual_... | 3.234375 | 3 |
tests/importing/test_read_genes.py | EKingma/Transposonmapper | 2 | 20429 | <filename>tests/importing/test_read_genes.py<gh_stars>1-10
from transposonmapper.importing import (
load_default_files,read_genes
)
def test_output_format():
a,b,c=load_default_files(gff_file=None,essentials_file=None,gene_names_file=None)
a_0,b_0,c_0=read_genes(gff_file=a,essentials_file=b,gene_names_fil... | 2.640625 | 3 |
src/apps/tractatusapp/views_spacetree.py | lambdamusic/wittgensteiniana | 1 | 20430 | <reponame>lambdamusic/wittgensteiniana
"""
Using
http://thejit.org/static/v20/Docs/files/Options/Options-Canvas-js.html#Options.Canvas
"""
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
import json
... | 2.375 | 2 |
vumi/blinkenlights/metrics_workers.py | apopheniac/vumi | 0 | 20431 | # -*- test-case-name: vumi.blinkenlights.tests.test_metrics_workers -*-
import time
import random
import hashlib
from datetime import datetime
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
... | 2.0625 | 2 |
src/sentry/web/forms/base_organization_member.py | JannKleen/sentry | 1 | 20432 | from __future__ import absolute_import
from django import forms
from django.db import transaction
from sentry.models import (
OrganizationMember,
OrganizationMemberTeam,
Team,
)
class BaseOrganizationMemberForm(forms.ModelForm):
"""
Base form used by AddOrganizationMemberForm, InviteOrganization... | 2 | 2 |
turbinia/workers/fsstat.py | dfjxs/turbinia | 1 | 20433 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2021 Google Inc.
#
# 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 ... | 2.140625 | 2 |
app/django-doubtfire-api/endpoint/urls.py | JiatengTao/speaker-verification-api | 0 | 20434 | <filename>app/django-doubtfire-api/endpoint/urls.py
from django.urls import include, path
from django.conf.urls import url
from endpoint.views import (
enroll_user,
validate_recording,
check_redis_health,
redirect_flower_dashboard,
)
urlpatterns = [
path("enroll", enroll_user),
path("validate",... | 1.71875 | 2 |
back/src/crud.py | Celeo/wiki_elm | 0 | 20435 | from datetime import datetime
from typing import List, Optional
import bcrypt
from sqlalchemy.orm import Session
from . import models, schemas
def get_user(db: Session, id: int) -> models.User:
"""Return a single user by id.
Args:
db (Session): database connection
id (int): id of the user
... | 3.09375 | 3 |
commands/cmd_invite.py | cygnus-dev/python01 | 0 | 20436 | <filename>commands/cmd_invite.py
async def run(ctx):
await ctx.send(''' `bot invite link:`
<https://discord.com/api/oauth2/authorize?client_id=732933945057869867&permissions=538569921&scope=bot>''') | 2.0625 | 2 |
polymorphic/tests/test_utils.py | likeanaxon/django-polymorphic | 1 | 20437 | <filename>polymorphic/tests/test_utils.py
from django.test import TransactionTestCase
from polymorphic.models import PolymorphicModel, PolymorphicTypeUndefined
from polymorphic.tests.models import (
Enhance_Base,
Enhance_Inherit,
Model2A,
Model2B,
Model2C,
Model2D,
)
from polymorphic.utils impo... | 2.234375 | 2 |
blockchain/utils.py | TheEdgeOfRage/blockchain | 0 | 20438 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 <<EMAIL>>
#
# Distributed under terms of the BSD 3-Clause license.
import hashlib
import itertools
import json
from decimal import Decimal
from multiprocessing import (
cpu_count,
Pool,
Process,
Queue
)
class DecimalJsonEncoder(... | 2.421875 | 2 |
myfunds/web/views/joint_limits/limit/views/participants.py | anzodev/myfunds | 0 | 20439 | <filename>myfunds/web/views/joint_limits/limit/views/participants.py<gh_stars>0
import peewee as pw
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from myfunds.core.models import Account
from myfunds.core.models import Category
from ... | 2.203125 | 2 |
elyra/pipeline/component_parser_kfp.py | rachaelhouse/elyra | 0 | 20440 | #
# Copyright 2018-2021 Elyra Authors
#
# 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 writ... | 2.203125 | 2 |
mayan/apps/mimetype/apps.py | eshbeata/open-paperless | 2,743 | 20441 | from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from common import MayanAppConfig
from .licenses import * # NOQA
class MIMETypesApp(MayanAppConfig):
name = 'mimetype'
verbose_name = _('MIME types')
def ready(self, *args, **kwargs):
super(MIMETyp... | 1.492188 | 1 |
test/level.py | Matt-London/command-line-tutorial | 1 | 20442 | from packages.levels.Level import Level
import packages.levels.levels as Levels
import packages.resources.functions as function
import packages.resources.variables as var
from packages.filesystem.Directory import Directory
from packages.filesystem.File import File
var.bash_history = ("Check")
test = Level("Instruct",... | 1.976563 | 2 |
tests/test_buffers.py | TheCharmingCthulhu/cython-vst-loader | 23 | 20443 | # noinspection PyUnresolvedReferences
import unittest
from cython_vst_loader.vst_loader_wrapper import allocate_float_buffer, get_float_buffer_as_list, \
free_buffer, \
allocate_double_buffer, get_double_buffer_as_list
class TestBuffers(unittest.TestCase):
def test_float_buffer(self):
pointer = ... | 2.53125 | 3 |
samples/17.multilingual-bot/translation/microsoft_translator.py | hangdong/botbuilder-python | 0 | 20444 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import uuid
import requests
class MicrosoftTranslator:
def __init__(self, subscription_key: str, subscription_region: str):
self.subscription_key = subscription_key
self.subscription_region = subscriptio... | 2.703125 | 3 |
dachar/utils/__init__.py | roocs/dachar | 2 | 20445 | <filename>dachar/utils/__init__.py
from .common import *
from .json_store import *
| 1.132813 | 1 |
scraper/models.py | mrcnc/assessor-scraper | 0 | 20446 | <filename>scraper/models.py<gh_stars>0
# -*- coding: utf-8 -*-
import os
import logging
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from scraper import se... | 2.578125 | 3 |
WeIrD-StRiNg-CaSe.py | lovefov/Python | 0 | 20447 | <filename>WeIrD-StRiNg-CaSe.py
def to_weird_case(string):
arr=string.split()
count=0
for i in arr:
tmp=list(i)
for j in range(len(tmp)):
if j%2==0:
tmp[j]=tmp[j].upper()
arr[count] = ''.join(tmp)
count+=1
return ' '.join(arr)
'''
一个比较不错的版本
d... | 3.875 | 4 |
FTP_client/LHYlearning/Entry.py | welles2000/CCNProject | 2 | 20448 | # 经典面向对象的GUI写法
from tkinter import *
from tkinter import messagebox
class Application(Frame):
"""一个经典的GUI程序"""
def __init__(self,master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""创建组件"""
... | 3.8125 | 4 |
curso-em-video/ex054.py | joseluizbrits/sobre-python | 0 | 20449 | # Grupo da Maioridade
'''Crie um programa que leia o ANO DE NASCIMENTO de
SETE PESSOAS. No final, mostre quantas pessoas ainda
não atingiram a maioridade e quantas já são maiores'''
from datetime import date
anoatual = date.today().year # Pegará o ano atual configurado na máquina
totalmaior = 0
totalmenor = 0
for pess... | 4.09375 | 4 |
stellar/simulation/data.py | strfx/stellar | 0 | 20450 | from typing import Tuple
import numpy as np
import png
from skimage.transform import resize
def load_world(filename: str, size: Tuple[int, int], resolution: int) -> np.array:
"""Load a preconstructred track to initialize world.
Args:
filename: Full path to the track file (png).
... | 3.1875 | 3 |
apps/user/serializers.py | major-hub/soil_app | 0 | 20451 | <reponame>major-hub/soil_app
from rest_framework import serializers
from user.models import User
from main.exceptions.user_exceptions import UserException
user_exception = UserException
class UserRegisterSerializer(serializers.ModelSerializer):
password_confirmation = serializers.CharField(max_length=128)
... | 2.671875 | 3 |
bf_compiler.py | PurpleMyst/bf_compiler | 31 | 20452 | <filename>bf_compiler.py<gh_stars>10-100
#!/usr/bin/env python3
import argparse
import ctypes
import os
import sys
from llvmlite import ir, binding as llvm
INDEX_BIT_SIZE = 16
def parse(bf):
bf = iter(bf)
result = []
for c in bf:
if c == "[":
result.append(parse(bf))
elif c ... | 2.78125 | 3 |
dapbench/record_dap.py | cedadev/dapbench | 0 | 20453 | <gh_stars>0
#!/usr/bin/env python
# BSD Licence
# Copyright (c) 2011, Science & Technology Facilities Council (STFC)
# All rights reserved.
#
# See the LICENSE file in the source distribution of this software for
# the full license text.
"""
Execute a programme that makes NetCDF-API OPeNDAP calls, capturing
request eve... | 2.296875 | 2 |
kesko_webapp/models.py | kounelisagis/kesko-food-waste-hackathon | 1 | 20454 | <filename>kesko_webapp/models.py
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Article(models.Model):
"""
Models available articles
"""
name = models.CharField(max_length=200)
serial_id =... | 2.21875 | 2 |
source/prosumer.py | gus0k/LEMsim | 0 | 20455 | <filename>source/prosumer.py
"""
Prosumer class, extendes the battery controler
"""
import numpy as np
from source.batterycontroller import BatteryController
class Prosumer(BatteryController):
def __init__(self, owner_id, b_max, b_min, eff_c, eff_d, d_max, d_min, price_buy, price_sell, load, expected_price_bu... | 2.8125 | 3 |
tests/calculations/test_inner_goals_regression.py | frc1678/server-2021-public | 0 | 20456 | <reponame>frc1678/server-2021-public
#!/usr/bin/env python3
# Copyright (c) 2019 FRC Team 1678: Citrus Circuits
import pytest
import numpy as np
import os, sys
current_directory = os.path.dirname(os.path.realpath(__file__))
parent_directory = os.path.dirname(current_directory)
grandparent_directory = os.path.dirname(p... | 2.28125 | 2 |
trove/tests/unittests/taskmanager/test_galera_clusters.py | a4913994/openstack_trove | 244 | 20457 | <reponame>a4913994/openstack_trove
# Copyright [2015] Hewlett-Packard Development Company, L.P.
# 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
#
... | 1.664063 | 2 |
AStyleTest/file-py/locale_enum_i18n.py | a-w/astyle | 0 | 20458 | <reponame>a-w/astyle<filename>AStyleTest/file-py/locale_enum_i18n.py
#! /usr/bin/python
""" Enumerate selected locales and sort by codepage to determine
which languages the locales support.
"""
# to disable the print statement and use the print() function (version 3 format)
from __future__ import print_function
... | 2.859375 | 3 |
src/Coord_cmd.py | aembillo/MNWellRecordGui | 0 | 20459 | """ 2015-07-23
Perform coordinate conversions from the command line.
Uses
"""
import argparse
import pyperclip
# p1 = argparse.ArgumentParser()
# p1.add_argument('x')
# print p1.parse_args(['123'])
#
# p2 = argparse.ArgumentParser()
# p2.add_argument('-d', action='store_const',const='dak')
# print p2.p... | 3.140625 | 3 |
contest/abc106/A.py | mola1129/atcoder | 0 | 20460 | A, B = map(int, input().split())
print((A - 1) * (B - 1))
| 2.625 | 3 |
pythonmisc/string_manipulation.py | davikawasaki/python-misc-module-library | 0 | 20461 | #! /usr/bin/env python
# Version: 0.1.1
import re
def convert_ws_header_vb_attributes(df):
output_txt = ""
for key in df.keys():
variant_array = "\'Dim "
i = 0
for word in [w.capitalize().replace('\t', '') for w in str(key).lower().split("(")[0].split(" ")]:
if i == 0:
... | 3.125 | 3 |
ALLCools/clustering/incremental_pca.py | mukamel-lab/ALLCools | 5 | 20462 | import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import IncrementalPCA as _IncrementalPCA
from ..count_matrix.zarr import dataset_to_array
def _normalize_per_cell(matrix, cell_sum):
print('normalize per cell to CPM')
if cell_sum is None:
... | 2.515625 | 3 |
wordcount/views.py | chinya07/Django-wordcount | 0 | 20463 | <filename>wordcount/views.py
from django.http import HttpResponse
from django.shortcuts import render
import operator
def home(request):
return render(request, 'home.html')
def count(request):
fulltext1=request.GET['fulltext1']
fulltext2=request.GET['fulltext2']
wordlist1=fulltext1.split(' '... | 2.578125 | 3 |
example/06-modules/modules.py | iten-engineering/python | 0 | 20464 | <filename>example/06-modules/modules.py
# =============================================================================
# Python examples - modules
# =============================================================================
# -----------------------------------------------------------------------------
# Module
# ... | 2.765625 | 3 |
.github/docker/checker_image/scripts/check_copyright_headers.py | TomasRejhons/siren | 0 | 20465 | <filename>.github/docker/checker_image/scripts/check_copyright_headers.py
#!/usr/bin/env python
#
# MIT License
#
# Copyright (c) 2021 silicon-village
#
# 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 th... | 2.015625 | 2 |
setup.py | finsberg/scholar_bot | 0 | 20466 | <reponame>finsberg/scholar_bot
# -*- coding: utf-8 -*-
import os
import sys
import platform
import glob
from setuptools import setup, find_packages, Command
if sys.version_info < (3, 6):
print("Python 3.6 or higher required, please upgrade.")
sys.exit(1)
version = "0.1"
name = "scholar_bot"
description = (... | 2.171875 | 2 |
time_series_rnn_without_wrapper.py | KT12/hands_on_machine_learning | 0 | 20467 | # Predict time series w/o using OutputProjectWrapper
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Create time series
t_min, t_max = 0, 30
resolution = 0.1
def time_series(t):
return t * np.sin(t) / 3 + 2 * np.sin(t * 5)
def next_batch(batch_size, n_steps):
t0 = np.random.rand... | 2.84375 | 3 |
pydocteur/actions.py | AFPy/PyDocTeur | 4 | 20468 | <filename>pydocteur/actions.py
import json
import logging
import os
import random
import time
from functools import lru_cache
from github import Github
from github import PullRequest
from pydocteur.github_api import get_commit_message_for_merge
from pydocteur.github_api import get_trad_team_members
from pydocteur.pr_... | 2.203125 | 2 |
visualise.py | ksang/fiery | 0 | 20469 | import os
from argparse import ArgumentParser
from glob import glob
import cv2
import numpy as np
import torch
import torchvision
import matplotlib as mpl
import matplotlib.pyplot as plt
from PIL import Image
from fiery.trainer import TrainingModule
from fiery.utils.network import NormalizeInverse
from fiery.utils.in... | 2.15625 | 2 |
autoelective/util.py | apomeloYM/PKUAutoElective | 0 | 20470 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: util.py
import os
import csv
from copy import deepcopy
import hashlib
from functools import wraps
from collections import OrderedDict
from ._compat import json, JSONDecodeError
from .exceptions import NoInstanceError, ImmutableTypeError, ReadonlyPr... | 2.09375 | 2 |
reference_data/uk_biobank_v3/1_extract_ukb_variables.py | thehyve/genetics-backend | 6 | 20471 | <filename>reference_data/uk_biobank_v3/1_extract_ukb_variables.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# <NAME>
#
"""
bsub -q small -J interactive -n 1 -R "select[mem>8000] rusage[mem=8000] span[hosts=1]" -M8000 -Is bash
"""
import gzip
import sys
def main():
# Args
in_ukb = '/nfs/users/nfs_e/em21... | 2.5 | 2 |
main.py | Staubtornado/juliandc | 0 | 20472 | import asyncio
import discord
from discord.ext import commands, tasks
import os
import random
import dotenv
import difflib
import configparser
###
version = '4.0.0'
###
bot = commands.Bot(command_prefix = '!', owner_id = 272446903940153345, intents = discord.Intents.all())
bot.remove_command('help')
co... | 2.09375 | 2 |
lib/utils.py | MusaTamzid05/simple_similar_image_lib | 0 | 20473 | import tensorflow as tf
import numpy as np
def euclidean_dist(x, y):
return np.linalg.norm(x - y)
def limit_gpu():
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
tf.config.set_logical_device_configuration(
gpus[0],
[tf.config.Logic... | 2.71875 | 3 |
dataloaders/voc.py | psui3905/CCT | 308 | 20474 | from base import BaseDataSet, BaseDataLoader
from utils import pallete
import numpy as np
import os
import scipy
import torch
from PIL import Image
import cv2
from torch.utils.data import Dataset
from torchvision import transforms
import json
class VOCDataset(BaseDataSet):
def __init__(self, **kwargs):
sel... | 2.40625 | 2 |
FWCore/Integration/test/ThinningTest1_cfg.py | gputtley/cmssw | 6 | 20475 | <filename>FWCore/Integration/test/ThinningTest1_cfg.py
# This process is the first step of a test that involves multiple
# processing steps. It tests the thinning collections and
# redirecting Refs, Ptrs, and RefToBases.
#
# Produce 15 thinned collections
#
# Collection A contains Things 0-8
# Collection B contains... | 2.28125 | 2 |
tests/Bio/test_tandem.py | iwasakishuto/Keras-Imitation | 4 | 20476 | # coding: utf-8
from kerasy.Bio.tandem import find_tandem
from kerasy.utils import generateSeq
len_sequences = 1000
def get_test_data():
sequence = generateSeq(size=len_sequences,
nucleic_acid='DNA',
weights=None,
seed=123)
seque... | 2.640625 | 3 |
NEW_PRAC/HackerRank/Python/SetDifferenceString.py | side-projects-42/INTERVIEW-PREP-COMPLETE | 13 | 20477 | <filename>NEW_PRAC/HackerRank/Python/SetDifferenceString.py<gh_stars>10-100
# >>> s = set("Hacker")
# >>> print s.difference("Rank")
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(set(['R', 'a', 'n', 'k']))
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(['R', 'a', 'n', 'k'])
# set(['c', 'r', 'e', 'H'])
#... | 3.25 | 3 |
src/dotacrunch/drawer.py | tpinetz/dotacrunch | 1 | 20478 | from PIL import Image, ImageDraw
from numpy import array, random, vstack, ones, linalg
from const import TOWERS
from copy import deepcopy
from os import path
class MapDrawer:
"""
a class for drawing Dota2Maps with replay-parsed data
"""
def __init__(self, towers, received_tables):
... | 2.703125 | 3 |
nsm.py | svepe/neural-stack | 0 | 20479 | import numpy as np
import chainer.functions as F
from chainer import Variable
def neural_stack(V, s, d, u, v):
# strengths
s_new = d
for t in reversed(xrange(s.shape[1])):
x = s[:, t].reshape(-1, 1) - u
s_new = F.concat((s_new, F.maximum(Variable(np.zeros_like(x.data)), x)))
u = F.... | 2.65625 | 3 |
chaos_genius/celery_config.py | eltociear/chaos_genius | 1 | 20480 | <filename>chaos_genius/celery_config.py<gh_stars>1-10
from datetime import timedelta
from celery.schedules import crontab, schedule
CELERY_IMPORTS = ("chaos_genius.jobs")
CELERY_TASK_RESULT_EXPIRES = 30
CELERY_TIMEZONE = "UTC"
CELERY_ACCEPT_CONTENT = ["json", "msgpack", "yaml"]
CELERY_TASK_SERIALIZER = "json"
CELERY... | 2.109375 | 2 |
speaksee/data/utils.py | aimagelab/speaksee | 29 | 20481 |
def get_tokenizer(tokenizer):
if callable(tokenizer):
return tokenizer
if tokenizer == "spacy":
try:
import spacy
spacy_en = spacy.load('en')
return lambda s: [tok.text for tok in spacy_en.tokenizer(s)]
except ImportError:
print("Please in... | 3.15625 | 3 |
oldcontrib/media/image/servee_registry.py | servee/django-servee-oldcontrib | 0 | 20482 | from servee import frontendadmin
from servee.frontendadmin.insert import ModelInsert
from oldcontrib.media.image.models import Image
class ImageInsert(ModelInsert):
model = Image
frontendadmin.site.register_insert(ImageInsert) | 1.515625 | 2 |
run.py | Lohitapallanti/Predicting-Titanic-Survive | 0 | 20483 | from train import train
from processing import Processing
""" The Main run file, where the program execution and controller is based. """
class Run(train, Processing):
def final_function(self):
print('This project predicts the persons who will survive if the same RMS Titanic ')
print('incident h... | 3.59375 | 4 |
scripts/pretty-printers/gdb/install.py | tobireinhard/cbmc | 412 | 20484 | <gh_stars>100-1000
#!/usr/bin/env python3
import os
from shutil import copyfile
def create_gdbinit_file():
"""
Create and insert into a .gdbinit file the python code to set-up cbmc pretty-printers.
"""
print("Attempting to enable cbmc-specific pretty-printers.")
home_folder = os.path.expanduser... | 2.8125 | 3 |
pyutils/solve.py | eltrompetero/maxent_fim | 0 | 20485 | <filename>pyutils/solve.py
# ====================================================================================== #
# Module for solving maxent problem on C elegans data set.
#
# Author : <NAME>, <EMAIL>
# ====================================================================================== #
from .utils import *
f... | 2.828125 | 3 |
lingvo/tasks/car/ops/nms_3d_op_test.py | Singed-jj/lingvo | 0 | 20486 | <reponame>Singed-jj/lingvo<gh_stars>0
# Lint as: python3
# Copyright 2019 The TensorFlow 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.apach... | 1.617188 | 2 |
BDS_2nd_downsampling.py | oxon-612/BDSR | 1 | 20487 | <reponame>oxon-612/BDSR
#第二次降采样使用的代码
import numpy as np
import random
# import sys
import os
from sklearn import preprocessing
# import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import Axes3D
# import math
from scipy.stats import norm
# from sklearn.neighbors import KernelDensity
# import statisti... | 2.96875 | 3 |
model.py | e-yi/hin2vec_pytorch | 18 | 20488 | import torch
import numpy as np
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
def binary_reg(x: torch.Tensor):
# forward: f(x) = (x>=0)
# backward: f(x) = sigmoid
a = torch.sigmoid(x)
b = a.detach()
c = (x.detach() >= 0).float()
return a - b + c
class HIN2vec(nn.Module... | 2.78125 | 3 |
pygrep/classes/boyerMoore.py | sstadick/pygrep | 0 | 20489 | <gh_stars>0
import string
from helpers import *
class BoyerMoore(object):
""" Encapsulates pattern and associated Boyer-Moore preprocessing. """
def __init__(self, pattern, alphabet=string.ascii_letters + string.whitespace + string.punctuation):
self.pattern = pattern
self.patternLen = len(pa... | 3.1875 | 3 |
basicts/archs/DGCRN_arch/__init__.py | zezhishao/GuanCang_BasicTS | 3 | 20490 | from basicts.archs.DGCRN_arch.DGCRN_arch import DGCRN | 1.023438 | 1 |
kido/settings/production.example.py | alanhamlett/kid-o | 34 | 20491 | SECRET_KEY = None
DB_HOST = "localhost"
DB_NAME = "kido"
DB_USERNAME = "kido"
DB_PASSWORD = "<PASSWORD>"
COMPRESSOR_DEBUG = False
COMPRESSOR_OFFLINE_COMPRESS = True
| 1.0625 | 1 |
run.py | Prakash2403/ultron | 13 | 20492 | #! /usr/bin/python3
from default_settings import default_settings
from ultron_cli import UltronCLI
if __name__ == '__main__':
default_settings()
try:
UltronCLI().cmdloop()
except KeyboardInterrupt:
print("\nInterrupted by user.")
print("Goodbye")
exit(0)
| 1.984375 | 2 |
losses/dice_loss.py | CharlesAuthier/geo-deep-learning | 121 | 20493 | import torch
import torch.nn as nn
import torch.nn.functional as F
def soft_dice_score(
output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None) -> torch.Tensor:
assert output.size() == target.size()
if dims is not None:
intersection = torch.sum(output * t... | 2.796875 | 3 |
src/pytezos/jupyter.py | konchunas/pytezos | 98 | 20494 | import inspect
import re
from functools import update_wrapper
from typing import Optional
def is_interactive() -> bool:
try:
_ = get_ipython().__class__.__name__ # type: ignore
return True
except NameError:
return False
def get_attr_docstring(class_type, attr_name) -> Optional[str]:... | 2.4375 | 2 |
torch_template/training.py | dongqifong/inspiration | 0 | 20495 | import torch
def train_one_epoch(model, train_loader, loss_func, optimizer):
model.train()
running_loss = 0.0
for batch_idx, (x, y) in enumerate(train_loader):
out = model(x)
optimizer.zero_grad()
loss = loss_func(out, y)
loss.backward()
optimizer.step()
run... | 2.53125 | 3 |
pytext/__init__.py | NunoEdgarGFlowHub/pytext | 1 | 20496 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import json
import uuid
from typing import Callable, Mapping, Optional
import numpy as np
from caffe2.python import workspace
from caffe2.python.predictor import predictor_exporter
from .builtin_task import register_builtin_... | 2.125 | 2 |
modules/cudaobjdetect/misc/python/test/test_cudaobjdetect.py | ptelang/opencv_contrib | 7,158 | 20497 | #!/usr/bin/env python
import os
import cv2 as cv
import numpy as np
from tests_common import NewOpenCVTests, unittest
class cudaobjdetect_test(NewOpenCVTests):
def setUp(self):
super(cudaobjdetect_test, self).setUp()
if not cv.cuda.getCudaEnabledDeviceCount():
self.skipTest("No CUDA-ca... | 2.453125 | 2 |
gizmo/mapper.py | emehrkay/gizmo | 19 | 20498 | import logging
import inspect
import re
from collections import OrderedDict
from gremlinpy.gremlin import Gremlin, Param, AS
from .entity import (_Entity, Vertex, Edge, GenericVertex, GenericEdge,
ENTITY_MAP)
from .exception import (AstronomerQueryException, AstronomerMapperException)
from .traversal import Trav... | 2.015625 | 2 |
utils.py | Nicolas-Lefort/conv_neural_net_time_serie | 0 | 20499 | <reponame>Nicolas-Lefort/conv_neural_net_time_serie
import pandas_ta as ta
def clean(df, df_signal):
df = df.join(df_signal)
df.replace("", "NaN", inplace=True)
df.dropna(inplace=True)
df = df.reset_index(drop=True)
df_signal = df['signal']
df.drop(columns=['volume', 'high', 'low', 'open', 'sig... | 2.71875 | 3 |