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
smorest_crud/test/test_crud.py
jetbridge/smorest-crud
9
12771851
from flask.testing import FlaskClient from smorest_crud.test.app import USER_NAME def test_list(client: FlaskClient, pets): res = client.get("/human") assert res.status_code == 200 res = res.json assert len(res) == 10 assert res[0]["pets"][0] assert res[0]["pets"][0]["genus"] def test_get(...
2.421875
2
pymatflow/qe/scripts/qe-bands.py
DeqiTang/pymatflow
6
12771852
#!/usr/bin/env python # _*_ coding: utf-8 _*_ import os import argparse from pymatflow.qe.static import StaticRun """ usage: """ control = {} system = {} electrons = {} bands = {} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-d", "--directory", t...
2.421875
2
harvester/harvester_classifier.py
diogonal/SentimentAnalyser
1
12771853
<gh_stars>1-10 ######################################################################################################### # # Author: <NAME> # Date: Apr/2015 # Name: harvester_classifier.py # Description: Performs Sentiment, geo location and gender analysis for streamed tweets as they come. # ...
2.46875
2
day4/part1.py
rockybulwinkle/advent-of-code-2020
0
12771854
<filename>day4/part1.py import sys import common if len(sys.argv) != 2: print(f"Usage: {sys.argv[0]} file") passports = common.load_passports(sys.argv[1]) count_p1 = 0 count_p2 = 0 for idx,i in enumerate(passports): if i.valid_p1(): count_p1+=1 valid = i.valid_p2() if valid: count_p...
3.0625
3
python/GafferImageUI/ResampleUI.py
ddesmond/gaffer
561
12771855
<gh_stars>100-1000 ########################################################################## # # Copyright (c) 2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: #...
0.878906
1
config/default.py
sartography/cr-connect-workflow
2
12771856
<reponame>sartography/cr-connect-workflow import os import re from os import environ basedir = os.path.abspath(os.path.dirname(__file__)) JSON_SORT_KEYS = False # CRITICAL. Do not sort the data when returning values to the front end. # The API_TOKEN is used to ensure that the # workflow synch can work without a lo...
2.09375
2
tests/test_aio_trampoline.py
suned/pfun
126
12771857
import pytest from hypothesis import assume, given from pfun import compose, identity from pfun.aio_trampoline import Done from pfun.hypothesis_strategies import aio_trampolines, anything, unaries from .monad_test import MonadTest class TestTrampoline(MonadTest): @pytest.mark.asyncio @given(aio_trampolines(...
2.359375
2
Cogs/administration.py
CptSnuffy/Research-Bot
0
12771858
import os from datetime import datetime from distutils.util import strtobool import discord from discord.ext import commands from dotenv import load_dotenv load_dotenv() LOCKDOWN_ACTIVE = bool(os.getenv('LOCKDOWN_ACTIVE')) class Administration(commands.Cog): @commands.command() @commands.has_permissio...
2.328125
2
tests/test_sklearn_normalizer_converter.py
twosense/sklearn-onnx
323
12771859
# SPDX-License-Identifier: Apache-2.0 """ Tests scikit-normalizer converter. """ import unittest import numpy from sklearn.preprocessing import Normalizer from skl2onnx import convert_sklearn from skl2onnx.common.data_types import ( Int64TensorType, FloatTensorType, DoubleTensorType) from test_utils import dump_da...
2.5
2
nqueens.py
aliyaconrad/nqueens
0
12771860
import random as r def solve(board_size): """Solves the n-queens problem given a board size n Args: board_size (int): The size of the n*n board containing n queens. Returns: board (int[]): A list where each element corresponds to the row of a queen. It is 1-based. """ # Declare...
4.28125
4
plusseg/modeling/segmentor/generalized_segmentor.py
tonysy/SegmentationToolbox.PyTorch
13
12771861
<reponame>tonysy/SegmentationToolbox.PyTorch """ Implement the Generalized Segmentation Model """ import torch from torch import nn # from plusseg.structures from ..backbone import build_backbone from ..decoder import build_decoder from ..postprocessor import build_post_processor from ..decoder import SegmentationLo...
2.71875
3
python/dcp027_balanced_parenthesis.py
iapurba/Daily-Coding-Problem
1
12771862
#!/usr/bin/env python3 def isBalanced(s: str) -> bool: stack = [] pair = {'(': ')', '{': '}', '[': ']'} for ch in s: # For left brackets push right brackets if (ch in pair.keys()): stack.append(pair[ch]) else: # Unmatch right char if len(stack) =...
3.875
4
app.py
CalvinGreen94/Heroku_Heart_Attack
0
12771863
import numpy as np from flask import Flask, session,abort,request, jsonify, render_template,redirect,url_for,flash import pickle import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from keras.models import load_model import os import stripe ...
2.875
3
tests/test_block_observation.py
knifecake/leapdna-python
0
12771864
<reponame>knifecake/leapdna-python from leapdna.errors import LeapdnaError from leapdna.blocks.locus import Locus from leapdna.blocks.allele import Allele from .support import TestCase from leapdna.blocks import Observation class TestObservationBlock(TestCase): def test_can_be_instantiated(self): l1 = Lo...
2.671875
3
tests/base_tests/expression_tests/test_truediv.py
lycantropos/symba
2
12771865
from numbers import Real from typing import Union from hypothesis import given from symba.base import Expression from tests.utils import equivalence from . import strategies @given(strategies.expressions, strategies.non_zero_reals_or_expressions) def test_basic(expression: Expression, real_or_express...
2.859375
3
oidc_auth/tests/test_views.py
intelie/django-oidc-auth
25
12771866
<filename>oidc_auth/tests/test_views.py from urllib.parse import urlparse, parse_qs from django.conf import settings from django.contrib.auth import get_user_model from importlib import import_module from django.test import Client from nose import tools import mock from .utils import OIDCTestCase from oidc_auth.models...
2.21875
2
tests/features/steps/datasets_repo/test_datasets_delete.py
dataloop-ai/dtlpy
10
12771867
<gh_stars>1-10 import behave @behave.when(u'I delete the dataset that was created by name') def step_impl(context): context.project.datasets.delete(dataset_name=context.dataset.name, sure=True, really=True) @behave.when(u'I delete the datas...
2.453125
2
pyglet-hg/tests/window/WINDOW_FULLSCREEN_SIZE.py
sangh/LaserShow
21
12771868
#!/usr/bin/env python '''Test that window can be set to and from various fullscreen sizes. Expected behaviour: One window will be opened. Press a number to switch to the corresponding fullscreen size; hold control and press a number to switch back to the corresponding window size: 0 - Default si...
3.015625
3
tripp/knn.py
mjamesruggiero/tripp
1
12771869
from collections import Counter import algebra def majority_vote(labels): """assumes that labels are ordered from nearest to farthest""" vote_counts = Counter(labels) winner, winner_count = vote_counts.most_common(1)[0] num_winners = len([count for count in vote_counts.values() ...
3.59375
4
evaluation/forks.py
jordibisbal8/network-slicing
0
12771870
import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.read_csv('/home/jordibisbal/WS18-MSc-JordiBisbalAnsaldo--NetworkSlicing/evaluation/experiments/1/forks/forks_pow.csv') x = np.arange(0.0, 100, 1) data = df[['T1', 'T2','T3','T4', 'T5','T6','T7', 'T8','T9','T10', 'T11','T12','T13', 'T14',...
2.546875
3
src/tabu_list.py
AHalic/tabu-search
0
12771871
from typing import List, Tuple import time import pandas as pd from initial_solution import * from local_search import * from graph import * def algorithm(nodes: List[dict], vehicles: int, clients: int, vehicle_capacity: int, tenure: int, file_writer, iter_max:int=1000, savings:bool=True) -> None: """ Aplica ...
3.40625
3
nikkei2019_2_qual_b.py
hythof/atc
0
12771872
<reponame>hythof/atc from collections import Counter n,*d=map(int,open(0).read().split()) c=Counter(d) if d[0]!=0 or c[0]!=1: print(0) exit() ans=1 m=998244353 for i in range(1, max(d)+1): ans*=pow(c[i-1],c[i],m) ans%=m print(ans)
2.46875
2
universe/wrappers/experimental/__init__.py
BitJetKit/universe
8,120
12771873
from universe.wrappers.experimental.action_space import SafeActionSpace, SoftmaxClickMouse from universe.wrappers.experimental.observation import CropObservations from universe.wrappers.experimental.random_env import RandomEnv
1.109375
1
website/migrations/0055_merge_20210119_2125.py
czhu1217/cmimc-online
0
12771874
# Generated by Django 3.1.5 on 2021-01-20 02:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0052_auto_20210114_2228'), ('website', '0054_task_grader_data_file'), ] operations = [ ]
1.40625
1
supar/models/__init__.py
ExplorerFreda/parser
0
12771875
# -*- coding: utf-8 -*- from .constituency import CRFConstituencyModel from .dependency import (BiaffineDependencyModel, CRF2oDependencyModel, CRFDependencyModel, CRFNPDependencyModel, SimplestBiaffineDependencyModel) __all__ = ['BiaffineDependencyModel', '...
1.054688
1
For_Cluster/Temp/letshpc_folder/main_script_without_perf.py
yatin2410/HPC_N_QUEENS
2
12771876
<filename>For_Cluster/Temp/letshpc_folder/main_script_without_perf.py #!/bin/python import subprocess import os import sys import maps import time import logging def line(n): print('-'*n) logging.basicConfig(filename = "LetsHPC_Team_CodeRunner.log", level = logging.INFO) logger = logging.getLogger(__name__) ...
2.578125
3
tests/integration/records/single_db/test_records_save_df.py
cwegrzyn/records-mover
36
12771877
import pytz import logging from .base_records_test import BaseRecordsIntegrationTest from ..directory_validator import RecordsDirectoryValidator from records_mover.records import ( RecordsSchema, DelimitedRecordsFormat, ProcessingInstructions ) import tempfile import pathlib import datetime logger = logging.getLo...
2.4375
2
python/tvm/contrib/graph_runtime.py
dayanandasiet/tvmdbg
0
12771878
"""Minimum graph runtime that executes graph containing TVM PackedFunc.""" from .._ffi.base import string_types from .._ffi.function import get_global_func from .rpc import base as rpc_base from .. import ndarray as nd from ..tools.debug.runtime import debugruntime from ..tools.debug.util import common def create(grap...
2.125
2
r2k/cli/config/config_show.py
mcouthon/rss-to-kindle
11
12771879
import click import orjson as json import yaml from r2k.cli import cli_utils, logger from r2k.config import config as _config @click.command("show") @cli_utils.config_path_option() @click.option( "-j", "--json", "is_json", is_flag=True, help="When passed the output will be in JSON format (e.g. fo...
2.546875
3
savingsapp/apps.py
primeuser/banking-software-django
3
12771880
<filename>savingsapp/apps.py from django.apps import AppConfig class SavingsappConfig(AppConfig): name = 'savingsapp'
1.320313
1
packages/depolitics.org/_old/src/application/forms.py
caveljan/depolitics
0
12771881
<reponame>caveljan/depolitics<gh_stars>0 from django import forms from .models import Politician class AddForm(forms.ModelForm): class Meta: model = Politician fields = ('first_name', 'last_name', 'name_variants', 'current_function', ...
2.234375
2
applications/Ma-Net/utils/mask_damaging.py
Simon-liusheng/PaddleVideo
0
12771882
<filename>applications/Ma-Net/utils/mask_damaging.py import numpy as np from scipy.ndimage import interpolation try: from skimage import morphology, transform except ImportError as e: print( f"{e}, [scikit-image] package and it's dependencies is required for MA-Net." ) import paddle import cv2 impor...
2.03125
2
custom_components/ge_home/entities/ccm/ge_ccm_pot_not_present_binary_sensor.py
87racer/ha_gehome
0
12771883
<reponame>87racer/ha_gehome from ..common import GeErdBinarySensor class GeCcmPotNotPresentBinarySensor(GeErdBinarySensor): @property def is_on(self) -> bool: """Return True if entity is not pot present.""" return not self._boolify(self.appliance.get_erd_value(self.erd_code))
2.109375
2
ScienceCruiseDataManagement/data_storage_management/management/commands/importfromstaging.py
Swiss-Polar-Institute/science-cruise-data-management
6
12771884
<reponame>Swiss-Polar-Institute/science-cruise-data-management<gh_stars>1-10 from django.core.management.base import BaseCommand, CommandError from data_storage_management import cifs_utils from data_storage_management.models import Directory, NASResource from django.conf import settings import os # This file is part...
2.28125
2
test/ably/restrequest_test.py
jvinet/ably-python
22
12771885
<reponame>jvinet/ably-python<gh_stars>10-100 import httpx import pytest from ably import AblyRest from ably.http.paginatedresult import HttpPaginatedResponse from test.ably.restsetup import RestSetup from test.ably.utils import BaseAsyncTestCase from test.ably.utils import VaryByProtocolTestsMetaclass, dont_vary_proto...
1.851563
2
schools2/pages.py
ferleyrincon/schools
0
12771886
<gh_stars>0 from otree.api import Currency as c, currency_range from ._builtin import Page, WaitPage from .models import Constants class consent(Page): form_model = 'player' form_fields = ['consent','consent_account'] def is_displayed(self): return self.round_number == 1 class ResultsWaitPage(Wa...
2.171875
2
tests/debug.py
theiviaxx/unhandled
0
12771887
<reponame>theiviaxx/unhandled import unhandled conf = { 'handlers': [ unhandled.VerboseExceptionHandler, unhandled.SimpleExceptionHandler ] } unhandled.init() def foo(): f = 1 print(f) 1/0 # with unhandled.pause(): foo()
2.265625
2
tools/update.py
HadesD/LaraCC
0
12771888
import os import subprocess subprocess.call([ 'git' , 'submodule' , 'foreach' , 'git' , 'checkout' , 'master' ]) subprocess.call([ 'git' , 'submodule' , 'foreach' , 'git' , 'pull' , 'origin' , 'master' ])
1.890625
2
api/main.py
reddimohan/FastAPI-RestAPI-PostgreSQL-PgAdmin-Authentication-docker
0
12771889
<gh_stars>0 from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.core import tasks from app.api_v1.api import api_router from app.db.base_class import Base from app.db.session import engine from app.core.config import settings def get_application(): app = FastAPI( tit...
2.046875
2
libra/validator_config.py
MoveOnLibra/libra-core
5
12771890
<filename>libra/validator_config.py from __future__ import annotations from libra.move_resource import MoveResource from libra.crypto.ed25519 import Ed25519PublicKey from libra.crypto.x25519 import X25519PublicKey from canoser import Struct, BytesT Multiaddr = BytesT() class ValidatorConfig(Struct): _fields = [ ...
1.945313
2
OSTL/P03-palindrome.py
ashnigga98/CollegeStuff
0
12771891
<reponame>ashnigga98/CollegeStuff # # if type(input) == string: # find if palindrome # elif type(input) == number: # find factorial # find if palindrome # def pal(st): l = len(st) i = 0 flag = True while i < l//2: if st[i] == st[l-i-1]: pass else: flag = False i += 1 return flag while True: ...
4.09375
4
python-packages/order_utils/src/zero_ex/order_utils/signature_utils.py
TheOceanTrade/0x-monorepo
0
12771892
<reponame>TheOceanTrade/0x-monorepo<gh_stars>0 """Signature utilities.""" from typing import Dict, Tuple import json from pkg_resources import resource_string from eth_utils import is_address, to_checksum_address from web3 import Web3 import web3.exceptions from web3.utils import datatypes from zero_ex.dev_utils.typ...
1.945313
2
app/create_app.py
KarolJaksik/IO-Project
3
12771893
<gh_stars>1-10 from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from passlib.apps import custom_app_context as pwd_context from flask_jwt_extended import JWTManager from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_o...
2.015625
2
src/magicdb/database/Database.py
CircleOnCircles/MagicDB
5
12771894
import firebase_admin from firebase_admin import credentials, firestore class Database: def __init__(self): self._conn = None def connect(self, creds=None, from_file=None): if not creds and not from_file: raise Exception("Credentials or service account json file path required to connect with firestore") ...
3.125
3
database/generic_repository.py
fcjack/InventoryManager
0
12771895
<gh_stars>0 import sqlite3 class GenericRepository: def get_connection(self): connection = sqlite3.connect('inventory') return connection
2.203125
2
python/tests/test_graph_business_trip.py
daveeS987/data-structures-and-algorithms
0
12771896
import pytest from graphs.graph import Graph, Vertex, Edge from graph_business_trip.graph_business_trip import business_trip def test_can_instantiate_Graph(): graph = Graph() assert graph assert graph._adjacency_list == {} def test_can_instantiate_Vertex(): vertex = Vertex() assert vertex a...
2.828125
3
elif_bayindir/phase_1/python_basic_1/day_8/q3.py
CodedLadiesInnovateTech/-python-challenge-solutions
6
12771897
<reponame>CodedLadiesInnovateTech/-python-challenge-solutions # Question 3 # Absolute file path. import os os.chdir("/home/elif/Desktop") print(os.path.abspath("elma.py"))
2.78125
3
env/sample_server.py
Normandez/ddos_watchdog
1
12771898
import http.server import socketserver import threading ADDR = "192.168.2.1" PORT = 80 class UDPHandler(socketserver.DatagramRequestHandler): def handle(self): data = self.request[0] socket = self.request[1] print ('client send: ', data) socket.sendto(b'Hello from server!', se...
3.265625
3
salinization/prod/salinization/config.py
elbertsoftware/SpringboardAIC
3
12771899
<gh_stars>1-10 import confuse config = None def get_config(): global config if config == None: config = confuse.Configuration('salinization', __name__) return config
1.890625
2
array_problems/Tests.py
daniel-zeiler/potential-happiness
0
12771900
import unittest import array_problems.Solutions as array_problems import array_problems.Solutions_Two as array_problems_two import array_problems.Solutions_Three as array_problems_three import array_problems.Solutions_Four as array_problems_four import array_problems.Solutions_Five as array_problems_five class Soluti...
2.953125
3
gru_multi_cnn.py
dtchuink/RCovnvNet
0
12771901
<filename>gru_multi_cnn.py ''' Created on Oct 2, 2018 @author: danielle ''' import torch from torch import nn from torch.autograd import Variable import torch.nn.functional as F from datasets import PartDataset from lr_scheduler import ReduceLROnPlateau from tensorflow.contrib.batching.ops.gen_batch_ops import batch ...
2.15625
2
tests/util/util.py
havardhuns/graphsense-REST
0
12771902
import yaml def yamldump(data): if isinstance(data, list): data = [d.to_dict() for d in data] else: data = data.to_dict() print(yaml.dump(data))
3.0625
3
seniorproject/recommendation/simpletocompound/simpletocompound.py
teammanicotti/writingstyle
0
12771903
<gh_stars>0 """Encapsulates the logic of determining sentence type and similarity.""" import logging from typing import List from spacy.tokens import Span from seniorproject.model.simpletocompoundrecommendation import \ SimpleToCompoundRecommendation from seniorproject.recommendation.simpletocompound.sentencecombi...
2.703125
3
petabvis/main.py
PEtab-dev/petab-interactive-viz
6
12771904
import argparse import sys # We need sys so that we can pass argv to QApplication import os import warnings import pandas as pd import petab.C as ptc import pyqtgraph as pg from PySide6 import QtWidgets, QtCore, QtGui from PySide6.QtWidgets import ( QVBoxLayout, QComboBox, QWidget, QLabel, QTreeView ) from petab ...
2.375
2
pi_mqtt_gpio/modules/rc522.py
BitStab/pi-mqtt-gpio
0
12771905
from pi_mqtt_gpio.modules import GenericSensor import logging REQUIREMENTS = ("spidev","mfrc522") CONFIG_SCHEMA = { "rc522": {"type": "integer", "required": True, "empty": False}, } _LOG = logging.getLogger("mqtt_gpio") class Sensor(GenericSensor): """ Implementation of RC255 NFC/RFID sensor. """ ...
2.796875
3
speakerz/accounts/views.py
avisalmon/speakerz
0
12771906
<filename>speakerz/accounts/views.py from django.urls import reverse_lazy from .forms import UserCreatForm from django.views.generic import CreateView class SignUp(CreateView): form_class = UserCreatForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html'
1.695313
2
nn_interpretability/dataset/imagenet_data_loader.py
miquelmn/nn_interpretability
41
12771907
<reponame>miquelmn/nn_interpretability import torch from pathlib import Path import torchvision.datasets as datasets from torchvision.transforms import transforms class ImageNetValDataLoader: def __init__(self, batch_size: int = 64): self.valdir = Path(__file__).parent.parent.parent.joinpath('data/ImageNe...
2.71875
3
xl_tensorflow/models/vision/detection/architecture/fpn.py
Lannister-Xiaolin/xl_tensorflow
0
12771908
# 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
1.90625
2
events/tests.py
Chiefautoparts/MillGeekV2
0
12771909
# # -*- coding: utf-8 -*- # from __future__ import unicode_literals # from django.test import TestCase # # Create your tests here. # class SimpleTest(TestCase): # self.failUnlessEqual(1 + 1, 2) # __test__ = {"doctest": """ # Another way to test that 1 + 1 is equal to 2. # >>> 1 + 1 == 2 # True # """}
2.609375
3
modules/models.py
ifr1m/pcdarts-tf2
26
12771910
<filename>modules/models.py import tensorflow as tf from absl import logging from tensorflow.keras import Model, Sequential from tensorflow.keras.layers import (Input, Dense, Flatten, Conv2D, AveragePooling2D, GlobalAveragePooling2D, ReLU) from m...
2.4375
2
server/app/utils/setup.py
WagnerJM/quality
0
12771911
import os import secrets def create_env_file(): prompt = "> " print("POSTGRES_USER= ?") POSTGRES_USER = input(prompt) print("POSTGRES_PW= ?") POSTGRES_PW = input(prompt) print("DATABASE= ?") DATABASE = input(prompt) print("REDIS_PW= ?") REDIS_PW = input(prompt) SECRET_KEY...
2.671875
3
paper code/solveCrossTime.py
PKandarp/TICC
393
12771912
from snap import * from cvxpy import * import math import multiprocessing import numpy from scipy.sparse import lil_matrix import sys import time import __builtin__ import code # File format: One edge per line, written as "srcID dstID" # Commented lines that start with '#' are ignored # Returns a TGraphVX...
2.3125
2
hcc_ws/src/estimation_pos/src/drone_object.py
Jackie890621/Localization_by_Apriltag
0
12771913
<reponame>Jackie890621/Localization_by_Apriltag<gh_stars>0 #!/usr/bin/env python2 from numpy.core.defchararray import count from numpy.lib.financial import nper import rospy import numpy as np import message_filters import cv2 from cv_bridge import CvBridge, CvBridgeError from darknet_ros_msgs.msg import BoundingBoxes...
2.140625
2
lm_pretrain/evaluate.py
dillondaudert/pssp_lstm
3
12771914
<reponame>dillondaudert/pssp_lstm """Evaluate the model""" # basic example of training a network end-to-end from time import process_time from pathlib import Path import tensorflow as tf, numpy as np import pandas as pd import numpy as np from .model_helper import create_model def evaluate(hparams, files, outfile=None...
2.578125
3
cls/prs.py
HesswareGmbH/clscenter-python
0
12771915
<reponame>HesswareGmbH/clscenter-python import requests import json import urllib import time import base64 verify_SSL = False # Some enums to make it easier to read # we use python 2.7 so enum.Enum is not available class CommandMode(object): ProgMode = 0 DataMode = 1 WaitForAck = 2 class MeterReading(object)...
2.8125
3
783_minimum_distance_between_BST_nodes.py
Sanster/LeetCode
2
12771916
from utils import TreeNode class Solution: pre = None min_val = 999999 def minDiffInBST(self, root: TreeNode) -> int: self.pre = None self.min_val = 999999 self.inorder(root) return self.min_val """ 中序遍历可以得到从小到大的值,只要当前值和前一个最小的值做减法就可以了 """ def inorder(self...
3.234375
3
tests/test_session_creation.py
pyansys/openapi-common
1
12771917
import json import os from functools import wraps import pytest import requests_mock import requests_ntlm from ansys.openapi.common import ( SessionConfiguration, ApiClientFactory, ApiConnectionException, ) SERVICELAYER_URL = "http://localhost/mi_servicelayer" SECURE_SERVICELAYER_URL = "https://localhost...
2.234375
2
setup.py
guidow/pyfarm-master
0
12771918
<reponame>guidow/pyfarm-master # No shebang line, this module is meant to be imported # # Copyright 2013 <NAME> # Copyright 2015 Ambient Entertainment GmbH & Co. KG # # 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 c...
1.5
2
essay/models.py
lukasy2/strona
0
12771919
<gh_stars>0 from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext as _ from quiz.models import Question @python_2_unicode_compatible class Essay_Question(Question): def check_if_correct(self, guess): return Fals...
2.046875
2
tests/test_pyprocessing_math.py
jeacom25b/pyprocessing
0
12771920
from unittest import TestCase from copy import copy from pyprocessing.math import PVector class PyProcessingMathTest(TestCase): def setUp(self): pass def test_pvector_instanciation(self): ''' Test instanciating a vector ''' vector = PVector(0, 0, 0) self.asser...
3.3125
3
setup.py
gerpark/ftsim
0
12771921
<filename>setup.py #!/usr/bin/env python3 # encoding: UTF-8 from setuptools import setup, find_packages import pathlib VERSION = '0.9.3' DESCRIPTION = 'Simulates and visualises transport of loadunits in a warehouse environment.' # Get the long description from the README file here = pathlib.Path(__file__).parent.res...
1.414063
1
scripts/run_telathbot.py
telathio/telathbot
9
12771922
<filename>scripts/run_telathbot.py import httpx import typer def main( url: str = typer.Option( ..., help="Fully formed URL (i.e. http://telathbot.com", envvar="TELATHBOT_URL" ) ): typer.echo("Starting TelathBot SafetyTools checks.") ip_check_resp = httpx.post( f"{url}/appdata/check/ip...
2.71875
3
DWM/lab1.py
Cha-V/VSCodes
1
12771923
import mysql.connector import pandas as pd from sqlalchemy import create_engine hostname="localhost" dbname="DWM" uname="root" pwd="<PASSWORD>" engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}".format(host=hostname, db=dbname, user=uname, pw=pwd)) dataset = pd.read_csv('Student_details.csv') dataset
2.84375
3
acnportal/acnsim/tests/test_base.py
gazzayeah/acnportal
0
12771924
<reponame>gazzayeah/acnportal import unittest import numpy as np from .. import ChargingNetwork from ..base import ErrorAllWrapper class TestErrorAllWrapper(unittest.TestCase): @classmethod def setUpClass(cls): cls.builtin_data = 2 cls.builtin_wrapper = ErrorAllWrapper(cls.builtin_data) ...
2.703125
3
research/attention_ocr/python/datasets/testdata/fsns/download_data.py
gujralsanyam22/models
82,518
12771925
<gh_stars>1000+ import urllib.request import tensorflow as tf import itertools URL = 'http://download.tensorflow.org/data/fsns-20160927/testdata/fsns-00000-of-00001' DST_ORIG = 'fsns-00000-of-00001.orig' DST = 'fsns-00000-of-00001' KEEP_NUM_RECORDS = 5 print('Downloading %s ...' % URL) urllib.request.urlretrieve(URL,...
2.765625
3
libs/pipeline_monitor/test.py
silentmonk/KubeFlow
2,527
12771926
from pipeline_monitor import prometheus_monitor as monitor _labels= {'a_label_key':'a_label_value'} @monitor(labels=_labels, name="test_monitor") def test_log_inputs_and_outputs(arg1: int, arg2: int): return arg1 + arg2 test_log_inputs_and_outputs(4, 5)
1.671875
2
PinEstate/adverts/migrations/0001_initial.py
ohouens/Real_Estates_Recommender_System
1
12771927
<gh_stars>1-10 # Generated by Django 3.2.4 on 2021-07-30 16:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Estate', fi...
1.851563
2
torchlib/visualization.py
CarlosPena00/kaggle-datasciencebowl-2018
0
12771928
<gh_stars>0 import cv2 import numpy as np import matplotlib.pyplot as plt def torgb(im): if len(im.shape)==2: im = np.expand_dims(im, axis=2) im = np.concatenate( (im,im,im), axis=2 ) return im def setcolor(im, mask, color): tmp=im.copy() tmp=np.reshape( tmp, (-1, im.shap...
2.5625
3
cowin_project/models/sub_project/prev_investment_management/sub_project_establishment.py
shangdinvxu/cowinaddons
0
12771929
<reponame>shangdinvxu/cowinaddons # -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.modules.module import get_module_resource from odoo import tools from odoo.exceptions import UserError # 项目立项 构建小项目 class Cowin_project_subproject(models.Model): _name = 'cowin_project.cowin_subpro...
2.046875
2
tests/testutils.py
xxh840912/zask
0
12771930
import random import os _tmpfiles = [] def random_ipc_endpoint(): tmpfile = '/tmp/zerorpc_test_socket_{0}.sock'.format( str(random.random())[2:]) _tmpfiles.append(tmpfile) return 'ipc://{0}'.format(tmpfile) def teardown(): global _tmpfiles for tmpfile in _tmpfiles: print 'unlink...
2.5625
3
authentication/templates/urls.py
aruna1993/django-rest-framework-crud-jwt
0
12771931
<gh_stars>0 from django.contrib import admin from rest_framework.documentation import include_docs_urls from django.urls import include, path from rest_framework.schemas import get_schema_view from django.views.generic import TemplateView # urls urlpatterns = [ path('openapi/', get_schema_view( title="Movie Restf...
1.765625
2
benchmark.py
frawi/mptcp-tests
2
12771932
#!/usr/bin/env python2 def create_network(paths, bw, loss, latency): from mininet.net import Mininet from mininet.link import TCLink from mininet.node import CPULimitedHost, Controller from mininet.log import info net = Mininet(controller=Controller, link=TCLink) # since we need a switch we a...
2.5
2
survey/forms.py
Udantu/portfolio-v1
0
12771933
from django import forms class AnswerQuestion(forms.Form): answer = forms.IntegerField()
1.867188
2
tools/wptrunner/wptrunner/browsers/safari_webdriver.py
Ms2ger/web-platform-tests
1
12771934
<gh_stars>1-10 from .base import inherit from . import safari from ..executors.executorwebdriver import (WebDriverTestharnessExecutor, # noqa: F401 WebDriverRefTestExecutor) # noqa: F401 inherit(safari, globals(), "safari_webdriver") # __wptrunner__ magically appears fro...
1.609375
2
opentsdb/exceptions.py
razvandimescu/opentsdb-py
48
12771935
<filename>opentsdb/exceptions.py class TSDBClientException(Exception): pass class TSDBNotAlive(TSDBClientException): pass class TagsError(TSDBClientException): pass class ValidationError(TSDBClientException): pass class UnknownTSDBConnectProtocol(TSDBClientException): def __init__(self, pr...
2.25
2
docs/migrations/0003_documentation_language.py
lnxpy/docket
3
12771936
<reponame>lnxpy/docket # Generated by Django 3.0.4 on 2020-04-04 13:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('docs', '0002_auto_20200404_1326'), ] operations = [ migrations.AddField( model_name='documentation', ...
1.578125
2
Iniciante-Begginer/Python/#1001 - #1050/#1010-CalculoSimples.py
jocelinoFG017/Beecrowd-judge-solutions
2
12771937
<gh_stars>1-10 # Author: <NAME> a, b = input().split(), input().split() q1 = int(a[1]) v1 = float(a[2]) q2 = int(b[1]) v2 = float(b[2]) t1 = q1 * v1 t2 = q2 * v2 tt = t1 + t2 print('VALOR A PAGAR: R$ %.2f' %tt)
2.875
3
Preprocess/Mat2Edgelist.py
yashchandak/GNN
1
12771938
import networkx as nx from scipy.io import loadmat x = loadmat(dataset) dataset='blogcatalog.mat' x = loadmat(dataset) x = x['network'] G = nx.from_scipy_sparse_matrix(x) del x f=open("BC_DW.edgelist",'wb') nx.write_edgelist(G, f)
2.78125
3
utility/profile.py
mingsumsze1/mcts
0
12771939
from pyinstrument import Profiler from functools import wraps def profile(func): @wraps(func) def wrapper(*args, **kwargs): profiler = Profiler() profiler.start() results = func(*args, **kwargs) profiler.stop() profiler.output_text() return results return wrapper
2.46875
2
wrappers/python/virgil_crypto_lib/foundation/_c_bridge/_vscf_message_info_editor.py
odidev/virgil-crypto-c
26
12771940
<reponame>odidev/virgil-crypto-c # Copyright (C) 2015-2021 Virgil Security, Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # (1) Redistributions of source code must retain the abov...
0.6875
1
Lib/site-packages/jupyterlab_server/process_app.py
edupyter/EDUPYTER38
0
12771941
"""A lab app that runs a sub process for a demo or a test.""" import sys from jupyter_server.extension.application import ExtensionApp, ExtensionAppJinjaMixin from tornado.ioloop import IOLoop from .handlers import LabConfig, add_handlers from .process import Process class ProcessApp(ExtensionAppJinjaMixin, LabConf...
2.453125
2
subway/examples/miscs/pi_run.py
Rails-on-HPC/subway
4
12771942
from random import random import sys def pie(times=100): incircle = 0 for _ in range(times): x = random() y = random() if x * x + y * y < 1: incircle += 1 return incircle / times * 4 if __name__ == "__main__": with open(sys.argv[1], "r") as f: times = f.re...
2.96875
3
securityheaders/checkers/xpoweredby/__init__.py
th3cyb3rc0p/securityheaders
151
12771943
from .present import XPoweredByPresentChecker __all__ = ['XPoweredByPresentChecker']
1.054688
1
scripts/makedocu.py
lsyefficient/qwtplot3d
64
12771944
<gh_stars>10-100 import os.path import shutil import tarfile import zlib import zipfile from time import gmtime, strftime refuseddirs = ['CVS','images'] refuseddirsextra = ['CVS','small'] source = 'V:\\\\cvs\\qwtplot3d\\doc\\' sourceim = 'V:\\\\cvs\\qwtplot3d\\doc\\images\\' zipname = 'V:\\\\cvs\\uploads\\qwtplot3d-d...
2.359375
2
autotabular/pipeline/components/classification/gaussian_nb.py
jianzhnie/AutoTabular
48
12771945
import numpy as np from autotabular.pipeline.components.base import AutotabularClassificationAlgorithm from autotabular.pipeline.constants import DENSE, PREDICTIONS, UNSIGNED_DATA from ConfigSpace.configuration_space import ConfigurationSpace class GaussianNB(AutotabularClassificationAlgorithm): def __init__(sel...
2.484375
2
Python/Merge_sort.py
Harshalszz/-HACKTOBERFEST2K20
30
12771946
def merge_sort(unsorted_list): if len(unsorted_list) <= 1: return unsorted_list # Finding the middle point and partitioning the array into two halves middle = len(unsorted_list) // 2 left = unsorted_list[:middle] right = unsorted_list[middle:] left = merge_sort(left) right = merge_s...
4.28125
4
matlab_ext/code-miners/projects/prepro/src_2/hided/tmp.py
zaqwes8811/coordinator-tasks
0
12771947
<gh_stars>0 ''' удаляем комментаии ''' def purgeFromComments( fname ): # читаем в список linesFromInc = file2ListLines( fname ) # ищем закомментированные строки и пишем незак. в файл try: f = io.open( fname, "wt")#, encoding='utf-8' ) # пусть так и остается try: for at in linesFromInc: if not ';' in at...
3.078125
3
qarc-gym/qarc-innovation.py
kasimte/QARC
40
12771948
import gym import gym_qarc import numpy as np from inet import InnovationNetwork import os import tensorflow as tf VIDEO_BIT_RATE = [0.01, 0.3, 0.5, 0.8, 1.1, 1.4] A_DIM = len(VIDEO_BIT_RATE) S_INFO = 6 S_LEN = 10 # take how many frames in the past LR_RATE = 1e-4 RAND_RANGE = 1000 env = gym.make('QARC-v0') total_ste...
2.4375
2
StatisticsPreview/migrations/0003_auto_20190828_1128.py
tifat58/lsv-c4-django-webexperiment
1
12771949
<filename>StatisticsPreview/migrations/0003_auto_20190828_1128.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('StatisticsPreview', '0002_auto_20190828_1017'), ] operations = [ ...
1.484375
1
database.py
nathanielangafor/Dandy-2021-Backend
0
12771950
<gh_stars>0 import json import sqlite3 import base64 import random from google.cloud import storage import string from PIL import Image from io import BytesIO import os from flask import Flask, request app = Flask(__name__) app.secret_key = b"Da ya biezlikiy patamy shto u menya nie litso" from PIL import ImageFile Ima...
2.5625
3