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 |
|---|---|---|---|---|---|---|
prototree/train.py | TristanGomez44/ProtoTree | 35 | 45300 | <gh_stars>10-100
from tqdm import tqdm
import argparse
from copy import deepcopy
import torch
import torch.nn.functional as F
import torch.optim
import torch.utils.data
from torch.utils.data import DataLoader
from prototree.prototree import ProtoTree
from util.log import Log
def train_epoch(tree: ProtoT... | 2.296875 | 2 |
scp.py | KvantPro/SCP | 1 | 45301 | <reponame>KvantPro/SCP
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SCP.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
f... | 2.171875 | 2 |
egs/librispeech/s5/fairseq_ltlm/ltlm/pyutils/kaldi_utils.py | somniumism/kaldi | 1 | 45302 | <reponame>somniumism/kaldi<filename>egs/librispeech/s5/fairseq_ltlm/ltlm/pyutils/kaldi_utils.py
# Copyright 2021 STC-Innovation LTD (Author: <NAME>)
import subprocess
import os
import time
import logging
logger = logging.getLogger(__name__)
def compute_wer(orig_fname, utt2hyp, tmp_dir='tmp', keep_tmp=False, hyp_fil... | 2.140625 | 2 |
polygon_cli/colors.py | SergeyMelnikov/polygon-cli | 50 | 45303 | <filename>polygon_cli/colors.py
import colorama
colorama.init(autoreset=True)
def colored(color):
return lambda message, *args: color + message.format(*args) + colorama.Style.RESET_ALL
error = colored(colorama.Fore.RED)
warning = colored(colorama.Fore.YELLOW)
success = colored(colorama.Fore.GREEN)
info = color... | 2.40625 | 2 |
vendor/istio.io/api/python/istio_api/networking/v1alpha3/service_dependency_pb2.py | octarinesec/istio | 2 | 45304 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: networking/v1alpha3/service_dependency.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from googl... | 1 | 1 |
text/src/autogluon/text/text_prediction/infer_types.py | zhiqiangdon/autogluon | 4,462 | 45305 | <gh_stars>1000+
import collections
import pandas as pd
import warnings
from typing import Union, Optional, List, Dict, Tuple
from autogluon.core.constants import MULTICLASS, BINARY, REGRESSION
from .constants import NULL, CATEGORICAL, NUMERICAL, TEXT
#TODO, This file may later be merged with the infer type logic in ta... | 3 | 3 |
python/partition_string.py | Hamng/python-sources | 0 | 45306 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 14:37:54 2021
@author: Ham
"""
import more_itertools as mit
import io
STDIN_SIO = io.StringIO("""
abcd
""".strip())
def partition_mit(s: str) -> list:
# Copied from: https://stackoverflow.com/questions/4904430/find-all-list-permutations-of-split... | 3.546875 | 4 |
src/workflow/tests/test_workflows.py | opnfv/laas | 2 | 45307 | <reponame>opnfv/laas
##############################################################################
# Copyright (c) 2018 <NAME>, <NAME>, and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distr... | 2.203125 | 2 |
tests/database/test_key_value.py | UMDLARS/CYLGame | 2 | 45308 | <gh_stars>1-10
import pytest
from CYLGame.Database import GameDB
from . import ex_db, temp_dir
def test_simple_str(ex_db: GameDB):
tok = ex_db.__players[0]
ex_db.save_value(tok, "test_key", "test_value")
assert ex_db.get_value(tok, "test_key") == "test_value"
def test_simple_2(ex_db: GameDB):
tok ... | 2.234375 | 2 |
notifications/sms.py | HexNumbers/OctoPrint | 0 | 45309 | <reponame>HexNumbers/OctoPrint
import smtplib, sys, urllib2
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from PIL import Image
import io
GMAIL_USERNAME = '*******<EMAIL>'
GMAIL_PASS = '*******'
RECEPIENT = '*******<EMAIL>'
SNAP_URL='http://1... | 2.78125 | 3 |
Day 20/day20.py | RyanRMurray/aoc2018 | 0 | 45310 | <gh_stars>0
from operator import itemgetter
dir = {
'N' : [0,-1],
'E' : [1, 0],
'W' : [-1,0],
'S' : [0, 1]
}
grid = {} #point -> 0 for open space, 1 for door
def get_input(f_path):
input = open(f_path, 'r').read()
return list(input)
def build_branch(string, ptr):
global grid
root = ptr
while len(string) >... | 2.90625 | 3 |
PiCN/Layers/PacketEncodingLayer/Encoder/SimpleStringEncoder.py | NikolaiRutz/PiCN | 0 | 45311 | """A extrem simple Packet Encoder for the BasicPacketEncodingLayer"""
from PiCN.Layers.PacketEncodingLayer.Encoder import BasicEncoder
from PiCN.Packets import Packet, Content, Interest, Name, Nack, NackReason, UnknownPacket
class SimpleStringEncoder(BasicEncoder):
"""An extreme simple Packet Encoder for the Basi... | 2.953125 | 3 |
dendropy/test/test_dataio_nexml_reader_chars.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 0 | 45312 | <reponame>EnjoyLifeFund/macHighSierra-py36-pkgs
# !/usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 <NAME> and <NAME>.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of ... | 1.960938 | 2 |
tests/test_a2c_pendulum.py | Anidwyd/pandroide-svpg | 1 | 45313 | <gh_stars>1-10
import datetime
import os
from pathlib import Path
import torch
from omegaconf import OmegaConf
from svpg.algos import A2C, SVPG
dtime = datetime.datetime.now().strftime("/%y-%m-%d/%H-%M-%S/")
params = {
"save_run": True,
"logger": {
"classname": "salina.logger.TFLogger",
"log_... | 2.125 | 2 |
Executor/Tasks/Run/cli_execute.py | 5genesis/ELCM | 1 | 45314 | from Task import Task
from Helper import Cli
class CliExecute(Task):
def __init__(self, logMethod, parent, params):
super().__init__("CLI Execute", parent, params, logMethod, None)
def Run(self):
parameters = self.params['Parameters']
cwd = self.params['CWD']
cli = Cli(parame... | 2.265625 | 2 |
airflow/scheduler.py | pengwei715/ticketAlert | 0 | 45315 | import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
schedule_interval = timedelta(days=2)
default_args = {
'owner': '<NAME>',
'depends_on_past': False,
'start_date': datetime.now() - schedule_interval,
'email': ['<EMA... | 2.640625 | 3 |
greenpithumb/pump.py | markselias/GreenPiThumb | 83 | 45316 | import logging
logger = logging.getLogger(__name__)
# Pump rate in mL/s (4.3 L/min)
_PUMP_RATE_ML_PER_SEC = 4300.0 / 60.0
# Default amount of water to add to the plant (in mL) when pump manager detects
# low soil moisture.
DEFAULT_PUMP_AMOUNT = 200
class Pump(object):
"""Wrapper for a Seaflo 12V water pump."""... | 3.28125 | 3 |
lib.py | miami-acm/unit-testing | 0 | 45317 | #!/usr/bin/env python3
def sleep_in(weekday, vacation):
"""
The parameter weekday is True if it is a weekday, and the parameter
vacation is True if we are on vacation. We sleep in if it is not a
weekday or we're on vacation. Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(T... | 4.28125 | 4 |
gvars.py | MattSkiff/cow_flow | 0 | 45318 | import config as c
FEAT_MOD_DIR = './models/feat_extractors/'
VIZ_DIR = './viz'
WEIGHT_DIR = './weights'
MODEL_DIR = './models'
LOG_DIR = './logs'
C_DIR = './cstates'
DMAP_DIR = './data/precompute/size_{}_sigma_{}/'.format(c.filter_size,c.sigma) | 1.195313 | 1 |
Botnets/Exploits/kace.py | 1ucif3r/DDOS-th31ucif3r | 1 | 45319 | #!/usr/bin/python
import threading
import sys
import time
import random
import socket
import subprocess
import re
import os
import struct
import array
import requests
from threading import Thread
from time import sleep
from requests.auth import HTTPDigestAuth
from decimal import *
ips = open(sys.argv[1], "r").readli... | 2.453125 | 2 |
elationmagic.py | lordjabez/light-maestro | 1 | 45320 | <filename>elationmagic.py
"""
@copyright: 2013 Single D Software - All Rights Reserved
@summary: Elation Magic 260 MIDI interface for Light Maestro.
"""
# Standard library imports
import logging
# Additional library imports
import rtmidi
import rtmidi.midiconstants
# Application imports
import console
# Named log... | 2.390625 | 2 |
6 kyu/Caesar Cipher Encryption Variation.py | mwk0408/codewars_solutions | 6 | 45321 | def caesar_encode(phrase, shift):
res=[]
for i,j in enumerate(phrase.split()):
res.append("".join(chr(ord("a")+(ord(k)-ord("a")+shift+i)%26) for k in j))
return " ".join(res) | 3.46875 | 3 |
python/setup.py | dune-mirrors/dune-python | 0 | 45322 | from setuptools import setup, find_packages
setup(name='dune.common',
namespace_packages=['dune'],
version='2.4',
description='Python package accompanying the DUNE project',
url='http://www.dune-project.org',
author='<NAME>',
author_email='<EMAIL>',
license='BSD',
packag... | 1.375 | 1 |
freeTextAnalyse.py | tommyzhu1995/machine_reading | 0 | 45323 | <reponame>tommyzhu1995/machine_reading<gh_stars>0
import pandas as pd
import re
import jieba.analyse as analyse
import jieba
from collections import Counter
# Title行均不计入索引中
excel_path = 'DCoinSurveyETL.xlsx'
# d = pd.read_excel(excel_path, sheet_name=0, usecols=[8,9,11,12,13])
d = pd.read_excel(excel_path, sh... | 2.703125 | 3 |
tests/test_utils.py | Supplyframe/inlinestyler | 0 | 45324 | from unittest import TestCase
from inlinestyler.utils import inline_css
class TestUtils(TestCase):
def setUp(self):
self.the_document = '<html><head><style>.turn_red{ color: red; }</style></head><body><p class="turn_red">This text should be red.</p></body></html>'
def test_inline_css(self):
... | 2.984375 | 3 |
tests/trainer/snorkel/test_utils.py | michael-aloys/knodle | 71 | 45325 | <filename>tests/trainer/snorkel/test_utils.py
import numpy as np
from scipy import sparse as ss
import torch
from torch.utils.data import TensorDataset
from knodle.trainer.snorkel.utils import (
z_t_matrix_to_snorkel_matrix,
prepare_empty_rule_matches,
add_labels_for_empty_examples
)
def test_z_t_matrix_... | 2.1875 | 2 |
Chapter03/main.py | waltechel/KaggleStudy20220103 | 0 | 45326 | <reponame>waltechel/KaggleStudy20220103
import cv2
import numpy as np
import time, argparse
parser = argparse.ArgumentParser()
parser.add_argument('--video', help='Input video path')
args = parser.parse_args()
# 비디오 캡처한다.
cap = cv2.VideoCapture(args.video if args.video else 0)
# 3초 쉬도록 한다.
time.sleep(3)
# 비디오 앞부분에는... | 2.640625 | 3 |
api/tests/integration/test_record.py | azzamsa/RESTKnot | 18 | 45327 | import datetime
import app.helpers.helpers
from app.controllers.api import record as record_api
from app.helpers import helpers
class TestRecord:
def get_record(self, records, type_):
for record in records:
if record["type"] == type_:
return record
def test_list_no_Record... | 2.59375 | 3 |
trafo.py | Bierbunker/Lab-Tool | 1 | 45328 | import sympy as simp
from sympy import sin, pi
import pandas as pd
from labtool_ex2 import Project
from uncertainties import ufloat
if __name__ == "__main__":
gm = {
"P1": r"P_1",
"PR": r"P_R",
"theoPR": r"P_R",
"U1": r"U_1",
"U2": r"U_2",
"I1": r"I_1",
"I2":... | 2.0625 | 2 |
rdkit/Chem/UnitTestGraphDescriptors.2.py | darkreactions/rdkit | 0 | 45329 | <filename>rdkit/Chem/UnitTestGraphDescriptors.2.py
# $Id$
#
# Copyright (C) 2003-2006 Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit so... | 2.125 | 2 |
nudging/model/propensity_score.py | UtrechtUniversity/nudging | 1 | 45330 | """ Reference: https://matheusfacure.github.io/python-causality-handbook/11-Propensity-Score.html#
"""
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import NearestNeighbors
import seaborn as sns
from matplotlib import pyplot as plt
from causalinference... | 3.046875 | 3 |
test.py | geographika/hashtable-swig | 0 | 45331 | <reponame>geographika/hashtable-swig
import mapscript
ht = mapscript.hashTableObj()
ht["key1"] = "value1" | 1.96875 | 2 |
day24/register.py | heijp06/AoC-2021 | 0 | 45332 | <reponame>heijp06/AoC-2021<filename>day24/register.py
from __future__ import annotations
from expressions import InputExpression, BinaryExpression, ValueExpression
import operator
import math
class Register:
BinaryOperations = {
"mul": (operator.mul, '*'),
"add": (operator.add, '+'),
"mod"... | 2.8125 | 3 |
code/tools/prepare_instance.py | santomon/taskonomy | 789 | 45333 | import subprocess
import os
def download_task_model(task):
m_path = os.path.join('/home/ubuntu/s3', "model_log_final", task,
"logs/model.permanent-ckpt")
dirs, fname = os.path.split(m_path)
dst_dir = dirs.replace('/home/ubuntu/s3', "s3://taskonomy-unpacked-oregon")
... | 2.25 | 2 |
osbot_utils/utils/Misc.py | owasp-sbot/OSBot-Utils | 0 | 45334 | import base64
import hashlib
import inspect
import logging
import os
import random
import string
import sys
import textwrap
import re
import uuid
import warnings
from datetime import datetime
from secrets import token_bytes
from time import sleep
from urllib.parse import urlencode, quote_plus, unquote_plus
from d... | 2.3125 | 2 |
teamcat_service/docker_build/target/one_step_build/teamcat/doraemon/project/viewmodels/project_left_nav_bar.py | zhangyin2088/Teamcat | 6 | 45335 | #coding=utf-8
'''
Created on 2015-9-24
@author: Devuser
'''
from doraemon.project.models import Project
class ProjectLeftNavBar(object):
'''
classdocs
'''
def __init__(self,request,projectid):
self.request=request
# self.dashboard_href='/project/'+str(projectid)+'/dashboard'
s... | 2.203125 | 2 |
plugins/broadcast.py | DeveloperNoob/BAD_LOKI_FACE | 0 | 45336 | #By @Joel_Noob
from pyrogram import Client, filters
from config import Config
@Client.on_message(
filters.private
& filters.command("broadcast")
& filters.user(Config.ADMINS)
& filters.reply
)
async def broadcast_(c, m):
await c.start_broadcast(
broadcast_message=m.reply_to_message, admin... | 1.75 | 2 |
tests/unit_tests/test_config.py | sspbft/sspbft-template | 6 | 45337 | <reponame>sspbft/sspbft-template
import unittest
import os
from conf import config
class TestConfig(unittest.TestCase):
def test_config_can_parse_nodes_txt(self):
s = "0,localhost,127.0.0.1,5000\n1,localhost,127.0.0.1,5001\n"
path = "conf/tmp.txt"
with open(path, "w") as f:
f.wr... | 2.84375 | 3 |
escalation/utility/wizard_utils.py | twosixlabs/escalation_demo | 0 | 45338 | <gh_stars>0
import copy
import json
import os
import re
from flask import current_app
from utility.constants import *
UI_SCHEMA_PAIRS = {
VISUALIZATION: VISUALIZATION_OPTIONS,
SELECTOR: SELECTABLE_DATA_DICT,
PLOTLY: PLOT_SPECIFIC_INFO,
}
def save_main_config_dict(config_dict):
main_config_path = os... | 2.453125 | 2 |
src/jen/functions.py | VishalShenoy2002/JEN | 1 | 45339 | <reponame>VishalShenoy2002/JEN
import pyautogui
import calendar
import datetime
import random
import subprocess
import time
import os
import webbrowser
import wikipedia
def day_today():
'''
The day_today() function as the name suggests tells you what day is it today.
It sees the system day and tells y... | 4.28125 | 4 |
affine/affine_funcs.py | OSU-slatelab/geometric-embedding-properties | 3 | 45340 | <gh_stars>1-10
from preprocessing import process_embedding
from preprocessing import check_valid_file
from preprocessing import check_valid_dir
import numpy as np
from progressbar import progressbar
from tqdm import tqdm
import pyemblib
import sympy
import scipy
import time
import sys
import os
#==... | 2.34375 | 2 |
accounts/models.py | Murtuza47/Star-Social | 0 | 45341 | <gh_stars>0
from django.db import models
from django.contrib import auth
# Create your models here.
class User(auth.models.User, auth.models.PermissionsMixin):
"""This class is inherited from base User class and the permissions mixin"""
def __str__(self):
return f"@{self.username}" #This username come... | 2.484375 | 2 |
optimizer/geoetryModel/inner_rect.py | terasakisatoshi/pythonCodes | 0 | 45342 | <reponame>terasakisatoshi/pythonCodes<filename>optimizer/geoetryModel/inner_rect.py
from matplotlib import pyplot as plt
import z3
from z3 import Real, Optimize, If
from fractions import Fraction
EPS = 1e-2
def plotline(ax, b, e, *args):
ax.plot([b[0], e[0]], [b[1], e[1]], *args)
def add_cond_on_segment(optim... | 2.421875 | 2 |
src/genie/libs/parser/dell/os10/tests/ShowIPInterfaceBrief/equal/golden_output_expected.py | DataKnox/genieparser | 0 | 45343 | expected_output = {
'ints': {
'Ethernet 1/1/1': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/2': {
'ip_address': 'unassigned',
'ok': True,
... | 1.96875 | 2 |
recipes/migrations/0004_auto_20210308_0628.py | PavelYasukevich/foodgram-project | 0 | 45344 | <reponame>PavelYasukevich/foodgram-project<gh_stars>0
# Generated by Django 3.1.7 on 2021-03-08 06:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0003_auto_20210304_1233'),
]
operations = [
migrations.AlterField(
... | 1.5625 | 2 |
tests/strategies/__init__.py | lycantropos/bentley_ottmann | 13 | 45345 | from .base import (points_strategies,
segments_strategies)
| 1.007813 | 1 |
core/models/article.py | agolibroda/PyTorWiki | 0 | 45346 | <filename>core/models/article.py
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
#
# Copyright 2015 <NAME>
#
# article.py
from __future__ import print_function
import logging
import json
import string # string.Template
import zlib
# import markdown
import tornado.options
# import pymysql
... | 2.046875 | 2 |
board_app/migrations/0004_alter_boardmodel_snsimage.py | OkuboAtsushi/board-project | 0 | 45347 | <filename>board_app/migrations/0004_alter_boardmodel_snsimage.py
# Generated by Django 3.2.3 on 2021-08-01 12:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('board_app', '0003_alter_boardmodel_snsimage'),
]
operations = [
migrations.... | 1.429688 | 1 |
model/lstm_layers.py | zhazhangqi/sentence_classification | 59 | 45348 |
import numpy as np
import theano
import theano.tensor as tensor
from utils import _p, numpy_floatX
from utils import ortho_weight, uniform_weight, zero_bias
""" Encoder using LSTM Recurrent Neural Network. """
def param_init_encoder(options, params, prefix='lstm_encoder'):
n_x = options['n_x']
n_h = opt... | 2.734375 | 3 |
plugins/auth/crypto/algo_pbkdf2.py | UltrosBot/Ultros | 16 | 45349 | # coding=utf-8
from plugins.auth.crypto.algo_base import BaseAlgorithm
from pbkdf2 import crypt
__author__ = '<NAME>'
class PBKDF2Algo(BaseAlgorithm):
def check(self, hash, value, salt=None):
return hash == self.hash(value, hash)
def hash(self, value, salt=None):
return crypt(
... | 2.484375 | 2 |
src/recipes/op.py | astromancer/recipes | 0 | 45350 | <gh_stars>0
"""
Some drop-in replacements for the cool builtin operator classes, but with added
support for default values
"""
# pylint: disable=redefined-builtin
# pylint: disable=invalid-name
# std libs
import builtins
import warnings
import functools as ftl
from operator import *
# local libs
import docsplice a... | 2.328125 | 2 |
qa/check_header.py | eletesta/cirkit | 0 | 45351 | <filename>qa/check_header.py
#!/usr/bin/env python3
import fnmatch
import os
from termcolor import colored
header_cirkit = """/* {tool}
* Copyright (C) 2009-2015 University of Bremen
* Copyright (C) 2015-2017 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this softwar... | 2.203125 | 2 |
Exercicios/Ex095.py | RenanRibeiroDaSilva/Meu-Aprendizado-Python | 2 | 45352 | """ Ex - 095 - Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema
de visualização de detalhes do aproveitamento de cada jogador."""
# Como eu fiz.
# T.L.D.:
cad_joga = dict()
gol_part = list()
dad_jgdr = list()
# Area de desenvolvimeno:
wh... | 4.1875 | 4 |
analyse/filter.py | hha227/AUT2003_proj | 0 | 45353 | import numpy as np
import statistics as stat
treshold = 3
def removeFalseData(input_data):
while(1):
try:
input_data.remove(False)
except ValueError:
break
return(input_data)
def removeNegatives(input_data):
processed_data = []
for val in input_d... | 3.4375 | 3 |
model/fcn.py | cj-mclaughlin/semseg | 1 | 45354 | import encoding
from torch import nn
import torch
class FCN(nn.Module):
"""
wrapper around encnet module, putting it into terms similar to psp/psanet for convenience
"""
def __init__(self, pretrained=True):
super(FCN, self).__init__()
self.model = encoding.models.get_model('FCN_ResNet50... | 2.84375 | 3 |
templates/tlogserver/actions.py | 5l1v3r1/0-orchestrator | 3 | 45355 | <gh_stars>1-10
from js9 import j
def get_container(service, password):
from zeroos.orchestrator.sal.Container import Container
return Container.from_ays(service.parent, password, logger=service.logger)
def is_port_listening(container, port, timeout=30, listen=True):
import time
start = time.time()
... | 1.828125 | 2 |
Week 6 Text files, csv and spreadsheets/Task12.py | retverd/python_hse | 0 | 45356 | # Для решения этой задачи необходимо установить библиотеку openpyxl и создать скрипт со следующем содержанием:
# Запустите скрипт и в качестве ответа введите то, что он выведет.
import openpyxl
wb = openpyxl.load_workbook('inputs/input12.xlsx')
sh = wb.active
nmin = sh.cell(row=7, column=2).value
for rownum in range(... | 3.828125 | 4 |
smartlearner/status.py | MarcCote/smartlearner | 0 | 45357 | from os.path import join as pjoin
from .utils import save_dict_to_json_file, load_dict_from_json_file
class Status(object):
def __init__(self, trainer=None, starting_epoch=0, starting_update=0):
self.current_epoch = starting_epoch
self.current_update = starting_update
self.current_update_... | 2.53125 | 3 |
autotest/autotest/webtest/webauto_testcase3.py | zhouxuerong/autotest | 0 | 45358 | <filename>autotest/autotest/webtest/webauto_testcase3.py
import os
import time
import unittest
from selenium import webdriver
import pymysql,requests,time,sys,re
import urllib,zlib
import json
sys.path.append("..")
from autotest.common import mySqlOperation
import HTMLTestRunner
PATH = lambda p:os.path.abspath(os.path... | 2.390625 | 2 |
10601-hws/HW 6/hw6/python/hwTestLeNet.py | dfreilich/machine-learning-workspace | 0 | 45359 | <reponame>dfreilich/machine-learning-workspace
import numpy as np
import cnn_lenet
import pickle
import copy
import random
import matplotlib as mp
import matplotlib.pyplot as plt
import math
def get_lenet():
"""Define LeNet
Explanation of parameters:
type: layer type, supports convolution, pooling, relu
chann... | 3.171875 | 3 |
src/pybuiltins/module/__init__.py | Xiddoc/ComPy | 0 | 45360 | """
Python module.
""" | 1.195313 | 1 |
Chatbot_KG/chatbot_scrapy/wikidataSpider/wikientities/wikientities/loadjson.py | guci314/Chatbot_CN | 1 | 45361 | <gh_stars>1-10
import json
with open('entities2.json', 'r') as f:
for line in f:
entityjson = json.loads(line)
print(entityjson)
| 2.453125 | 2 |
conf/urls.py | crisariasgg/RepinSolution | 0 | 45362 | """URL Configuration"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.views.generic import TemplateView
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('apps.users.urls', 'use... | 1.835938 | 2 |
tests.py | Shetty4L/mnist-pytorch | 0 | 45363 | if __name__ == '__main__':
assert True == True
| 1.289063 | 1 |
inventory.py | d4rkp0rt/NouvelEspace | 2 | 45364 | <reponame>d4rkp0rt/NouvelEspace
import savegame
inventory = []
gas_vent_on = True
def add_item(item):
inventory.append(item)
def remove_item(item):
inventory.remove(item)
def show_inventory():
if inventory:
print("You are currently carrying:")
print(inventory)
else:
print("... | 3.390625 | 3 |
pages/migrations/0001_initial.py | mixnix/subject_rate | 0 | 45365 | <reponame>mixnix/subject_rate
# Generated by Django 2.1.3 on 2018-11-22 04:31
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CourseName'... | 1.851563 | 2 |
fake_lstm.py | amangit007/Fake-News-Detector | 4 | 45366 | <filename>fake_lstm.py
import pandas as pd
import numpy as np
import sys
# Importing the data
df = pd.read_csv('fake_or_real_news.csv')
try:
news_clean_encoded = np.loadtxt('news_encoding.gz')
title_clean_encoded = np.loadtxt('title_encoding.gz')
except:
print ("Please first encode the data!!")
sys.exi... | 3.125 | 3 |
src/spaceone/inventory/error/custom.py | jihyungSong/plugin-azure-power-state | 1 | 45367 | <filename>src/spaceone/inventory/error/custom.py
from spaceone.core.error import ERROR_BASE
class ERROR_REPOSITORY_BACKEND(ERROR_BASE):
status_code = 'INTERNAL'
message = 'Repository backend has problem. ({host})'
class ERROR_DRIVER(ERROR_BASE):
status_code = 'INTERNAL'
message = '{message}'
class... | 2.203125 | 2 |
db_server.py | YashithaNadiranga/MysqlFlask | 0 | 45368 | <reponame>YashithaNadiranga/MysqlFlask<filename>db_server.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:pass@localhost/student_details'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_ke... | 2.75 | 3 |
setup.py | Jhengsh/blob-cli | 0 | 45369 | <reponame>Jhengsh/blob-cli<gh_stars>0
from setuptools import setup, find_packages
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Natural Language :: English',
'Programming Language :: Python',
'Pro... | 1.398438 | 1 |
bucket_operations.py | scaleoutsean/storagegrid-dmc | 0 | 45370 | <gh_stars>0
# StorageGRID Data Management Console (DMC)
# Copyright (c) 2018, NetApp, Inc.
# Licensed under the terms of the Modified BSD License (also known as New or Revised or 3-Clause BSD)
import re
from app import logger
from app import get_s3_client
from utils import *
from flask import jsonify
import botocore... | 2.125 | 2 |
p041.py | piohhmy/euler | 0 | 45371 | '''We shall say that an n-digit number is pandigital if it makes use of all the
digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is
also prime. What is the largest n-digit pandigital prime that exists?'''
import itertools
import functools
def pandigital_generator(n):
perms = itertools.pe... | 4.0625 | 4 |
relay_daemon/logger.py | vt-gs/relay_daemon | 0 | 45372 | <filename>relay_daemon/logger.py
#!/usr/bin/env python2
# Logger utilities
import math, sys, os, time, struct, traceback, binascii, logging
import datetime as dt
class MyFormatter(logging.Formatter):
#Overriding formatter for datetime
converter=dt.datetime.utcfromtimestamp
def formatTime(self, record, da... | 2.375 | 2 |
prism/__init__.py | mwaldronii/prism-python | 1 | 45373 | <gh_stars>1-10
from prism.prism import Prism, load_schema
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
__all__ = ["Prism", "load_schema"]
| 1.242188 | 1 |
keycloak_config/actions/create_client.py | mkurcius/keycloak-config-tool | 0 | 45374 | """
Client creation action.
~~~~~~~~~~~~~~~~~~~~~~~
"""
from .action import Action
from .action import ActionExecutionException
from .action import InvalidActionConfigurationException
from .utils import get_user_roles
from .utils import InvalidUserResponse
from .utils import process_user_roles
import requests
import ... | 2.234375 | 2 |
yuuhpizzakebab/pizza/views.py | lex/yuuh-pizza-kebab | 0 | 45375 | from yuuhpizzakebab import app, admin_required, login_required
from .models import Pizza, Topping
from flask import render_template, session, redirect, url_for, request, flash
@app.route('/pizzas')
def list_pizzas():
"""Shows a list of pizzas."""
return render_template('pizza/pizzas.html',
... | 2.765625 | 3 |
assignment-4.py | Daredevil3722/CS-Assignments | 0 | 45376 | <reponame>Daredevil3722/CS-Assignments
import mysql.connector as connector
from prettytable import PrettyTable
from prettytable import from_db_cursor
import time
db = connector.connect(host = "localhost", user = "root", passwd = "<PASSWORD>!", database = 'assignments')
if(db):
print("SQL Connectivity Successful")
... | 3.03125 | 3 |
unshortener/trash.py | hayj/Unshortener | 1 | 45377 | class UnshortenerOld():
"""
Todo option selenium ?
"""
def __init__(self,
logger=None,
verbose=True,
maxItemCount=100000000,
maxDataSizeMo=10000,
dataDir=None,
seleniumBrowserCount=20,
... | 2.59375 | 3 |
scripts/02_merge_shp_to_gpkg.py | MIERUNE/create_gpkg_for_city_boundaries | 3 | 45378 | <reponame>MIERUNE/create_gpkg_for_city_boundaries
import glob
from pathlib import Path
import geopandas as gpd
import pandas as pd
zip_path_list = [Path(l) for l in glob.glob("../download/*.zip")]
town_gdf = pd.concat(
[gpd.read_file("zip://" + str(zipfile)) for zipfile in zip_path_list]
).pipe(gpd.GeoDataFrame)... | 2.53125 | 3 |
tickle/agenda.py | soren-n/tickle | 0 | 45379 | # External module dependencies
from dataclasses import dataclass, field
from typing import Any, ParamSpec, Callable, Tuple, List, Dict, Set
from pathlib import Path
import hashlib
import json
import yaml
# Internal module dependencies
from . import dataspec
############################################################... | 2.171875 | 2 |
RemoveElement.py | sujitmandal/leetCode | 0 | 45380 | <gh_stars>0
class Solution:
def removeElement(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(count)
return(count)
obj = Solution()
obj.removeElement([3,2,2,3], 3)
... | 3.234375 | 3 |
src/crawl_video.py | happylin0x29a/pandatv_host_video | 0 | 45381 | #!/usr/bin/env python
# coding:utf-8
"""
@version: 3.4.4
@author: linfeng
@file: crawl_video.py
@time: 2019/3/16 16:04
"""
import os
import re
import requests
from multiprocessing import Process
from urllib.parse import urlparse
from base_crawl import BaseCrawl
class CrawlVideo(Process, BaseCrawl):
def __init... | 2.640625 | 3 |
blaze/datashape/__init__.py | davidfischer/blaze-core | 1 | 45382 | import parser
from coretypes import *
def dopen(fname):
contents = open(fname).read()
return parser.parse_extern(contents)
def dshape(o):
if isinstance(o, str):
return parser.parse(o)
elif isinstance(o, DataShape):
return o
else:
raise TypeError('Cannot create dshape from o... | 2.8125 | 3 |
CMUTweetTagger.py | renhaocui/activityExtractor | 1 | 45383 | import subprocess, shlex, json, re
from wordsegment import load, segment
from difflib import SequenceMatcher
import sys
reload(sys)
sys.setdefaultencoding('utf8')
load()
RUN_TAGGER_CMD = "java -XX:ParallelGCThreads=2 -Xmx1000m -jar utilities/ark-tweet-nlp-0.3.2.jar"
def removeLinks(input):
urls = re.findall("(?P... | 2.765625 | 3 |
samples/sample.py | yuta-ubiquitous/pyMagician | 0 | 45384 | # -*- coding: utf-8 -*-
import signal
from pyMagician import pyMagician
signal.signal(signal.SIGINT, signal.SIG_DFL)
magician = pyMagician(port='/dev/cu.usbmodem0121')
if magician.connect():
print('- success connect')
print('- read_version')
print(magician.read_version())
for n in range(3):
... | 2.328125 | 2 |
packages/snet_cli/snet/snet_cli/version.py | dhruvshettty/snet-cli | 0 | 45385 | __version__ = "v0.2.3"
| 1.015625 | 1 |
lhzutil.py | LiHongzhuo/wxBot | 0 | 45386 | # -*- coding: utf-8 -*-
# 获取字符串中匹配子串的最后一个位置
def find_last(string, str):
last_position = -1
while True:
position = string.find(str, last_position+1)
if position == -1:
return last_position
last_position = position
# 将文件名改写成小文件名
def thumbFilePath(filepath):
... | 3.921875 | 4 |
bestiary/management/commands/parse_game_data.py | Itori/swarfarm | 66 | 45387 | <reponame>Itori/swarfarm
from django.core.management.base import BaseCommand
from bestiary import parse
class Command(BaseCommand):
help = 'Parse all bestiary data from game files'
def handle(self, *args, **kwargs):
self.stdout.write('Processing static files...')
parse.static.decrypt_images(... | 2.140625 | 2 |
Booking a Room/room.py | rajitbanerjee/kattis | 2 | 45388 | <filename>Booking a Room/room.py
"""https://open.kattis.com/problems/bookingaroom"""
from random import randint
r, n = map(int, input().split())
if r == n:
print("too late")
exit()
booked = []
for _ in range(n):
booked.append(int(input()))
n = randint(1, r)
while n in booked:
# keep on shuffling unt... | 3.5 | 4 |
visualization_apps/MgO_pareto/PCA/real_data_pca.py | eragasa/pypospack | 4 | 45389 | <filename>visualization_apps/MgO_pareto/PCA/real_data_pca.py
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering, AffinityPropagati... | 2.328125 | 2 |
Backtest/main/Visual/StratVisual.py | simonydbutt/b2a | 2 | 45390 | from bokeh.plotting import figure, output_file, show
from Backtest.main.Utils.AssetBrackets import AssetBrackets
class StratVisual:
def __init__(self, resultsDict):
self.resultsDict = resultsDict
self.A = AssetBrackets()
def periodReturns(self):
brackets = self.A.getBrackets()
... | 2.703125 | 3 |
src/mem/HybridController/eDRAM_Cache_Side/eDRAM.py | MattDAngeli/Hybrid-eDRAM-PCM-Full-System-Simulator | 0 | 45391 | from m5.params import *
from m5.proxy import *
from MemObject import *
from eDRAMCacheTags import *
class eDRAMCache(MemObject):
type = 'eDRAMCache'
cxx_header = "mem/HybridController/eDRAM_Cache_Side/eDRAM_cache.hh"
block_size = Param.Int(Parent.block_size, "same as parent")
size = Param.MemoryS... | 1.960938 | 2 |
flask_response_builder/response_builder.py | cs91chris/flask_response_builder | 4 | 45392 | from functools import wraps
import flask
from flask import current_app as cap
from .builders.builder import Builder
from .config import DEFAULT_BUILDERS, set_default_config
class ResponseBuilder:
def __init__(self, app=None, builders=None):
"""
:param app:
:param builders:
"""
... | 2.65625 | 3 |
resotocore/resotocore/db/jobdb.py | someengineering/resoto | 126 | 45393 | <filename>resotocore/resotocore/db/jobdb.py
from resotocore.db.async_arangodb import AsyncArangoDB
from resotocore.db.entitydb import EntityDb, EventEntityDb, ArangoEntityDb
from resotocore.task.task_description import Job
JobDb = EntityDb[Job]
EventJobDb = EventEntityDb[Job]
def job_db(db: AsyncArangoDB, collection... | 1.78125 | 2 |
grouper/setup.py | lfaraone/grouper | 0 | 45394 | <gh_stars>0
from argparse import ArgumentParser, Namespace # noqa
import logging
from grouper import __version__
def parse_args(parser, default_config_path):
# type(ArgumentParser, str) -> Namespace
parser.add_argument(
"-c", "--config", default=default_config_path, help="Path to config file.")... | 2.578125 | 3 |
interview/leet/859_Buddy_Strings.py | eroicaleo/LearningPython | 1 | 45395 | <filename>interview/leet/859_Buddy_Strings.py<gh_stars>1-10
#!/usr/bin/env python3
class Solution:
def buddStrings(self, A, B):
la, lb = len(A), len(B)
if la != lb:
return False
diff = [i for i in range(la) if A[i] != B[i]]
if len(diff) > 2 or len(diff) == 1:
... | 3.546875 | 4 |
classes/magic_method/method1.py | zhangyage/Python-oldboy | 1 | 45396 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
__new__ __init__
'''
class Programer(object):
def __new__(self, *args, **kwargs):
print 'call __new__ method!'
print args
return object.__new__(self, *args, **kwargs)
def __init__(self,name,age):
prin... | 3.859375 | 4 |
EDA/index.py | jbofill10/Movies-EDA | 1 | 45397 | <reponame>jbofill10/Movies-EDA
from EDA import MetaData
def run(meta_df):
MetaData.metadata_eda(meta_df)
| 1.359375 | 1 |
Projects/events/views.py | jjfleet/Capstone | 2 | 45398 | from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import EventListing
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestM... | 2.046875 | 2 |
tests/h/tasks/indexer_test.py | 13625025773/h | 0 | 45399 | import datetime
from unittest import mock
import pytest
from h_matchers import Any
from h.tasks import indexer
class FakeSettingsService:
def __init__(self):
self._data = {}
def get(self, key):
return self._data.get(key)
def put(self, key, value):
self._data[key] = value
clas... | 2.21875 | 2 |