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 |
|---|---|---|---|---|---|---|
paccmann_sets/utils/loss_setmatching.py | PaccMann/paccmann_sets | 3 | 50400 | <reponame>PaccMann/paccmann_sets
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.one_hot_categorical import OneHotCategorical
class SetMatchLoss(nn.Module):
def __init__(
self,
loss: str,
ce_type: str = 'row',
temperature: float = None,
... | 2.375 | 2 |
tests/unit/test_context.py | TiesWestendorp/MTG-Mana-Simulator | 10 | 50401 | <gh_stars>1-10
"""
Unit tests for Context class
"""
from mtg_mana_simulator.context import Context
def test_discard_cards():
"""
Test discard_cards instance method
"""
for card_to_discard in range(7):
context = Context(hand=list(range(7)))
context.discard_cards([card_to_discard])
... | 2.875 | 3 |
cds_ils/patrons/indexer.py | kpsherva/cds-ils | 6 | 50402 | <reponame>kpsherva/cds-ils
# Copyright (C) 2021 CERN.
#
# CDS-ILS is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""Patron Indexer for CDS-ILS."""
from flask import current_app
from invenio_accounts.models import User
from invenio_ap... | 1.921875 | 2 |
microservices/svc/echo/run.py | Syu-syusan/internship | 0 | 50403 | <gh_stars>0
import asyncio
import conf
import server
if __name__ == "__main__":
asyncio.run(server.run(host=conf.APP_IP_ADDRESS, port=conf.APP_PORT))
| 1.75 | 2 |
nlptoolkit/data/__init__.py | jianzhnie/d2nlp | 3 | 50404 | '''
Author: jianzhnie
Date: 2022-03-04 17:13:55
LastEditTime: 2022-03-04 17:13:55
LastEditors: jianzhnie
Description:
'''
| 1.023438 | 1 |
examples/simple.py | tomamore/AnyDeck | 0 | 50405 | from anydeck import AnyDeck
# Create a default deck
# A default deck consists of a standard deck of poker cards with four suits with cards numbered 2 through 10, as well
# as a Jack, Queen, King, and Ace for each suit. The standard deck gives a value to the card equal to their
# face value further Jack, Queen, and Kin... | 3.703125 | 4 |
Web_Server/webapps/buildinginfos/views.py | ajfar-bem/wisebldg | 0 | 50406 | import json
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from webapps.buildinginfos.models import BuildingInfo
from _utils.device_list_utils import get_device_list_and... | 2.03125 | 2 |
self_virtualenv/do_virtualenv.py | zhaoyu69/python3-learning | 1 | 50407 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# virtualenv: 为每个应用创建一套“隔离”的Python运行环境。
# pip3 install virtualenv
# 整一套独立的python运行环境
# 1. 创建目录
# mkdir myproject
# cd myproject/
# 2. 创建一个独立的Python运行环境,命名为venv
# virtualenv --no-site-packages venv
# --no-site-packages 不带任何第三方包
# 进入环境
# source venv/bin/activate
# venv... | 2.125 | 2 |
beekeeper/admin.py | evan10s/beekeeper | 0 | 50408 | from django.contrib import admin
from django.conf import settings
# Register your models here.
from .models import Treatment
admin.site.register(Treatment)
| 1.234375 | 1 |
tests/utils/test_serializer.py | guilhermevarela/ilu | 2 | 50409 | <filename>tests/utils/test_serializer.py
import os
import unittest
from ilurl.utils.serialize import Serializer
class TestSerialization(unittest.TestCase):
class Foo(Serializer):
def __init__(self, foo):
self.foo = foo
def setUp(self):
'''Define the simplest test class'''
... | 2.859375 | 3 |
enthought/help/help_plugin/help_code.py | enthought/etsproxy | 3 | 50410 | # proxy module
from __future__ import absolute_import
from apptools.help.help_plugin.help_code import *
| 1.132813 | 1 |
py/base/ItemMap.py | jeremybennett/force-riscv | 0 | 50411 | <filename>py/base/ItemMap.py
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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.171875 | 2 |
python/ql/test/query-tests/Security/CWE-079/jinja2_escaping.py | vadi2/codeql | 4,036 | 50412 |
Environment(loader=templateLoader, autoescape=fake_func())
from flask import Flask, request, make_response, escape
from jinja2 import Environment, select_autoescape, FileSystemLoader, Template
app = Flask(__name__)
loader = FileSystemLoader( searchpath="templates/" )
unsafe_env = Environment(loader=loader)
safe1_env... | 2.59375 | 3 |
tests/executor/test_model_results_main.py | adolgert/cascade | 0 | 50413 | import pandas as pd
import pytest
from cascade.executor.model_results_main import _get_model_results
def test_get_model_results_inputs_ok(ihme):
"""at_mvid=265844 has 5850 rows, ode_mvid=102680 has 238836 rows
"""
results_columns = ['model_version_id', 'year_id', 'location_id', 'sex_id',
... | 2.5 | 2 |
morphology_embed.py | hbatta/morphological-nmt | 0 | 50414 | # -*- coding: utf-8 -*-
"""Morphology_embed.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1uZUe-O4GgKuMK1FfbAV7xztgtD4lWEEC
"""
import stanza
import argparse
parser = argparse.ArgumentParser(description='A tutorial of argparse!')
parser.add_arg... | 2.8125 | 3 |
Projects/Project 0/Warm-up/loops.py | ivenpoker/Python-Projects | 1 | 50415 | <filename>Projects/Project 0/Warm-up/loops.py<gh_stars>1-10
#!/usr/bin/env python3
#: Program Purpose:
#: Read an integer N. For all non-negative integers i < N
#: print i * i.
#:
#: Program Author: <NAME> <<EMAIL>
#: Program Date : 11/04/2019 (mm/dd/yyyy)
def process(int_val):
for x in range(i... | 3.546875 | 4 |
task_runner/FHIRTest_Sandbox/FHIR_Operation/fhir_test_cases.py | ideaworld/Tester | 0 | 50416 | from .FHIR_Generator import Generator
from .genomics_test_generator.fhir_genomics_test_gene import *
import os
spec_basepath = os.path.join(os.getcwd(), 'task_runner/resources/spec/')
def get_resource_correct_cases(version, resource_type):
'''
get correct resource objects for a certain resource type
'''
... | 2.3125 | 2 |
cap1/c1e2.4.py | JoseArtur/phyton-exercices | 0 | 50417 | b=5
a=3
print((2*a)*(3*b))
| 3.234375 | 3 |
armstrong/core/arm_layout/backends.py | cirlabs/armstrong.core.arm_layout | 0 | 50418 | from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
class BasicRenderModelBackend(object):
def get_layout_template_name(self, model, name):
ret = []
for a in model.__class__.mro():
if not hasattr(a, "_meta"):
continue
... | 2.40625 | 2 |
Class 12/File_Handling/Text files/lab_act3.py | itsezsid/computer-science | 0 | 50419 | def names(name_list):
with open('textfile3.txt', 'w') as myfile:
myfile.writelines(name_list)
myfile.close()
print(name_list)
menu()
def display_name(n):
with open('textfile3.txt', 'r') as myfile:
name_list = myfile.readlines()
print(name_list[n-1])
retu... | 4.3125 | 4 |
scheme/tests/07.py | sfailsthy/CS-61A | 0 | 50420 | test = {
'name': 'Problem 7',
'points': 1,
'suites': [
{
'cases': [
{
'answer': '103495fc3358e1b6354d1d4a277039e6',
'choices': [
r"""
Pair('quote', Pair(A, nil)), where:
A is the quoted expression
""",
r"""
... | 2.328125 | 2 |
tools/gz.py | codeyu/unihandecode-net | 0 | 50421 | import os, gzip
INPUT_FILES=['kr_codepoints.json','ja_codepoints.json','zh_codepoints.json','vn_codepoints.json','yue_codepoints.json','unicodepoints.json']
for f in INPUT_FILES:
source = os.path.join('result', f)
input = open(source, 'rb')
s = input.read()
input.close()
dest =... | 2.65625 | 3 |
stk-in4300/oblig1/lib/functions.py | simehaa/MachineLearning | 1 | 50422 | <gh_stars>1-10
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
def read_file(filename):
"""Read a csv data file located in the ./data/ directory
Return design matrix X and y-data"""
DATA_DIR = "./data"
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
DAT... | 3.21875 | 3 |
src/tests/test_logger.py | hypergol/hypergol | 49 | 50423 | <filename>src/tests/test_logger.py<gh_stars>10-100
import os
import pickle
from unittest import TestCase
from hypergol import Logger
from pathlib import Path
class TestLogger(TestCase):
def __init__(self, methodName):
super(TestLogger, self).__init__(methodName=methodName)
self.logFile = Path('te... | 2.78125 | 3 |
summarize/test.py | ChaiJT/summarize | 1 | 50424 |
# from textrank4zh import TextRank4Keyword
#
# test_text = open("test_text.txt", "r", encoding="utf-8").read()
#
#
# tr4w = TextRank4Keyword()
# tr4w.analyze(text=test_text,lower=True, window=2, pagerank_config={'alpha':0.85})
#
# for item in tr4w.get_keywords(10, word_min_len=1):
# print(item.word, item.weight)
#... | 2.90625 | 3 |
triangle.py | Mohan-V-P/Shapes | 0 | 50425 | import cv2
import numpy as np
from shapes import Myinit
class Triangle(Myinit):
def __init__(self):
super(Triangle, self).__init__()
self.vertices = np.array([[100,50], [150,150], [50,150]],np.int32)
self.vertices = self.vertices.reshape((-1, 1, 2))
self.color=(255,0,255)
... | 3.171875 | 3 |
filter_numberbatch.py | frankier/AutoExtend | 0 | 50426 | <gh_stars>0
import click
def filter_lines(input, prefix):
for line in input:
if line.startswith(prefix):
yield line
@click.command('filter-conceptnet')
@click.argument("lang")
@click.argument("input", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def main(lang, input,... | 2.984375 | 3 |
preprocessor/python/Z_common/process.py | SpiritFlag/FM0-Decoder | 2 | 50427 | import sys
import os
import timeit
from global_vars import *
def common_process(file, fnc, isFile):
try:
if file != None and os.path.exists(file):
select = input("FILE is already exist. Press 'Y' if you want to rewrite. ")
if select != 'Y':
print("Execution aborted..")
... | 2.828125 | 3 |
autocert/__init__.py | peng22/auto-cert-edited | 9 | 50428 | default_app_config = 'autocert.apps.DjangoAutocertConfig'
| 0.949219 | 1 |
day05/ventsday1.py | chipmonkey/adventofcode2021 | 0 | 50429 | import numpy as np
class vents:
def __init__(self, segments):
self.segments = segments
(self.maxx, self.maxy) = self._getmaxxy()
self.board = np.zeros((self.maxx+1, self.maxy+1), dtype=int)
def _getmaxxy(self):
allxs = [x[0] for x in self.segments]
allxs.extend([x[2] ... | 3.203125 | 3 |
koapy/cli/utils/credential.py | resoliwan/koapy | 1 | 50430 | <filename>koapy/cli/utils/credential.py
import os
import click
from koapy.config import (
config,
config_from_dict,
default_user_config_path,
save_config,
user_config,
)
def prompt_credential():
credential = config.get("koapy.backend.kiwoom_open_api_plus.credential")
default_user_id = c... | 2.734375 | 3 |
angeline_yu/SARS.py | homologus/2020-intermediate-class | 3 | 50431 | <filename>angeline_yu/SARS.py
from Bio import SeqIO
from Bio.Seq import Seq
#Accessing SARS Genome and storing it in reads
reads = list(SeqIO.parse("/share/SARS/SARS-2020.fasta", "fasta"))
#translating the 3 reading frames
translation1 = reads[0].seq.translate()
translation2 = reads[0].seq.translate()
translation3 = ... | 3.34375 | 3 |
gui.py | PLepelley/trombinoscope | 0 | 50432 | from tkinter import *
from PIL import Image, ImageTk
import sql
import mysql.connector as msq
# Ouverture de la connexion
# --------------------------------------------------------
config = {
"user": "root",
"password": "<PASSWORD>",
"host": "127.0.0.1",
"port": "8081",
"database": "trombinoscope"... | 2.734375 | 3 |
Linux/InfluxConnector2.py | ARMAGEDONgtx/IoT-system-PLC-data-to-InfluxDB | 13 | 50433 | '''
PLC data acquisition APP.
Storage: InfluxDB
Fetch API: Snap7
GUI: PySimpleGUI
Author: <NAME>
'''
import xml.etree.ElementTree as ET
import snap7
import time
from snap7.util import *
from snap7.snap7types import *
import influxdb
import multiprocessing
from collections import defaultdict
from threading import Thr... | 2.640625 | 3 |
keras_text_classifier/classifier_v3.py | hanstananda/ndsc_beginner | 1 | 50434 | # This is used for testing Fine Tune Hyper-Parameters
from datetime import datetime
import itertools
import json
import matplotlib.pyplot as plt
import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.wrappers.scikit_learn import KerasClassifier
from keras_preprocessing.sequence import pad_sequences
... | 2.71875 | 3 |
src/utils/audio.py | Jiyao17/fledge | 4 | 50435 |
import os
from torchaudio.datasets import SPEECHCOMMANDS
import torch
class SubsetSC(SPEECHCOMMANDS):
def __init__(self, subset, data_path):
super().__init__(root=data_path, download=True)
def load_list(filename):
filepath = os.path.join(self._path, filename)
with open(f... | 2.65625 | 3 |
spiders/a505.py | senlyu163/crawler | 0 | 50436 | <reponame>senlyu163/crawler<filename>spiders/a505.py
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from ..utils import extract_CN_from_content
from ..items import ScrapySpiderItem
import re
class A505Spider(CrawlSpider):
name = '5... | 2.84375 | 3 |
tools/network_datatypes/network.py | p2m2/galaxy-tools | 1 | 50437 | <reponame>p2m2/galaxy-tools<gh_stars>1-10
"""
Network sbml class
"""
import logging, os, os.path, sys, time, tempfile, shutil, string, glob, re
from galaxy.datatypes.sniff import *
from galaxy.datatypes import data
from galaxy.datatypes.metadata import MetadataElement
from galaxy.datatypes.xml import GenericXml
fro... | 2.453125 | 2 |
setup.py | dmitriiweb/clpb | 1 | 50438 | from setuptools import setup
with open('README.rst') as readme:
r = str(readme.read())
setup(
name='clpb',
version='1.0.0',
url='https://github.com/dmitriiweb/clpb',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description=' Command line progress bar for Python 3',
long_... | 1.1875 | 1 |
wandb/integration/kfp/wandb_logging.py | soumik12345/client | 0 | 50439 | def wandb_log( # noqa: C901
func=None,
# /, # py38 only
log_component_file=True,
):
"""Wrap a standard python function and log to W&B"""
import json
import os
from functools import wraps
from inspect import Parameter, signature
from kfp import components
from kfp.components im... | 2.34375 | 2 |
Python-Advanced/tuples_and_sets_exercise/battle_of_names.py | Xamaneone/SoftUni-Intro | 0 | 50440 | n = int(input())
even_numbers_set = set()
odd_numbers_set = set()
for current_iteration_count in range(1, n+1):
name = input()
current_sum = sum([ord(el) for el in name]) // current_iteration_count
if current_sum % 2 == 0:
even_numbers_set.add(current_sum)
else:
odd_numbers_set.add(cu... | 4 | 4 |
tests/integration/baseTestValidator.py | COEJKnight/one | 1 | 50441 | <gh_stars>1-10
import unittest
from datetime import datetime, timedelta
import os
from random import randint
import boto.s3
from webtest import TestApp
from boto.s3.key import Key
from dataactvalidator.health_check import create_app
from dataactcore.interfaces.db import GlobalDB
from dataactcore.scripts.databaseSetup... | 2.078125 | 2 |
tests/unit/nano_tcg/entities/test_funcs.py | pitzer42/nano_tcg | 1 | 50442 | <reponame>pitzer42/nano_tcg
from nano_magic.entities import draw, move
def test_draw():
n = 1
deck = ['1', '2', '3']
hand = []
draw(n, deck, hand)
assert deck == ['1', '2']
assert hand == ['3']
def test_move():
i = 1
hand = ['1', '2', '3']
board = []
move(i, hand, board)
... | 2.40625 | 2 |
product_spider/items.py | Pandaaaa906/product_spider | 0 | 50443 | <gh_stars>0
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
# import scrapy
import scrapyautodb as scrapy
class JkItem(scrapy.OrderedItem):
cat_no = scrapy.Field()
en_name = scrapy.Field()
chs_name = scr... | 2.328125 | 2 |
maskrcnn_benchmark/modeling/roi_heads/box_head/roi_box_predictors.py | CityU-AIM-Group/NLTE | 1 | 50444 | <gh_stars>1-10
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from maskrcnn_benchmark.modeling import registry
import torch
from torch import nn
import torch.nn.functional as F
@registry.ROI_BOX_PREDICTOR.register("FastRCNNPredictor")
class FastRCNNPredictor(nn.Module):
def __init__(self, ... | 1.960938 | 2 |
sample.py | Wentao-Shi/Molecule-RNN | 3 | 50445 | <filename>sample.py
# Copyright: <NAME>, 2021
from dataloader import SELFIEVocab, RegExVocab, CharVocab
from model import RNN
import argparse
import torch
import yaml
import selfies as sf
from tqdm import tqdm
from rdkit import Chem
# suppress rdkit error
from rdkit import rdBase
rdBase.DisableLog('rdApp.error')
def... | 2.234375 | 2 |
moe/tests/bandit/__init__.py | dstoeckel/MOE | 966 | 50446 | # -*- coding: utf-8 -*-
r"""Testing code for the (Python) bandit library.
Testing is done via the Testify package:
https://github.com/Yelp/Testify
This package includes:
* Test cases/test setup files
* Tests for bandit/epsilon: :mod:`moe.tests.bandit.epsilon`
* Tests for bandit/ucb: :mod:`moe.tests.bandit.ucb`
* Tes... | 1.5625 | 2 |
examples/04_Goddard_0knot.py | likping/OpenGoddard | 81 | 50447 | # -*- coding: utf-8 -*-
# Copyright 2017 Interstellar Technologies Inc. All Rights Reserved.
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from OpenGoddard.optimize import Problem, Guess, Condition, Dynamics
class Rocket:
g0 = 1.0 # Gravity at surface [-]
def __in... | 2.796875 | 3 |
paper/make_tarball.py | ADACS-Australia/quokka | 11 | 50448 | import argparse
from pathlib import Path
import tarfile
from zipfile import ZipFile
from scanf import scanf
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tarball_output')
parser.add_argument('tex_files',nargs='*')
args = parser.parse_args()
files = []
... | 2.875 | 3 |
modules/2.79/bpy/types/TextCurve.py | cmbasnett/fake-bpy-module | 0 | 50449 | <filename>modules/2.79/bpy/types/TextCurve.py
TextCurve.text_boxes = None
| 1.054688 | 1 |
start.py | alois21/instagram-bot | 0 | 50450 | # ┌────────────────────────────────────────────────────────────────────────┐
# │ InstaBot - Python Selenium Bot │
# ├────────────────────────────────────────────────────────────────────────┤
# │ Copyright © 2019 <NAME> |
# | (https://github.com... | 2.78125 | 3 |
Idat_Python2022/Semana_9/Ejercicio10.py | Kennethguerra3/Python_Ejercicio_2022 | 0 | 50451 | <gh_stars>0
num = int(input("Numero: "))
for i in range(1,13):
m = num * i
print(num,"X",i,"=",m) | 3.796875 | 4 |
app/core/tests/test_models.py | horzym/recipe-app-api | 0 | 50452 | <gh_stars>0
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='<EMAIL>', password='<PASSWORD>'):
"""Create user"""
return get_user_model().objects.create_user(email, password)
class ModelTest(TestCase):
def test_create_superus... | 2.859375 | 3 |
MagicTelecomAPILib/Models/Account.py | MagicTelecom/mt_python_api | 0 | 50453 | # -*- coding: utf-8 -*-
"""
MagicTelecomAPILib.Models.Account
This file was automatically generated by APIMATIC v2.0 on 06/22/2016
"""
from MagicTelecomAPILib.APIHelper import APIHelper
class Account(object):
"""Implementation of the 'Account' model.
TODO: type model description here.
... | 2.75 | 3 |
experiment_housing_1.py | slonoko/sentiment-analysis | 0 | 50454 | <filename>experiment_housing_1.py
from azureml.core import Experiment, RunConfiguration, ScriptRunConfig, Workspace, Environment, Model
from azureml.train.dnn import TensorFlow
from azureml.core.conda_dependencies import CondaDependencies
ws = Workspace.from_config()
environment = Environment.from_conda_specification... | 2.515625 | 3 |
lib/segmentation/algorithm.py | rusty1s/embedded_gcnn | 74 | 50455 | <reponame>rusty1s/embedded_gcnn<gh_stars>10-100
import numpy as np
from skimage import color, segmentation
def slic(image, num_segments, compactness=10, max_iterations=10, sigma=0):
image = _preprocess(image)
return segmentation.slic(image, num_segments, compactness, max_iterations,
... | 2.265625 | 2 |
inoutdoor_dataset/inoutdoor_dataset_writer.py | meyerjo/inoutdoor_tfrecord | 0 | 50456 | import os
import re
import json
from os.path import expanduser
import zipfile
import datetime
import tensorflow as tf
import numpy as np
from utils import mkdir_p
from inoutdoor_dataset_download import InoutdoorDatasetDownload
from inoutdoor_versions import *
from tf_features import *
from PIL import Image
class In... | 2.125 | 2 |
distributed/s3.py | gdementen/distributed | 1 | 50457 | from __future__ import print_function, division, absolute_import
import logging
import io
from warnings import warn
from dask import bytes as dbytes
from s3fs import S3FileSystem
from .executor import default_executor, ensure_default_get
logger = logging.getLogger(__name__)
def read_text(fn, keyname=None, encodi... | 2.265625 | 2 |
dexp/processing/utils/_test/test_scatter_gather_i2v.py | haesleinhuepf/dexp | 16 | 50458 | import numpy as np
from arbol import aprint
from dexp.processing.utils.scatter_gather_i2v import scatter_gather_i2v
from dexp.utils.backends import Backend
from dexp.utils.testing.testing import execute_both_backends
from dexp.utils.timeit import timeit
@execute_both_backends
def test_scatter_gather_i2v(ndim=3, leng... | 2.34375 | 2 |
indice_pollution/__init__.py | betagouv/indice_pollution | 2 | 50459 | <filename>indice_pollution/__init__.py
import requests
import csv
from sqlalchemy.orm import joinedload
from indice_pollution.history.models.commune import Commune
from indice_pollution.history.models.indice_atmo import IndiceATMO
from indice_pollution.history.models.episode_pollution import EpisodePollution
from flas... | 1.945313 | 2 |
073_setMatrixZeroes.py | stuti-rastogi/leetcode-python-solutions | 4 | 50460 | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
if not matrix:
return
# use first row as "cols" array, use first column as "rows" array
# to do that, first store what ne... | 3.765625 | 4 |
leetcode/554_brick_wall/554_brick_wall.py | ryangillard/misc | 0 | 50461 | class Solution(object):
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
hash_map = {}
for row in wall:
sum = 0
for brick in row[:-1]:
sum += brick
hash_map[str(sum)]... | 3.359375 | 3 |
examples/problems/burgers.py | s274001/PINA | 4 | 50462 | <gh_stars>1-10
import torch
from pina.problem import TimeDependentProblem, SpatialProblem
from pina.operators import grad
from pina import Condition
from pina.span import Span
class Burgers1D(TimeDependentProblem, SpatialProblem):
spatial_variables = ['x']
temporal_variable = ['t']
output_variables = ['... | 2.015625 | 2 |
rasa/core/training/converters/__init__.py | chaneyjd/rasa | 37 | 50463 | <gh_stars>10-100
from rasa.core.training.converters.story_markdown_to_yaml_converter import (
StoryMarkdownToYamlConverter,
)
| 1.210938 | 1 |
libs/helpers.py | ggarri/mgit | 0 | 50464 | import multiprocessing
import traceback
from multiprocessing.pool import Pool
class Color():
_RED = "\033[1;31m"
_BLUE = "\033[1;34m"
_YELLOW = "\033[1;93m"
_CYAN = "\033[1;36xm"
_GREEN = "\033[0;32m"
_RESET = "\033[0;0m"
_BOLD = "\033[;1m"
_REVERSE = "\033[;7m"
@staticmethod
... | 2.703125 | 3 |
week_07/tests/test_my_math.py | vlasenckov/MIPT_py_3_term | 5 | 50465 | from my_mathematics.simple_math import MyMath
import math
import pytest
@pytest.mark.parametrize('x', [0, 1, 2, 3, 4, 5, 0.01, 3e-7, 232, 213123, 392, 921])
def test_check_sine(x):
assert math.sin(x) == MyMath.sin(x)
def test_check_pi():
assert round(math.pi, 2) == MyMath.pi
@pytest.mark.parametrize('x', ... | 2.796875 | 3 |
crane_controllers/external/casadi-3.4.5/test/python/misc.py | tingelst/crane | 2 | 50466 | #
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010-2014 <NAME>, <NAME>, <NAME>,
# <NAME>. All rights reserved.
# Copyright (C) 2011-2014 <NAME>
#
# CasADi is free software; you can redistribute it and/or
# ... | 2.296875 | 2 |
main.py | UKY-IRA/pytorch-soft-actor-critic | 0 | 50467 | import argparse
import copy
import datetime
import gym
import numpy as np
import itertools
import torch
import csv
import os
import json
from plane_env import Plane
from sac import SAC
from verify import verify_models, generate_agent_simulator
from torch.utils.tensorboard import SummaryWriter
from replay_memory import ... | 1.960938 | 2 |
varia/cmip5_pystac_val.py | crim-ca/stac-ingest | 0 | 50468 | from pystac.validation.stac_validator import STACValidator, STACValidationError
from pystac.validation.schema_uri_map import DefaultSchemaUriMap
from pystac import STAC_IO
import json
try:
import jsonschema
except ImportError:
jsonschema = None
class CMIP5SchemaSTACValidator(STACValidator):
"""Validate ... | 2.65625 | 3 |
tests/test_response_stream.py | silver-castle/mach9 | 5 | 50469 | <filename>tests/test_response_stream.py
from mach9 import Mach9
from mach9.response import stream
from mach9.http import BodyChannel
data = 'abc' * 100000
app = Mach9('test_response_stream')
def test_response_stream():
@app.post('/post/<id>', stream=True)
async def post(request, id):
assert isinstan... | 2.578125 | 3 |
webdjango/migrations/0002_auto_20181222_2028.py | myog-io/WebDjangular | 1 | 50470 | <filename>webdjango/migrations/0002_auto_20181222_2028.py<gh_stars>1-10
# Generated by Django 2.1.4 on 2018-12-22 22:28
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('webdjango', '0001_initial'),
]
oper... | 1.835938 | 2 |
Semester I/Design and Analysis of Algorithm/Practical 07 - Krushkals Algorithm/krushkals.py | STreK7/MSc.-CS | 0 | 50471 | import matplotlib.pyplot as plt
import networkx as nx
import random
class Graph:
def __init__(self,vertex):
self.v = vertex
self.graph = []
def add_edge(self, source, destination, weight):
self.graph.append([source, destination, weight])
def algo(self):
parent... | 3.046875 | 3 |
base/pylib/function.py | jpolitz/lambda-py-paper | 0 | 50472 | # function type
class function(object):
def __get__(self, obj, objtype):
# when used as attribute a function returns a bound method or the function itself
object = ___id("%object")
method = ___id("%method")
NoneType = ___id("%NoneType")
if obj is None and objtype is not NoneType:
# no obj... | 3.453125 | 3 |
taskscraper/scalprum/apps.py | YlmRdm/TaskScraper | 1 | 50473 | from django.apps import AppConfig
class ScalprumConfig(AppConfig):
name = 'scalprum'
| 1.0625 | 1 |
src/drkns/generation/GenerationTemplate.py | frantzmiccoli/drkns | 13 | 50474 | <reponame>frantzmiccoli/drkns<filename>src/drkns/generation/GenerationTemplate.py
class GenerationTemplate:
def __init__(
self,
source_path: str,
template: str,
group_template: str,
unit_template: str
):
self.source_path: str = source_path
... | 1.742188 | 2 |
fuxi/connector/cloudconnector/openstack.py | xxwjj/fuxi | 0 | 50475 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | 1.648438 | 2 |
ibsng/handler/user/get_user_info.py | ParspooyeshFanavar/pyibsng | 6 | 50476 | """Get user info API method."""
from ibsng.handler.handler import Handler
class getUserInfo(Handler):
"""Get user info class."""
def control(self):
"""Validate inputs after setup method.
:return: None
:rtype: None
"""
if hasattr(self, "user_id"):
self.is_v... | 2.984375 | 3 |
elasticsearch.py | Downlord/ansible-elasticsearch-callback | 0 | 50477 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
#The MIT License (MIT)
#
#Copyright (c) 2015 <NAME>
# 2021 <NAME> <EMAIL>
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restr... | 1.53125 | 2 |
OOP_Python/4_Jueves/calculos/__init__.py | aMurryFly/Old_Courses | 0 | 50478 | <reponame>aMurryFly/Old_Courses<filename>OOP_Python/4_Jueves/calculos/__init__.py
#Son directorios donde se almacenan módulos
'''
1) Crear una carpeta con un archivo __init__.py <- constructor
'''
| 1.328125 | 1 |
flaskr/blueprints/blog.py | MxBromelia/Flask-Tutorial | 0 | 50479 | from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort
from flaskr.blueprints.auth import login_required
from flaskr.schema import DB
from flaskr.schema.post import Post
from flaskr.schema.user import User
# Como não há url_prefix definido, a v... | 2.71875 | 3 |
box-get-enc-files.py | vaibhavb/box-ransomware-tools | 1 | 50480 | #!/opt/homebrew/bin/python3
import sys, argparse, pickle, os
sys.dont_write_bytecode = True
from http import client
from box import do_Box_OAuth
from boxsdk import Client
from boxsdk.exception import BoxAPIException
folder_ids = []
RANSOMWARE_KEY= '.deadbolt'
def get_files():
"""get all the files in the specified... | 2.453125 | 2 |
week_3/fizz.py | angelitabrg/lih_lab_python | 0 | 50481 | <gh_stars>0
"""
Exercícios 2 - FizzBuzz parcial, parte 1
Receba um número inteiro na entrada e imprima
Fizz
se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada.
"""
numero = int(input("Digite um número inteiro: "))
if(numero % 3 == 0):
print("Fizz")
else:
pri... | 4 | 4 |
test/e2e/containers/dsd_sender/sender.py | fk-currenxie/datadog-agent | 2 | 50482 | <filename>test/e2e/containers/dsd_sender/sender.py
import datadog
import time
client = datadog.dogstatsd.base.DogStatsd(socket_path="/var/run/dogstatsd/dsd.socket")
while True:
# Nominal case, dsd will inject its hostname
client.gauge('dsd.hostname.e2e', 1, tags=["case:nominal"])
client.service_check('dsd... | 1.921875 | 2 |
tictac/tictac/setup.py | SteveDMurphy/tic_tac_go | 0 | 50483 | <reponame>SteveDMurphy/tic_tac_go
from setuptools import setup
setup(
name="tictac",
version="0.1",
py_modules=["cli"],
install_requires=[
"Click",
],
entry_points="""
[console_scripts]
tictac=cli:tictac
""",
)
| 1.367188 | 1 |
venv/lib/python3.7/site-packages/foundation/template/loaders/app_directories.py | Ljuka/iwen | 1 | 50484 | <filename>venv/lib/python3.7/site-packages/foundation/template/loaders/app_directories.py<gh_stars>1-10
import os
from django.apps import apps
from django.core.exceptions import SuspiciousFileOperation
from django.template.loaders import app_directories
from django.template.base import Template, Origin
from django.tem... | 2.125 | 2 |
services/simcct/celery_runner.py | NeuralDev-io/arclytics_simcct | 2 | 50485 | <reponame>NeuralDev-io/arclytics_simcct
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# arclytics_sim
# celery_runner.py
#
# Attributions:
# [1]
# <NAME> and <NAME>. Mastering Flask Web Development - Second Edition.
# Birmingham: Packt Publishing, 2018.
# [2] ht... | 2.125 | 2 |
GUI.py | mmghannam/subdown | 0 | 50486 | from subscenery.scrapper import SubSceneScrapper
from tkinter import Tk, filedialog, Label, Listbox, ACTIVE
from tkinter import ttk
import os
win = Tk()
class Application(Tk):
def __init__(self):
ttk.Button(win, text='Choose a media file', command=self.choose_location_btn).grid(column=0, row=0)
s... | 2.890625 | 3 |
sphinx_paramlinks/__init__.py | sqlalchemyorg/sphinx-paramlinks | 7 | 50487 | <filename>sphinx_paramlinks/__init__.py
__version__ = "0.5.1"
from .sphinx_paramlinks import setup # noqa
| 0.964844 | 1 |
commands/archives/rename.py | martinwittmann/project-cmd | 1 | 50488 | <filename>commands/archives/rename.py
import click
import context
import util
from completions import get_local_archives
help_text = """(arn) Rename local archive.
You can use '%d' in NAME which gets replace with YYYY-MM-DD--HH:MM:SS which
is also the default name.
"""
@click.command(name='rename', help=help_text)... | 2.890625 | 3 |
Python/samples/house-energy/policies.py | nfgallimore/microsoft-bonsai-api | 1 | 50489 | """
Fixed policies to test our sim integration with. These are intended to take
Brain states and return Brain actions.
"""
import random
from typing import Dict
def random_policy(state: Dict = None):
"""
Ignore the state, move randomly.
"""
action = {"hvacON": random.randint(0, 1)}
return action
... | 3.359375 | 3 |
segmenter/bigram.py | trane293/nlp-project | 0 | 50490 | from __future__ import print_function
import sys, codecs, optparse, os
import heapq as heapq
import numpy as np
from heap import *
# pdb.set_trace()
optparser = optparse.OptionParser()
optparser.add_option("-c", "--unigramcounts", dest='counts1w', default=os.path.join('data', 'count_1w.txt'), help="unigram counts")
op... | 2.90625 | 3 |
core_engine/utils/gcp/automl_operations.py | arpitkjain7/synapse | 2 | 50491 | from google.cloud import automl
client = automl.AutoMlClient()
def get_operation_details(operation_id: str):
response = client._transport.operations_client.get_operation(operation_id)
if response.done:
if response.error.code != 0:
operation_status = "Failed"
error_message = re... | 2.4375 | 2 |
year-2020/day-14/part-1.py | mpryc/advent-of-code | 4 | 50492 | <reponame>mpryc/advent-of-code
#!/usr/bin/env python3
#
# eask:
# The initialization program (your puzzle input) can either update the bitmask
# or write a value to memory. Values and memory addresses are both 36-bit
# unsigned integers. For example, ignoring bitmasks for a moment, a line
# like mem[8] = 11 would write... | 4.03125 | 4 |
upath/tests/conftest.py | brl0/universal_pathlib | 17 | 50493 | <gh_stars>10-100
import os
import tempfile
from pathlib import Path
import subprocess
import shlex
import time
import sys
import pytest
from fsspec.implementations.local import LocalFileSystem
from fsspec.registry import register_implementation, _registry
def pytest_addoption(parser):
parser.addoption(
... | 2.109375 | 2 |
gtas/parsers/tests/__init__.py | minelytics/GTAS | 0 | 50494 | from gtas.parsers.tests.edifact import *
from gtas.parsers.tests.paxlst import *
| 1.023438 | 1 |
djangocms_bootstrap4/contrib/bootstrap4_content/constants.py | jpVm5jYYRE1VIKL/djangocms-bootstrap4 | 59 | 50495 | <reponame>jpVm5jYYRE1VIKL/djangocms-bootstrap4<filename>djangocms_bootstrap4/contrib/bootstrap4_content/constants.py
from django.utils.translation import gettext_lazy as _
CODE_TYPE_CHOICES = (
('code', _('Inline code')),
('pre', _('Code block')),
('var', _('Variables')),
('kbd', _('User input')),
... | 1.5 | 2 |
tests/ml_utils/test_plot_cv_indices.py | jameshtwose/jmspack | 0 | 50496 | # import matplotlib
# import matplotlib.pyplot as plt
# import pytest
# import seaborn as sns
#
# from jmspack.ml_utils import plot_cv_indices
#
#
# @pytest.fixture
# def df_test():
# """test dataset from seaborn"""
# return sns.load_dataset("iris")
#
#
# class TestPlotCvIndices:
# """Testing class to test ... | 2.6875 | 3 |
turing.py | ThePythonist/TuringMachinePiGenerator | 0 | 50497 | import pygame
import time
import sys
from pygame.locals import *
pygame.init()
screenWidth,screenHeight = 1600, 900
screen = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption("Turing Machine")
tape = [""]
if len(sys.argv) > 2:
tape = list(sys.argv[2])
for i in range(len(tape))... | 2.890625 | 3 |
spirit.py | electric-blue-green/micro-spirit | 1 | 50498 | <reponame>electric-blue-green/micro-spirit
from microbit import *
# Images
# /
r_roll = Image("00009:" "00090:" "00900:" "09000:" "90000")
# -
c_roll = Image("00000:" "00000:" "99999:" "00000:" "00000")
# \
l_roll = Image("90000:" "09000:" "00900:" "00090:" "00009")
# \-\
l_h_roll = Image("00000:" "90000:" "09990:" "00... | 2.765625 | 3 |
ch03tests/saskatchewan/test_overlap.py | pittachalk/rsd-engineeringcourse | 0 | 50499 | <reponame>pittachalk/rsd-engineeringcourse<gh_stars>0
from .overlap import overlap
def test_full_overlap():
assert overlap((1.,1.,4.,4.),(2.,2.,3.,3.)) == 1.0
def test_partial_overlap():
assert overlap((1,1,4,4),(2,2,3,4.5)) == 2.0
def test_no_overlap():
assert overlap((1,1,4,4),(4.5,4.5... | 2.078125 | 2 |