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
data/raw_data/test.py
orion-orion/Cloze_Test
1
23800
''' Descripttion: Version: 1.0 Author: ZhangHongYu Date: 2022-02-05 18:23:00 LastEditors: ZhangHongYu LastEditTime: 2022-05-17 16:26:12 ''' import os import sys import json import argparse from transformers import AlbertTokenizer from pytorch_pretrained_bert import BertTokenizer, BertForMaskedLM file_path = sys.argv[1...
2.53125
3
steampipe_alchemy/models/aws_route53_resolver_rule.py
RyanJarv/steampipe_alchemy
9
23801
<filename>steampipe_alchemy/models/aws_route53_resolver_rule.py from sqlalchemy import Column from sqlalchemy.types import JSON, Text, Boolean, TIMESTAMP, BigInteger from sqlalchemy.dialects import postgresql as psql from steampipe_alchemy.mixins import FormatMixins from steampipe_alchemy import Base class AwsRoute53...
2.09375
2
harvester/sharekit/extraction.py
nppo/search-portal
1
23802
import re from mimetypes import guess_type from django.conf import settings from datagrowth.processors import ExtractProcessor from datagrowth.utils import reach from core.constants import HIGHER_EDUCATION_LEVELS, RESTRICTED_MATERIAL_SETS class SharekitMetadataExtraction(ExtractProcessor): youtube_regex = re....
2.125
2
jake/test/test_audit.py
lvcarlosja/jake
0
23803
# # Copyright 2019-Present Sonatype 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 applicable law or agreed to ...
2.34375
2
vintage_commands.py
ktuan89/Vintage
0
23804
<reponame>ktuan89/Vintage import sublime, sublime_plugin import os #import subprocess def is_legal_path_char(c): # XXX make this platform-specific? return c not in " \n\"|*<>{}[]()" def move_while_path_character(view, start, is_at_boundary, increment=1): while True: if not is_legal_path_char(view....
2.46875
2
bitten/tests/notify.py
dokipen/bitten
1
23805
<reponame>dokipen/bitten #-*- coding: utf-8 -*- # # Copyright (C) 2007 <NAME>, <<EMAIL>> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import unittest from trac.db import DatabaseManager from trac.test import Envir...
1.976563
2
sparse gamma def/gamma_def_score.py
blei-lab/ars-reparameterization
33
23806
<filename>sparse gamma def/gamma_def_score.py from autograd import grad import autograd.numpy as np import autograd.numpy.random as npr import autograd.scipy.special as sp from gamma_def import * # Define helper functions for score fnc estimator def logQ(sample, alpha, m): """ Evaluates log of variational app...
2.71875
3
codes/Ex036.py
BelfortJoao/Curso-phyton01
3
23807
x = float(input('Qual o valor da casa que quer comprar? ')) y = int(input("em quantos anos quer comprar a casa? ")) z = int(input("Qual seu salario? ")) w = y*12 if x / w > (z/100)*30: print("Voce não pode comprar a casa") else: print('Voce pode comprar a casa a parcela é de {:.2f}'.format(x/y))
3.671875
4
datasets/base_dataset.py
iclr2022submission4/cgca
13
23808
import torch import random from torch.utils.data import Dataset, DataLoader from abc import ABC from models.base_model import Model from torch.utils.tensorboard import SummaryWriter from typing import List class BaseDataset(Dataset, ABC): name = 'base' def __init__(self, config: dict, mode: str = 'train'): self....
2.296875
2
open_data/dataset/migrations/0005_keyword_squashed_0006_remove_keyword_relevancy.py
balfroim/OpenData
0
23809
<reponame>balfroim/OpenData # Generated by Django 3.2 on 2021-04-21 13:01 from django.db import migrations, models class Migration(migrations.Migration): replaces = [('dataset', '0005_keyword'), ('dataset', '0006_remove_keyword_relevancy')] dependencies = [ ('dataset', '0004_alter_theme_i...
1.703125
2
src/converters/__init__.py
Peilonrayz/json_to_object
0
23810
<filename>src/converters/__init__.py from .converter import Converter, Converters, ron
1.28125
1
result/forms.py
Uqhs-1/uqhs
3
23811
# -*- coding: utf-8 -*- """ Created on Wed Jan 23 08:25:37 2019 @author: AdeolaOlalekan """ from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import BTUTOR, CNAME, Edit_User, QSUBJECT, Post class login_form(forms.Fo...
2.703125
3
00-basic/04_01_data_structures_lists.py
TranXuanHoang/Python
0
23812
<filename>00-basic/04_01_data_structures_lists.py # Lists # Basics foods = ['rice', 'Meat', 'vegetables', 'Eggs'] print(foods) # Same as foods[len(foods):] = ['butter'] foods.append('butter') print(foods) # Same as foods[len(foods):] = ['tomatoes', 'chili sauce'] foods.extend(['tomatoes', 'Chili sauce']) ...
4.1875
4
pond5/blueprints/webui/views.py
IvanFrezzaJr/pond5
0
23813
<reponame>IvanFrezzaJr/pond5<gh_stars>0 from flask import render_template def index(): return render_template("index.html", title='pond5 test')
1.898438
2
featureflags/__init__.py
enverbisevac/ff-python-server-sdk
0
23814
<gh_stars>0 """Top-level package for Feature Flag Server SDK.""" __author__ = """<NAME>""" __email__ = "<EMAIL>" __version__ = "0.1.0"
1.023438
1
MachineLearning/potential_field.py
JhaAman/lihax
0
23815
<reponame>JhaAman/lihax<filename>MachineLearning/potential_field.py #!/usr/bin/env python import math, socket, struct, numpy as np, sys # Get the gradient of the potential of an obstacle # particle at (ox, oy) with the origin at (mx, my) # Get the potential of an obstacle particle at (ox, oy) # with the origin at ...
2.5625
3
decomp/c/gen.py
nihilus/epanos
1
23816
from itertools import imap, chain from pycparser import c_generator, c_ast from decomp import data, ida from decomp.c import decl as cdecl, types as ep_ct from decomp.cpu import ida as cpu_ida XXX_INTRO_HACK = cpu_ida.ida_current_cpu().insns.support_header + ''' #include <stdint.h> typedef union EPANOS_REG { uint8...
2.109375
2
ocelot/io/__init__.py
cmutel/Ocelot
21
23817
# -*- coding: utf-8 -*- __all__ = ( "extract_directory", "cleanup_data_directory", "dataset_schema", "validate_directory", "validate_directory_against_xsd", ) from .extract_ecospold2 import extract_ecospold2_directory from ..filesystem import check_cache_directory, get_from_cache, cache_data import...
2.359375
2
Data-Structure/Basic-Struct/Stack-Queues/Evaluation-of-Expressions/Eval.py
tz70s/lesson
1
23818
#!/usr/bin/env python3 import stack import queue opset = {'*','+','(',")"} def readinfix(): fh = open("infix.txt") li = [] li += fh.read() print (li) return li def eval(): evlist = readinfix() postlist = [] st = stack.Stack() for op in evlist: if op in opset: s...
3.640625
4
example/py/CHSHInequality/chsh_inequality.py
samn33/qlazy
15
23819
import random from qlazy import QState def classical_strategy(trials=1000): win_cnt = 0 for _ in range(trials): # random bits by Charlie (x,y) x = random.randint(0,1) y = random.randint(0,1) # response by Alice (a) a = 0 # response by Bob (b) b = 0 ...
2.765625
3
peerplays/blockchainobject.py
farisshajahan/python-peerplays
10
23820
<reponame>farisshajahan/python-peerplays # -*- coding: utf-8 -*- from .instance import BlockchainInstance from graphenecommon.blockchainobject import ( BlockchainObject as GrapheneBlockchainObject, BlockchainObjects as GrapheneBlockchainObjects, ObjectCache, ) @BlockchainInstance.inject class BlockchainOb...
1.78125
2
Code/Python/LeetCode/tempCodeRunnerFile.py
dks1018/CoffeeShopCoding
0
23821
arr_1 = ["1","2","3","4","5","6","7"] arr_2 = [] for n in arr_1: arr_2.insert(0,n) print(arr_2)
3.40625
3
pyvat/utils.py
ponyville/pyvat
48
23822
from decimal import Decimal def ensure_decimal(value): return value if isinstance(value, Decimal) else Decimal(value)
2.828125
3
pype/modules/idle_manager/__init__.py
simonebarbieri/pype
0
23823
from .idle_module import ( IdleManager, IIdleManager ) __all__ = ( "IdleManager", "IIdleManager" )
1.195313
1
server/src/tests/samples/typeConstraint3.py
higoshi/pyright
0
23824
<gh_stars>0 # This sample exercises the type analyzer's assert type constraint logic. from typing import Union def foo(a: Union[str, int]) -> int: if True: # This should generate an error because # a could be a str. return a assert isinstance(a, int) return a
3.0625
3
Attention.py
Pok0923/Time-series-forecasting-model
0
23825
import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend as K from keras.models import Sequential,Model from keras.layers import * from keras.optimizers import SGD,Adam class OurLayer(Layer): def reuse(self, layer, *args, **kwargs): if not layer.built: if len(a...
2.59375
3
tests/remix/test_audio_chunk_merger.py
nroldanf/infiniteremixer
0
23826
<reponame>nroldanf/infiniteremixer<gh_stars>0 import numpy as np import pytest from infiniteremixer.remix.audiochunkmerger import AudioChunkMerger @pytest.fixture def chunk_manager(): return AudioChunkMerger() def test_chunk_manager_is_instantiated(chunk_manager): assert isinstance(chunk_manager, AudioChun...
2.421875
2
app/libpinanny/__init__.py
MelonSmasher/piNanny
0
23827
from subprocess import PIPE, Popen # Converts celsius temps to fahrenheit def c2f(celsius): return (9.0 / 5) * celsius + 32 # Gets the CPU temperature in degrees C def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() return floa...
3.046875
3
paas-ce/paas/paas/esb/apps/guide/component_template/en/hcp/get_host_list.py
renmcc/bk-PaaS
2
23828
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
1.84375
2
pretix_googlepaypasses/views.py
pc-coholic/pretix-googlepaypasses
2
23829
import json import logging from json import JSONDecodeError from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, ) from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from pretix.base.models import Organizer from . import tas...
2.03125
2
alf/utils/checkpoint_utils.py
breakds/alf
1
23830
<filename>alf/utils/checkpoint_utils.py # Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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.ap...
2.203125
2
automon/integrations/slack/config.py
TheShellLand/automonisaur
2
23831
<reponame>TheShellLand/automonisaur import os from automon.log import Logging log = Logging(name=__name__, level=Logging.ERROR) class ConfigSlack: slack_name = os.getenv('SLACK_USER') or '' slack_webhook = os.getenv('SLACK_WEBHOOK') or '' slack_proxy = os.getenv('SLACK_PROXY') or '' slack_token = os...
2.296875
2
z2z_metadata/__init__.py
Mitchellpkt/z2z-metadata
0
23832
<gh_stars>0 """Top-level package for z2z Metadata analysis.""" __author__ = """Isthmus // <NAME>""" __email__ = '<EMAIL>' __version__ = '0.0.1'
0.839844
1
pyeparse/tests/__init__.py
Eric89GXL/pyeparse
0
23833
<reponame>Eric89GXL/pyeparse # Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause)
0.855469
1
Murphi/ModularMurphi/TemplateClass.py
icsa-caps/HieraGen
6
23834
<filename>Murphi/ModularMurphi/TemplateClass.py import inspect import os import re class TemplateHandler: # Constant definitions tab = " " nl = "\n" sem = ";" end = sem + nl def __init__(self, template_dir: str): self.templatepath = os.path.dirname(os.path.abspath(inspect.getfile(in...
2.453125
2
bot/exts/filters/token_remover.py
adhikariprajitraj/bot
0
23835
<reponame>adhikariprajitraj/bot import base64 import binascii import logging import re import typing as t from discord import Colour, Message, NotFound from discord.ext.commands import Cog from bot import utils from bot.bot import Bot from bot.constants import Channels, Colours, Event, Icons from bot.exts.moderation....
2.34375
2
setup.py
PaulDodd/pynomial
0
23836
import sys from setuptools import setup, find_packages setup( name='pynomial', version='0.0.0', packages=find_packages(), author='<NAME>', author_email='<EMAIL>', description="python package for combinatorial problems", url="https://github.com/PaulDodd/pynomial.git", install_requires=[]...
1.382813
1
src/seedbox/migrations/versions/35099fc974d2_.py
nailgun/seedbox
29
23837
<filename>src/seedbox/migrations/versions/35099fc974d2_.py """empty message Revision ID: 35099fc974d2 Revises: ae00e7974dca Create Date: 2017-05-19 17:01:48.878196 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '35099fc974d2' down_revision = 'ae00e7974dca' bra...
1.5625
2
searchNMin2.py
plguhur/random-sets
0
23838
<filename>searchNMin2.py<gh_stars>0 from randomSets import * import numpy as np winners = [1,5,10] candidates = range(100, 1100, 500) Nmin = np.zeros((len(winners),len(candidates))) for i in range(len(winners)): for j in range(len(candidates)): print("Nwinner: %i, Ncandidates: %i" % (winners[i], candidates...
2.734375
3
drs4Calibration/drs4Calibration_version_0/config.py
fact-project/DrsTemperatureCalibration
0
23839
from drs4Calibration.drs4Calibration_version_0.constants import NRCELL, ROI # Dont shuffle drsValueTypes # The order have to be the same as the of the 'RUNIDs' # in the drsFiles drsValueTypes = ['Baseline', 'Gain', 'TriggerOffset'] renamedDrsValueTypes = ['Baseline', ...
1.742188
2
clisk/player/player.py
etano/clisk
0
23840
<filename>clisk/player/player.py class Player(object): """Player class Attributes: name (str): Player name """ def __init__(self, name): """Initialize player Args: name (str): Player name """ self.name = name def place_troops(self, ...
3.640625
4
bai03.py
trietto/python
0
23841
n=int(input("Nhap vao mot so:")) d=dict() for i in range(1, n+1): d[i]=i*i print(d)
3.515625
4
quizme.pyw
dmahugh/quizme
0
23842
<filename>quizme.pyw<gh_stars>0 """GUI for taking tests based on quizme-xxx.json files. """ import os import sys import json from random import randint import tkinter as tk from tkinter import font from tkinter import ttk from tkinter import filedialog from tkinter import messagebox from widgetrefs import widgets de...
3.65625
4
kedro/extras/datasets/pandas/appendable_excel_dataset.py
hfwittmann/kedro
1
23843
"""``AppendableExcelDataSet`` loads/saves data from/to a local Excel file opened in append mode. It uses pandas to handle the Excel file. """ from copy import deepcopy from pathlib import Path, PurePosixPath from typing import Any, Dict import pandas as pd from kedro.io.core import AbstractDataSet, DataSetError cla...
2.828125
3
examples/phobos/tests/test_std_system.py
kinke/autowrap
47
23844
def test_import(): import std_system
1.015625
1
graalpython/benchmarks/src/meso/euler31.py
muellren/graalpython
1
23845
<reponame>muellren/graalpython<filename>graalpython/benchmarks/src/meso/euler31.py #!/usr/bin/env python # Copyright 2008-2010 <NAME> # Copyright (c) 2013, 2014, Regents of the University of California # Copyright (c) 2017, 2018, Oracle and/or its affiliates. # All rights reserved. # # Revised BSD license # # This is a...
1.617188
2
comicMaker/readComicsOnlineRu.py
Gunjan933/comicMaker
3
23846
from .makeFullPdf import makeFullPdf from .parseImage import parseImage from .makePdf import makePdf import requests,os,os.path,sys,time,json from bs4 import BeautifulSoup def readComicsOnlineRu(): while True: try: with open('config.json', 'r', encoding="utf-8") as f: books = json.load(f) library=[*books[...
2.921875
3
geoipgen/generate.py
christivn/INDES-devices-scan-engine
2
23847
from . import subnetCal from . import functions from random import randint def IP(cidr): arr=subnetCal.simpleCalculate(cidr) min_host=arr[3] smin_host=min_host.split(".") max_host=arr[4] smax_host=max_host.split(".") ip="" for i in range(4): if(smin_host[i]==smax_host[i]): ...
2.6875
3
lib/googlecloudsdk/command_lib/filestore/operations/flags.py
bshaffer/google-cloud-sdk
0
23848
# -*- coding: utf-8 -*- # # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
1.398438
1
model_agreement.py
ntunlp/coherence-paradigm
0
23849
import sys import pickle from krips_alpha import krippendorff_alpha, nominal_metric def get_model_labels(model_output): model_labels = [] for x in model_output: try: if x['pos_score'] > x['neg_score']: model_labels.append('0') elif x['neg_score'] > x['pos_score']: model_labels.append('1') else: ...
2.484375
2
lewansoul-lx16a/lewansoul_lx16a.py
christophschnabl/lewansoul-lx16a
2
23850
<reponame>christophschnabl/lewansoul-lx16a __all__ = [ 'ServoController', 'TimeoutError', 'SERVO_ERROR_OVER_TEMPERATURE', 'SERVO_ERROR_OVER_VOLTAGE', 'SERVO_ERROR_LOCKED_ROTOR', ] from serial.serialutil import * from functools import partial import threading import logging SERVO_ID_ALL = 0xfe ...
2.34375
2
Basic Data Structures/string/leet_551_StudentAttendanceRecordI.py
rush2catch/algorithms-leetcode
0
23851
# Problem: Student Attendance Record I # Difficulty: Easy # Category: String # Leetcode 551: https://leetcode.com/problems/student-attendance-record-i/#/description # Description: """ You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : ...
3.796875
4
etc/check-python.py
maxzheng/auto-update
7
23852
#!/usr/bin/env python import argparse import os import platform import re import shutil import subprocess import sys SUPPORTED_VERSIONS = ('3.6', '3.7') IS_DEBIAN = platform.system() == 'Linux' and os.path.exists('/etc/debian_version') IS_OLD_UBUNTU = (IS_DEBIAN and os.path.exists('/etc/lsb-release') ...
2.84375
3
pnet/measure.py
changshuowang/PersistenceNetwork
1
23853
import numpy as np from sklearn.metrics import average_precision_score as ap from sklearn.metrics import roc_auc_score """ each row is an instance each column is the prediction of a class """ def _score_to_rank(score_list): rank_array = np.zeros([len(score_list)]) score_array = np.array(score_list) idx_so...
2.9375
3
src/trainer/transformations.py
tiborkubik/Robust-Teeth-Detection-in-3D-Dental-Scans-by-Automated-Multi-View-Landmarking
2
23854
""" :filename transformations.py :author <NAME> :email <EMAIL> from Classes of custom transformations that are applied during the training as additional augmentation of the depth maps. """ import torch import random import numpy as np import torch.nn.functional as F from random import randrange from s...
2.765625
3
solutions/python3/1009.py
sm2774us/amazon_interview_prep_2021
42
23855
class Solution: def bitwiseComplement(self, N: int, M = 0, m = 0) -> int: return N ^ M if M and M >= N else self.bitwiseComplement(N, M + 2 ** m, m + 1)
3.453125
3
cappuccino.py
y-tsutsu/cappuccino
1
23856
import random import shutil import sys from argparse import ArgumentParser from os import path from pathlib import Path from threading import Thread from PySide6 import __version__ as PySideVer from PySide6.QtCore import (Property, QCoreApplication, QObject, Qt, QTimer, Signal, Slot) from P...
2.203125
2
lofti_gaia/lofti.py
logan-pearce/lofti_gaia
2
23857
import astropy.units as u import numpy as np from lofti_gaia.loftitools import * from lofti_gaia.cFunctions import calcOFTI_C #from loftitools import * import pickle import time import matplotlib.pyplot as plt # Astroquery throws some warnings we can ignore: import warnings warnings.filterwarnings("ignore") '''This mo...
2.34375
2
src/data_curation/dataset_manager/views.py
NovaSBE-DSKC/retention-evaluation
0
23858
from src.data_curation.dataset_manager import get_meta import pandas as pd def view_all(): return get_meta() def get_docs(id): df = get_meta() docs = df[df["id"] == id]["docs"].iloc[0] df = pd.read_json(docs) return df
2.6875
3
deid/model/layers/__init__.py
KavishBhatia/deid-training-data
15
23859
from .gradient_reversal import GradientReversal from .noise import Noise, AdditiveNoise, MultiplicativeNoise
1.179688
1
db_pool/mysql/base.py
GiftLee/devops
300
23860
# -*- coding: utf-8 -*- """ 查看 django.db.backends.mysql.base.by 源码发现 django 连接 mysql 时没有使用连接池, 导致每次数据库操作都要新建新的连接并查询完后关闭,更坑的是按照 django 的官方文档设置 CONN_MAX_AGE 参数是为了复用连接,然后设置了 CONN_MAX_AGE 后,每个新连接查询完后并不 会 close 掉,而是一直在那占着。如果在高并发模式下,很容易出现 too many connections 错误。故重写 mysql 连接库,实现连接池功能。 """ from django.core.exceptions import I...
2.5
2
flowsa/flowbyfunctions.py
modelearth/flowsa
13
23861
<reponame>modelearth/flowsa<filename>flowsa/flowbyfunctions.py # flowbyfunctions.py (flowsa) # !/usr/bin/env python3 # coding=utf-8 """ Helper functions for flowbyactivity and flowbysector data """ import pandas as pd import numpy as np from esupy.dqi import get_weighted_average import flowsa from flowsa.common import...
2.09375
2
stochastic_hill_climbing/src/AdalineSGD.py
Wookhwang/Machine-Learning
0
23862
<reponame>Wookhwang/Machine-Learning<filename>stochastic_hill_climbing/src/AdalineSGD.py import numpy as np # gradient descent는 tensorflow에 이미 구현이 되어있다. # 확률적 선형 뉴런 분석기는 각 훈련 샘플에 대해서 조금씩 가중치를 업데이트 한다. class AdalineSGD(object): """Adaptive Linear Neuron 분류기 매개변수 ------------ eta : float ...
2.578125
3
las1.2.py
Theskill19/sweetpotato
0
23863
<filename>las1.2.py #2. Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. time = int(input("Введите время в секундах ")) hours = time // 3600 minutes = (time - hours * 3600) // 60 seconds = time - (hours * 3600 + ...
3.828125
4
tpdatasrc/tpgamefiles/rules/char_class/class020_archmage.py
edoipi/TemplePlus
0
23864
from toee import * import char_class_utils ################################################### def GetConditionName(): return "Archmage" def GetSpellCasterConditionName(): return "Archmage Spellcasting" def GetCategory(): return "Core 3.5 Ed Prestige Classes" def GetClassDefinitionFlags(): return CDF_CoreClass...
2.09375
2
src/bananas/drf/errors.py
beshrkayali/django-bananas
26
23865
<reponame>beshrkayali/django-bananas from rest_framework import status from rest_framework.exceptions import APIException class PreconditionFailed(APIException): status_code = status.HTTP_412_PRECONDITION_FAILED default_detail = "An HTTP precondition failed" default_code = "precondition_failed" class Ba...
2.1875
2
tools/train_net.py
luzhenyv/sesame
0
23866
<reponame>luzhenyv/sesame<gh_stars>0 """Train a video classification""" import torch import sesame.models.losses as losses import sesame.models.optimizer as optim import sesame.utils.distributed as du import sesame.utils.misc as misc import sesame.utils.metrics as metrics import sesame.utils.logger as logger from ses...
2.328125
2
setup.py
stshrive/pycense
0
23867
<gh_stars>0 import os import setuptools VERSION = "1.0.0a1+dev" INSTALL_REQUIRES = [ 'pip-licenses', ] CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research' ] def read(fname): return open(os.path.join(os.path.dirname(__file_...
1.453125
1
parents/admin.py
joseph0919/Student_Management_Django
0
23868
from django.contrib import admin from parents.models import Guardian admin.site.register(Guardian)
1.148438
1
src/test/tests/hybrid/missingdata.py
visit-dav/vis
226
23869
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: missingdata.py # # Tests: missing data # # Programmer: <NAME> # Date: Thu Jan 19 09:49:15 PST 2012 # # Modifications: # # -------------------------------------------------------------------...
2.296875
2
data_input/__init__.py
uabalabadubdub/ppcd-pec4
0
23870
<filename>data_input/__init__.py from pathlib import Path current_path = Path(".") datafolder = current_path / "data" imagefolder = current_path / "images" if not datafolder.exists(): print(f"Creating {datafolder}/...") datafolder.mkdir() if not imagefolder.exists(): print(f"Creating {imagefolder}/...") ...
3.109375
3
displacy_service_tests/test_server.py
mjfox3/spacy-api-docker
0
23871
import falcon.testing import pytest import json from displacy_service.server import APP, MODELS model = MODELS[0] @pytest.fixture() def api(): return falcon.testing.TestClient(APP) def test_deps(api): result = api.simulate_post( path='/dep', body='{{"text": "This is a test.", "model": "{m...
2.578125
3
exposures/generate_passwords.py
jarnoln/exposures
0
23872
#!/usr/bin/env python import random import argparse def generate_passwords(password_file_path): password_file = open(password_file_path, 'w') chars = 'abcdefghijklmnopqrstuvxyz01234567890_-!*' secret_key = ''.join(random.SystemRandom().choice(chars) for _ in range(50)) password_file.write("SECRET_KEY ...
3.34375
3
adversarial-transfer-nlp/CW_attack.py
AI-secure/Uncovering-the-Connections-BetweenAdversarial-Transferability-and-Knowledge-Transferability
8
23873
<filename>adversarial-transfer-nlp/CW_attack.py import sys import torch import numpy as np from torch import optim from util import args class CarliniL2: def __init__(self, targeted=True, search_steps=None, max_steps=None, cuda=True, debug=False, num_classes=14): self.debug = debug self.targeted...
2.453125
2
api/cueSearch/migrations/0005_searchcardtemplate_connectiontype.py
cuebook/CueSearch
3
23874
# Generated by Django 3.2.5 on 2022-02-18 08:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("dataset", "0001_initial"), ("cueSearch", "0004_auto_20220217_0217"), ] operations = [ migrations.Ad...
1.578125
2
FormulaAccordingPrint.py
FreeBirdsCrew/Brainstorming_Codes
1
23875
<reponame>FreeBirdsCrew/Brainstorming_Codes<filename>FormulaAccordingPrint.py<gh_stars>1-10 """ Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should ...
4.15625
4
src/django_sys_indicator/utils.py
marksweb/django-sys-indicator
1
23876
from __future__ import annotations from django.template.loader import render_to_string from .conf import settings def django_sys_indicator_tag() -> str: template_name = 'django_sys_indicator/system_indicator.html' try: color, border_color = settings.SYSTEM_INDICATOR_COLORS[ settings.SYS...
2.0625
2
MUNDO 1/ex023.py
athavus/Curso-em-video-Python-3
1
23877
<reponame>athavus/Curso-em-video-Python-3 n1 = int(input('Digite um número entre 0 e 9999: ')) u = n1 // 1 % 10 d = n1 // 10 % 10 c = n1 // 100 % 10 m = n1 // 1000 % 10 print(f'Analisando o número {n1}') print(f'unidade: {u}') print(f'dezena: {d}') print(f'centena: {c}') print(f'milhar: {m}')
3.59375
4
Python Notebook/Python files/data_utility.py
wilfy9249/Capstone-Fall-18
2
23878
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import os # In[2]: #function to get current directory def getCurrentDirectory(): listDirectory = os.listdir('../') return listDirectory # In[3]: #function to read csv file def readCsvFile(path): crimes_original =...
3.203125
3
microtbs_rl/algorithms/common/__init__.py
alex-petrenko/simple-reinforcement-learning
8
23879
<filename>microtbs_rl/algorithms/common/__init__.py from microtbs_rl.algorithms.common.agent import AgentLearner from microtbs_rl.algorithms.common.loops import run_policy_loop
1.148438
1
retrieve/GetTotalEarnings.py
TRiCAM-Lab/task-effort
0
23880
import sys from collections.abc import Mapping import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use a service account cred = credentials.Certificate('./service-account-key.json') firebase_admin.initialize_app(cred) db = firestore.client() for row in sys.stdin: ...
2.734375
3
pyGAE/handlers/ManageSubscriptionHandler.py
analyticstraining/pycocms
0
23881
<reponame>analyticstraining/pycocms<filename>pyGAE/handlers/ManageSubscriptionHandler.py<gh_stars>0 from BaseHandler import BaseHandler, user_required class ManageSubscriptionHandler(BaseHandler): @user_required def get(self): self.render_template('manage_subscription.html')
1.609375
2
aiphysim/models/spacetime.py
perovai/deepkoopman
0
23882
<gh_stars>0 import torch import torch.nn as nn class SpaceTime(nn.Module): def __init__(self, opts): # TODO: Add things like no. of hidden layers to opts pass class LSTM(nn.Module): # This class is largely derived from # https://stackabuse.com/time-series-prediction-using-lstm-with-pytor...
3.109375
3
fabfile/text.py
nprapps/austin
7
23883
#!/usr/bin/env python """ Commands related to syncing copytext from Google Docs. """ from fabric.api import task from termcolor import colored import app_config from etc.gdocs import GoogleDoc @task(default=True) def update(): """ Downloads a Google Doc as an Excel file. """ if app_config.COPY_GOOGL...
2.8125
3
program.py
jaesik817/programmable-agents_tensorflow
39
23884
import tensorflow as tf import numpy as np import math # Parameter order_num=2; class Program: def __init__(self,sess,state_dim,obj_num,fea_size,Theta,program_order,postfix): self.sess = sess; self.state_dim = state_dim; self.fea_size=fea_size; self.obj_num=obj_num; self.order_num=order_num; ...
2.75
3
ism_pkg/tools/opt_gaussian.py
endsley/stochastic_ISM
1
23885
<gh_stars>1-10 #!/usr/bin/env python import sys import matplotlib import numpy as np import random import itertools import socket import sklearn.metrics from scipy.optimize import minimize from scipy.optimize import Bounds from sklearn import preprocessing from sklearn.preprocessing import OneHotEncoder from sklearn....
2.1875
2
tests/commands/test_generate.py
pedrovelho/camp
0
23886
<reponame>pedrovelho/camp<gh_stars>0 # # CAMP # # Copyright (C) 2017, 2018 SINTEF Digital # All rights reserved. # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. # from unittest import TestCase from camp.commands import Command, Generate c...
2.375
2
create_cpu_config.py
ttungl/HeteroArchGen4M2S
5
23887
#!/usr/bin/env python # =========================================================================== # Copyright 2017 `<NAME>` # Email: ttungl at gmail dot com # Heterogeneous Architecture Configurations Generator for Multi2Sim simulator # (aka, `HeteroArchGen4M2S`) # `HeteroArchGen4M2S` is free software, which is fre...
1.710938
2
app/wall_e/models/canvas_api.py
dbwebb-se/umbridge
0
23888
<gh_stars>0 """ """ import os from flask import current_app from canvasapi import submission, requester from app.wall_e.models.requester import Requester from app.settings import settings class Canvas(Requester): """ Model class for wall_e.fetch """ def __init__(self, base_url, api_token, course_id, ...
2.59375
3
chat/views.py
xiaoqiao99/chat
2
23889
<reponame>xiaoqiao99/chat<gh_stars>1-10 from django.shortcuts import render # Create your views here. # chat/views.py from django.shortcuts import render from django.utils.safestring import mark_safe import json from chat.models import Room def index(request): # from channels.layers import get_channel_layer #...
2.125
2
src/app/db.py
jorwalk/fastapi-crud-async
0
23890
import os from sqlalchemy import (Column, DateTime, Integer, MetaData, String, Text, Table, create_engine) from sqlalchemy.sql import func from databases import Database DATABASE_URL = os.getenv("DATABASE_URL") # SQLAlchemy engine = create_engine(DATABASE_URL) metadata = MetaData() movies =...
2.75
3
python/greshunkel.py
qpfiffer/38-Moths
14
23891
<reponame>qpfiffer/38-Moths from ctypes import cdll, c_char_p, c_size_t, c_void_p, Union,\ LittleEndianStructure, c_char, POINTER,\ c_int, byref, CFUNCTYPE, create_string_buffer class greshunkel_var(Union): _fields_ = [ ("str", c_char * 513), ("arr", c_...
1.90625
2
objects/paginators.py
fossabot/KiwiBot
0
23892
from collections import OrderedDict from asyncio import TimeoutError, wait from concurrent.futures import FIRST_COMPLETED import time from discord import TextChannel, DMChannel from discord.errors import Forbidden, NotFound from objects.context import Context class PaginatorABC: def __init__(self, bot, looped...
2.46875
2
tests/test_managedblockchain/test_managedblockchain_proposalvotes.py
junelife/moto
1
23893
from __future__ import unicode_literals import os import boto3 import sure # noqa from freezegun import freeze_time from unittest import SkipTest from moto import mock_managedblockchain, settings from . import helpers @mock_managedblockchain def test_vote_on_proposal_one_member_total_yes(): conn = boto3.clien...
2.03125
2
docs/Others/Python_leetcode/Codes/1.Two_Sum.py
mheanng/PythonNote
2
23894
<gh_stars>1-10 """ 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] """ # %% class Solution: def twoSum(self, nums, target): S = set(nums) for num in S: ...
3.296875
3
pyathena/util/rebin.py
changgoo/pyathena-1
1
23895
<reponame>changgoo/pyathena-1 from __future__ import print_function import numpy as np def rebin_xyz(arr, bin_factor, fill_value=None): """ Function to rebin masked 3d array. Parameters ---------- arr : ndarray Masked or unmasked 3d numpy array. Shape is assumed to be (nz, ny, nx). ...
3.296875
3
fn_utilities/fn_utilities/components/utilities_shell_command.py
rudimeyer/resilient-community-apps
1
23896
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2018. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """Function implementation""" import os import logging import time import shlex import subprocess import json import chardet import winrm import re from resilient_circuits import Resilien...
2
2
snapmerge/home/migrations/0010_project_email.py
R4356th/smerge
13
23897
<reponame>R4356th/smerge # Generated by Django 2.0.1 on 2018-07-26 12:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0009_auto_20180726_1214'), ] operations = [ migrations.AddField( model_name='project', ...
1.460938
1
othello.py
edjacob25/Intelligent-Systems
0
23898
<filename>othello.py from games import (GameState, Game, query_player, random_player, alphabeta_player, play_game, minimax_decision, alphabeta_full_search, alphabeta_search) class Othello(Game): """Juega Othello en un tablero 8 x 8, con Max (primer jugador) jugando con ...
3.8125
4
bot/lib/controller/GetCommentTask.py
nullwriter/ig-actor
0
23899
<gh_stars>0 import time import re from FileLogger import FileLogger as FL import datetime class GetCommentTask: def __init__(self, task, name="extract-comment"): self.task = task self.name = name self.comments = [] self.log = FL('Extracted Comments {:%Y-%m-%d %H:%M:%S}.txt'.format...
2.65625
3