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 |
|---|---|---|---|---|---|---|
tests/it/test_docker_image_tag.py | gfi-centre-ouest/docker-devbox-ddb | 4 | 11700 | <filename>tests/it/test_docker_image_tag.py
import os
import zipfile
import yaml
from dotty_dict import Dotty
from pytest_mock import MockerFixture
from ddb.__main__ import main
from ddb.config import Config
from ddb.feature.version import is_git_repository
class TestDockerImageTag:
def test_image_tag_from_git_... | 2.15625 | 2 |
bin/zeisel.py | bendemeo/ample | 0 | 11701 | import numpy as np
import os
from scanorama import *
from scipy.sparse import vstack
from process import load_names
from experiments import *
from utils import *
NAMESPACE = 'zeisel'
METHOD = 'svd'
DIMRED = 100
data_names = [
'data/mouse_brain/zeisel/amygdala',
'data/mouse_brain/zeisel/cerebellum',
'data... | 2.078125 | 2 |
cogitare/monitor/workers/system_usage.py | cogitare-ai/cogitare | 90 | 11702 | <filename>cogitare/monitor/workers/system_usage.py
from threading import Thread
import psutil
import time
class SystemUsage(Thread):
def __init__(self, callback, *args, **kwargs):
super(SystemUsage, self).__init__(daemon=True)
self.interval = 1
self.enabled = False
self.callback =... | 2.703125 | 3 |
test/worker/net.py | ameserole/Naumachia | 0 | 11703 | import fcntl
import os
import socket
import struct
import warnings
import subprocess
import logging
import base64
logger = logging.getLogger(__name__)
# Dummy socket used for fcntl functions
_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
class AddrMeta(type):
@property
def maxvalue(cls):
... | 2.46875 | 2 |
kunrei.py | kosugi/alfred.romanizer | 0 | 11704 | # -*- coding: utf-8 -*-
basic_table = dict(map(lambda s: s.split(u'\t'), u'''
あ a
い i
う u
え e
お o
か ka
き ki
く ku
け ke
こ ko
さ sa
し si
す su
せ se
そ so
た ta
ち ti
つ tu
て te
と to
な na
に ni
ぬ nu
ね ne
の no
は ha
ひ hi
ふ hu
へ he
ほ ho
ま ma
み mi
む mu
め me
も mo
や ya
ゆ yu
よ yo
ら ra
り ri
る ru
れ re
ろ ro
わ wa
を wo
ぁ a
ぃ i
ぅ u
ぇ e
ぉ o
が... | 2.46875 | 2 |
tests/test_utils.py | loganthomas/turkey-bowl | 0 | 11705 | <reponame>loganthomas/turkey-bowl<filename>tests/test_utils.py
"""
Unit tests for utils.py
"""
# Standard libraries
import json
from pathlib import Path
# Third-party libraries
import pytest
# Local libraries
from turkey_bowl import utils
@pytest.mark.freeze_time
@pytest.mark.parametrize(
"frozen_date, expected... | 2.421875 | 2 |
regtests/webclgl/call_external_method.py | bpmbank/PythonJS | 319 | 11706 | <filename>regtests/webclgl/call_external_method.py
"""external method"""
class myclass:
def __init__(self, i):
self.index = i
def get_index(self):
return self.index
def run(self, n):
self.intarray = new(Int16Array(n))
self.intarray[ self.index ] = 99
@returns( array=n )
@gpu.main
def gpufunc():
... | 2.578125 | 3 |
pages/views.py | Total-Conversion/eco4coin | 0 | 11707 | <gh_stars>0
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import TemplateView, ListView
import csv
from django.http import HttpResponse
from backend.models import CustomUser
from django.contrib.auth.mixins import LoginRequiredMixin
class HomePageView(TemplateView):... | 2.21875 | 2 |
18.part2.py | elp2/advent_of_code_2018 | 1 | 11708 | from collections import defaultdict
def return_default():
return 0
REAL=open("18.txt").readlines()
SAMPLE=open("18.sample").readlines()
OPEN="."
TREE="|"
LUMBERYARD="#"
import copy
def safe_grid_get(grid, x, y, missing=None):
if x < 0 or y < 0:
return missing
if y >= len(grid):
return m... | 3.1875 | 3 |
PythonExercicios/ex031.py | Caio-Moretti/115.Exercicios-Python | 0 | 11709 | <gh_stars>0
dis = float(input('Digite a distância da sua viagem em Km: '))
if dis <= 200:
print('O valor da sua passagem será {:.2f} reais'.format(dis * 0.5))
else:
print('O valor da sua passagem será {:.2f} reais'.format(dis * 0.45))
| 3.5625 | 4 |
admin/collection_providers/forms.py | rdm-dev12/RDM-osf.io | 0 | 11710 | <filename>admin/collection_providers/forms.py
import bleach
import json
from django import forms
from osf.models import CollectionProvider, CollectionSubmission
from admin.base.utils import get_nodelicense_choices, get_defaultlicense_choices
class CollectionProviderForm(forms.ModelForm):
collected_type_choices ... | 1.90625 | 2 |
src/validate_model.py | mareklinka/esk-form-scanner-model | 0 | 11711 | <filename>src/validate_model.py
import data_providers as gen
import model_storage as storage
import numpy as np
import data_visualizer
import time
def evaluate(model_name):
"""
Evaluates the model stored in the specified file.
Parameters
----------
model_name : string
The name of the fil... | 3.203125 | 3 |
sdk/formrecognizer/azure-ai-formrecognizer/azure/ai/formrecognizer/_generated/v3_0_preview_1/models/_form_recognizer_client_enums.py | rsdoherty/azure-sdk-for-python | 0 | 11712 | <gh_stars>0
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# ... | 2.15625 | 2 |
activity_log/migrations/0004_auto_20170309_0929.py | farezsaputra/BandwidthControllingSystem | 0 | 11713 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('activity_log', '0003_activitylog_extra_data'),
]
operations = [
migrations.AlterField(
... | 1.765625 | 2 |
bin/read_oogeso_data.py | oogeso/oogeso | 2 | 11714 | <filename>bin/read_oogeso_data.py<gh_stars>1-10
import json
import oogeso.io.file_io
# Read in data, validate date et.c. with methods from io
test_data_file = "examples/test case2.yaml"
json_data = oogeso.io.file_io.read_data_from_yaml(test_data_file)
json_formatted_str = json.dumps(json_data, indent=2)
print("Type ... | 2.953125 | 3 |
TWITOFF/__init__.py | DSPT3/Twitoff | 0 | 11715 | <filename>TWITOFF/__init__.py
""" Entry Point for Our Twitoff Flask App """
from .app import create_app
APP = create_app() | 1.242188 | 1 |
fgivenx/test/test_mass.py | ejhigson/fgivenx | 11 | 11716 | import numpy
import pytest
import os
from shutil import rmtree
from numpy.testing import assert_allclose
import scipy.stats
import scipy.integrate
import scipy.special
from fgivenx.mass import PMF, compute_pmf
def gaussian_pmf(y, mu=0, sigma=1):
return scipy.special.erfc(numpy.abs(y-mu)/numpy.sqrt(2)/sigma)
def... | 2.234375 | 2 |
homeassistant/components/vera/config_flow.py | liangleslie/core | 2 | 11717 | """Config flow for Vera."""
from __future__ import annotations
from collections.abc import Mapping
import logging
import re
from typing import Any
import pyvera as pv
from requests.exceptions import RequestException
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries i... | 2.15625 | 2 |
bin/setup_spectrum.py | MFSJMenger/pysurf | 7 | 11718 | <filename>bin/setup_spectrum.py<gh_stars>1-10
import os
from shutil import copy2 as copy
#
from pysurf.logger import get_logger
from pysurf.sampling import Sampling
from pysurf.setup import SetupBase
from pysurf.utils import exists_and_isfile
from pysurf.spp import SurfacePointProvider
from colt import Colt
from sp_ca... | 2.4375 | 2 |
CeV - Gustavo Guanabara/exerc033.py | us19861229c/Meu-aprendizado-Python | 1 | 11719 | <gh_stars>1-10
#033: ler tres numeros e dizer qual o maior e qual o menor:
print("Digite 3 numeros:")
maiorn = 0
n = int(input("Numero 1: "))
if n > maiorn:
maiorn = n
menorn = n
n = int(input("Numero 2: "))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
n = int(input("Numero 3: "))
if n > maiorn:... | 3.875 | 4 |
test/test_dot.py | croqaz/dot | 0 | 11720 | <reponame>croqaz/dot
import pytest
from prop import strict_get
from prop import get as dot_get
class A:
def __init__(self, val):
self.val = val
def test_dot_get_list():
assert dot_get(['asd'], '0') == dot_get(['asd'], ['0']) == 'asd'
data = {'nested': [0, False, 'foo']}
assert dot_get(data... | 2.453125 | 2 |
site_scons/site_tools/mplabx_nbproject/__init__.py | kbhomes/ps2plus | 0 | 11721 | from pprint import pprint
import SCons.Builder
from SCons.Script import *
import json
import os
import copy
import collections
import xml.etree.ElementTree as ET
from mplabx import MPLABXProperties
MAKEFILE_TEXT = '''
MKDIR=mkdir
CP=cp
CCADMIN=CCadmin
RANLIB=ranlib
build: .build-post
.build-pre:
.build-post: .build-i... | 2.28125 | 2 |
lib/autoconnect/example/test_server.py | simotek/autoconnect | 0 | 11722 | <gh_stars>0
#
# test_server.py
#
# Copyright (C) 2001-2007 <NAME>.
# Email: <EMAIL>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the Li... | 2.59375 | 3 |
tests/test_loop_seer.py | Kyle-Kyle/angr | 6,132 | 11723 | <gh_stars>1000+
import os
import sys
import angr
import nose.tools
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')
def test_various_loops():
p = angr.Project(os.path.join(test_location, 'x86_64', 'various_loops'), auto_load_libs=False)
cfg = p.anal... | 1.867188 | 2 |
shongololo/Imet_serial.py | swyngaard/shongololo | 0 | 11724 | import serial , time , os
import serial.tools.list_ports as port
import logging
sho_logger = logging.getLogger("shongololo_logger")
def open_imets(devices):
"""Tries to open as many imet device serial ports as there are
:return:
a list of socket handles
"""
imet_sockets = []
for d in range(... | 2.875 | 3 |
libs/external_libs/docutils-0.4/test/test_transforms/test_peps.py | google-code-export/django-hotclub | 3 | 11725 | #! /usr/bin/env python
# Author: <NAME>
# Contact: <EMAIL>
# Revision: $Revision: 3915 $
# Date: $Date: 2005-10-02 03:06:42 +0200 (Sun, 02 Oct 2005) $
# Copyright: This module has been placed in the public domain.
"""
Tests for docutils.transforms.peps.
"""
from __init__ import DocutilsTestSupport
from docutils.tran... | 2.484375 | 2 |
rental_property/migrations/0011_alter_rentalunit_options.py | shumwe/rental-house-management-system | 1 | 11726 | # Generated by Django 4.0.2 on 2022-03-15 22:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rental_property', '0010_alter_rentalunit_status'),
]
operations = [
migrations.AlterModelOptions(
name='rentalunit',
options... | 1.484375 | 1 |
AxesFrame.py | Toyuri453/RSSP-Python-demo | 1 | 11727 | <filename>AxesFrame.py
import Terminal
class Axes():
def __init__(self, weak_terminal : 'Terminal.CartesianPoint'):
# self._initiator_x = weak_terminal._x
# self._initiator_y = weak_terminal._y
self._initiator = Terminal.CartesianPoint(0.0, 0.0, "UWB", "initiator")
self._weak... | 2.703125 | 3 |
api/generate.py | almeida-matheus/playlist-reader | 0 | 11728 | <reponame>almeida-matheus/playlist-reader
import re
from bs4 import BeautifulSoup # beautifulsoup4
import requests # requests
HEADER = {
"User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
}
def catch_info(base,pattern,str_add='... | 3.109375 | 3 |
homeassistant/components/deconz/const.py | hoverduck/core | 1 | 11729 | <filename>homeassistant/components/deconz/const.py
"""Constants for the deCONZ component."""
import logging
LOGGER = logging.getLogger(__package__)
DOMAIN = "deconz"
CONF_BRIDGE_ID = "bridgeid"
CONF_GROUP_ID_BASE = "group_id_base"
DEFAULT_PORT = 80
DEFAULT_ALLOW_CLIP_SENSOR = False
DEFAULT_ALLOW_DECONZ_GROUPS = Tru... | 1.679688 | 2 |
course_app/api/views.py | maks-nurgazy/diploma-project | 0 | 11730 | <reponame>maks-nurgazy/diploma-project
import json
from rest_framework.generics import ListAPIView, get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from course_app.api.serializers import CourseSerializer
from cour... | 2.203125 | 2 |
service/repository/repository_controller.py | yutiansut/cilantro | 3 | 11731 | <gh_stars>1-10
import os
import json
import logging
import yaml
from flask import Blueprint, jsonify, send_file, request, redirect
from service.errors import ApiError
from utils.repository import generate_repository_path, \
list_objects_in_repository
from utils.list_dir import list_dir
repository_controller = Bl... | 2.65625 | 3 |
src/python_import/C/cc.py | matiastang/matias-python | 0 | 11732 | #!/usr/bin/python3
#coding=utf-8
def cc_debug():
print(__name__) | 1.234375 | 1 |
plugin.audio.podcasts/addon.py | stobb3s/kodi-addon-podcast | 0 | 11733 | from datetime import datetime
import base64
import os
import re
import requests
import sys
import urllib.parse
import xmltodict
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import xbmcvfs
__PLUGIN_ID__ = "plugin.audio.podcasts"
# see https://forum.kodi.tv/showthread.php?tid=112916
_MONTHS = ["Jan", ... | 2.3125 | 2 |
.venv/Lib/site-packages/lemoncheesecake/reporting/savingstrategy.py | yadavdeepa365/HUDL_PYTHON | 34 | 11734 | import re
import time
from lemoncheesecake.events import TestSessionSetupEndEvent, TestSessionTeardownEndEvent, \
TestEndEvent, SuiteSetupEndEvent, SuiteTeardownEndEvent, SuiteEndEvent, SteppedEvent
from lemoncheesecake.reporting.report import ReportLocation
DEFAULT_REPORT_SAVING_STRATEGY = "at_each_failed_test"
... | 2.234375 | 2 |
genshin/models/genshin/chronicle/notes.py | thesadru/genshin.py | 63 | 11735 | """Genshin chronicle notes."""
import datetime
import typing
import pydantic
from genshin.models.genshin import character
from genshin.models.model import Aliased, APIModel
__all__ = ["Expedition", "ExpeditionCharacter", "Notes"]
def _process_timedelta(time: typing.Union[int, datetime.timedelta, datetime.datetime]... | 2.453125 | 2 |
src/the_tale/the_tale/common/bbcode/renderer.py | al-arz/the-tale | 85 | 11736 | <reponame>al-arz/the-tale
import smart_imports
smart_imports.all()
class Renderer:
__slots__ = ('tags', '_renderer')
def __init__(self, tags):
self.tags = tags
self._renderer = postmarkup.create(include=[],
use_pygments=False,
... | 2.203125 | 2 |
tests/python/unittest/test_meta_schedule_custom_rule_winograd_cpu.py | psrivas2/relax | 11 | 11737 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 1.882813 | 2 |
model_zoo/official/cv/FCN8s/src/nets/FCN8s.py | LottieWang/mindspore | 0 | 11738 | <filename>model_zoo/official/cv/FCN8s/src/nets/FCN8s.py<gh_stars>0
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.or... | 2.171875 | 2 |
scripts/seqrun_processing/sync_seqrun_data_from_remote.py | imperial-genomics-facility/data-management-python | 7 | 11739 | #!/usr/bin/env python
import argparse
from igf_data.task_tracking.igf_slack import IGF_slack
from igf_data.process.data_transfer.sync_seqrun_data_on_remote import Sync_seqrun_data_from_remote
parser = argparse.ArgumentParser()
parser.add_argument('-r','--remote_server', required=True, help='Remote server address')
par... | 2.109375 | 2 |
pydashlite/arrays/sum_by.py | glowlex/pydashlite | 0 | 11740 | from typing import Callable, Iterable, TypeVar
T = TypeVar('T')
Num = TypeVar('Num', int, float)
def sumBy(array: Iterable[T], iteratee: Callable[[T], Num] = None, start: Num = 0) -> Num:
if iteratee is None:
return sum([y for y in array], start)
return sum([iteratee(y) for y in array], start)
| 3.40625 | 3 |
Ten_Most_Common_Words.py | mcjohnchristopher/Python_Samples | 0 | 11741 | <reponame>mcjohnchristopher/Python_Samples
fhand = (romeo.txt)
counts = dict()
for line in fhand:
words = line.split()
for word in words():
count word = count.get(word, 0) + 1
st = list
for Key,Value in count.items():
st.append((val,key))
st.sort(reverse = true)
for val,key in st[:10]:
print key, v... | 3.25 | 3 |
python/testData/intentions/convertLambdaToFunction.py | jnthn/intellij-community | 2 | 11742 | newlist = lambda x<caret>, y: (x+y)/y
x = 1 | 1.554688 | 2 |
src/grpc_client.py | thealphadollar/py-grpcio-pg | 0 | 11743 | import grpc
from consts import PORT, SERVER_CERT
from grpc_generated_files import api_pb2, api_pb2_grpc
def main(stub):
request = api_pb2.ApiRequest(
name="Shivam",
message="Hey there!"
)
response = stub.ApiEndpoint(request)
print(response)
if __name__ == "__main__":
with open(S... | 2.78125 | 3 |
0188.Best Time to Buy and Sell Stock IV/solution.py | zhlinh/leetcode | 0 | 11744 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: <EMAIL>
Version: 0.0.1
Created Time: 2016-03-23
Last_modify: 2016-03-23
******************************************
'''
'''
Say you have an array for which the ith element is
th... | 3.90625 | 4 |
gips/gistmodel/post_processing.py | accsc/gips | 1 | 11745 | <filename>gips/gistmodel/post_processing.py
import numpy as np
import copy
from gips import FLOAT
from gips import DOUBLE
class post_processing(object):
def __init__(self, fitter, x, pairs=False, prefix=None):
self.fitter = fitter
self.x = x
self.pairs = pairs
self.case =... | 2.625 | 3 |
src/Cogs/InfoCog.py | kodyVS/Discord-Bot-Development | 5 | 11746 | <filename>src/Cogs/InfoCog.py
from discord.ext import commands
import discord
import requests
from bs4 import BeautifulSoup
# work in progress! more languages welcome!
class InfoCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name = 'docs', brief = 'programming language d... | 2.765625 | 3 |
Python/List/37.drop.py | angelmpalomares/ModelAndLanguagesForBioInformatics | 0 | 11747 | def drop(i_list: list,n:int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert(n>0)
_shallow_list = []
k=1
for element in i_list:
if k % n != 0:
... | 3.921875 | 4 |
cil/balanced_experience_replay.py | itaicaspi-intel/advanced-coach | 1 | 11748 | <gh_stars>1-10
#
# Copyright (c) 2017 Intel Corporation
#
# 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 l... | 2.0625 | 2 |
tools/schedprof/schedprof/mutex.py | ivochkin/dfk | 1 | 11749 | <reponame>ivochkin/dfk
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from schedprof.enumerated_instance import EnumeratedInstance
class Mutex(EnumeratedInstance):
def __init__(self):
super(Mutex, self).__init__(Mutex)
self.acquired_by = None
self.wait_queue = []
| 2.25 | 2 |
openpype/hosts/houdini/plugins/publish/increment_current_file.py | jonclothcat/OpenPype | 87 | 11750 | import pyblish.api
import avalon.api
from openpype.api import version_up
from openpype.action import get_errored_plugins_from_data
class IncrementCurrentFile(pyblish.api.InstancePlugin):
"""Increment the current file.
Saves the current scene with an increased version number.
"""
label = "Increment... | 2.21875 | 2 |
968 Binary Tree Cameras.py | krishna13052001/LeetCode | 872 | 11751 | #!/usr/bin/python3
"""
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One c... | 4.09375 | 4 |
examples/get_tiktoks_by_sound.py | twitter-79/TikTok-Api | 2,095 | 11752 | <gh_stars>1000+
from TikTokApi import TikTokApi
api = TikTokApi.get_instance()
count = 30
# You can find this from a tiktok getting method in another way or find songs from the discoverMusic method.
sound_id = "6601861313180207878"
tiktoks = api.by_sound(sound_id, count=count)
for tiktok in tiktoks:
print(tikt... | 2.515625 | 3 |
code/SimPleAC_pof_paperplots.py | 1ozturkbe/robustSPpaper | 0 | 11753 | from builtins import str
from builtins import range
from robust.simulations.simulate import filter_gamma_result_dict
from SimPleAC_save import load_obj
import pickle as pickle
import numpy as np
import matplotlib.pyplot as plt
from SimPleAC_pof_simulate import pof_parameters
if __name__ == "__main__":
# Retrieving... | 2.21875 | 2 |
test/show-cifar10.py | tom01h/deep-learning-from-scratch | 3 | 11754 | <filename>test/show-cifar10.py<gh_stars>1-10
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
from dataset.cifar10 import load_cifar10
from PIL import Image
np.set_printoptions(threshold=100)
(x_train, t_train), (x_test, t_test) = load_cifar10(flatten=... | 2.859375 | 3 |
vertex-server/signals/__init__.py | aoswalt/greenlite-hardware | 0 | 11755 | from . import lights
from . import schedule
| 0.9375 | 1 |
PWWS/fool.py | ForeverZyh/ASCC | 21 | 11756 | <reponame>ForeverZyh/ASCC
# coding: utf-8
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import argparse
import os
import numpy as np
from read_files import split_imdb_files, split_yahoo_files, split_agnews_files
from word_level_process import wo... | 1.96875 | 2 |
test_training_data.py | miermans/gym-2048 | 0 | 11757 | #!/usr/bin/env python
from __future__ import absolute_import
import numpy as np
import os
import pytest
import tempfile
import training_data
class TestTrainingData():
def test_add(self):
td = training_data.training_data()
assert np.array_equal(td.get_x(), np.empty([0, 4, 4], dtype=np.int))
... | 2.546875 | 3 |
tests/test_db_exam_psd.py | awenhaowenchao/bee | 4 | 11758 | <reponame>awenhaowenchao/bee
from datetime import datetime
from bee import Psd, CX, On, T
from bee import Model, IntegerField, StringField, DateTimeField, Equal, W, C
db_exam = Psd.open("exam")
# 1) sing table count search, SELECT COUNT(*) AS COUNT FROM t_teacher
with db_exam.connection() as conn:
teacher_count =... | 2.78125 | 3 |
slybot/slybot/plugins/scrapely_annotations/builder.py | coolkunal64/ht | 0 | 11759 | <gh_stars>0
import json
from scrapy import Selector
from scrapy.utils.spider import arg_to_iter
from scrapely.htmlpage import parse_html, HtmlTag, HtmlDataFragment
from collections import defaultdict
from itertools import tee, count, groupby
from operator import itemgetter
from slybot.utils import (serialize_tag, ad... | 2.21875 | 2 |
scripts/slave/recipes/mojo.py | bopopescu/chromium-build | 0 | 11760 | <filename>scripts/slave/recipes/mojo.py
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'adb',
'depot_tools/bot_update',
'depot_tools/gclient',
'goma',
'recipe_engine/context',
'recipe... | 1.46875 | 1 |
lib/navigation/AreaFighting.py | sadnecc/pb | 0 | 11761 | <gh_stars>0
# -*- coding:utf8 -*-
import random
import time
from lib.navigation.PathFinding import Pathfinding
from lib.control.Control import Control
from lib.unit.Player import Player
from lib.struct.CoordiPoint import CoordiPoint
# 区域打怪
class AreaFighting(Pathfinding):
# area_pos: 区域4角坐标。顺序为:左上,右上,左下,右下
def... | 2.59375 | 3 |
compress.py | willemwouters/PhotoboothPi | 0 | 11762 | <filename>compress.py<gh_stars>0
import os
import time
import sys
if(len(sys.argv) is 1):
path="/home/pi/storage/"
else:
path=sys.argv[1]
try:
arr=[]
for filename in os.listdir(path):
if("2018-09" in filename):
arr.append(filename)
for f in arr:
filen = os.path.spl... | 2.59375 | 3 |
html/en/reference/graphs/sage/graphs/graph_plot-2.py | sagemath/documentation | 10 | 11763 | <reponame>sagemath/documentation
petersen_spring = Graph(':I`ES@obGkqegW~')
sphinx_plot(petersen_spring) | 1.234375 | 1 |
module00/ex05/kata00.py | MedAymenF/42AI-Python-bootcamp | 0 | 11764 | <filename>module00/ex05/kata00.py<gh_stars>0
t = (19, 42, 21)
print(f"The {len(t)} numbers are: {t[0]}, {t[1]}, {t[2]}")
| 2.3125 | 2 |
examples/cochrane-simplification/log_regression/bow_newsela_lm_tokens.py | AshOlogn/transformers | 0 | 11765 | import json
import os
from os.path import join
from random import shuffle
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import MinMaxScaler, normalize
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cros... | 2.328125 | 2 |
fdrtd_server/exceptions.py | UNakade/server | 0 | 11766 | <filename>fdrtd_server/exceptions.py
import logging as _logging
def handle_exception(e):
if isinstance(e, ApiError):
_logging.exception(e.message)
return e.message, e.statuscode
_logging.exception(repr(e))
return None, 500
class ApiError(Exception):
def __init__(self, statuscode, ... | 2.421875 | 2 |
TCU/usageexample/automationexample.py | p--q/TCU | 0 | 11767 | <reponame>p--q/TCU
#!/opt/libreoffice5.4/program/python
# -*- coding: utf-8 -*-
import unohelper # オートメーションには必須(必須なのはuno)。
def macro():
ctx = XSCRIPTCONTEXT.getComponentContext() # コンポーネントコンテクストの取得。
smgr = ctx.getServiceManager() # サービスマネージャーの取得。
tcu = smgr.createInstanceWithContext("pq.Tcu", ctx) # サービス名か実装名でイ... | 1.976563 | 2 |
last_char.py | AkhilaSaiBejjarapu/Python | 0 | 11768 | word=input()
last_letter=(len(word)-1)
result=word[last_letter]
print(result) | 3.828125 | 4 |
simple_retry/decorators.py | nicolasmota/retry_decorator | 11 | 11769 | <filename>simple_retry/decorators.py
import time
from functools import wraps
import asyncio
from simple_retry.simple_retry.helpers import (
format_retry_message,
has_retries_to_go,
log_message
)
def retry(Except, retries=5, delay=0, logger=None, level='info', multiple=1):
def deco_retry(function):... | 2.578125 | 3 |
environment.py | bopopescu/cbrc-devteam-blog | 0 | 11770 | <filename>environment.py
# application environment
import settings
import sys
sys.path.append(settings.app_home_dir)
sys.path.append(settings.app_settings["app_lib_dir"])
| 1.71875 | 2 |
cogeo_mosaic/backends/base.py | drnextgis/cogeo-mosaic | 0 | 11771 | <reponame>drnextgis/cogeo-mosaic<filename>cogeo_mosaic/backends/base.py<gh_stars>0
"""cogeo_mosaic.backend.base: base Backend class."""
import abc
import itertools
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
import attr
import mercantile
from cachetools import TTLCache, cached
from cach... | 2.140625 | 2 |
userge/core/methods/decorators/on_filters.py | wildyvpn-network/bot | 0 | 11772 | # pylint: disable=missing-module-docstring
#
# Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >.
#
# This file is part of < https://github.com/UsergeTeam/Userge > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/uaudith/Userge/blob/master/LIC... | 2.1875 | 2 |
pygromos/tests/test_submission/test_hpc_queuing_submission_scheduling.py | pultar/PyGromosTools | 13 | 11773 | import unittest, tempfile
from pygromos.simulations.hpc_queuing.job_scheduling.schedulers import simulation_scheduler
from pygromos.data.simulation_parameters_templates import template_md
from pygromos.data.topology_templates import blank_topo_template
from pygromos.simulations.hpc_queuing.submission_systems import D... | 1.890625 | 2 |
tutorials.py | Xython/pattern-matching | 20 | 11774 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 30 17:03:01 2017
@author: misakawa
"""
from pattern_matching import Match, when, var, T, t, _, overwrite
from numpy.random import randint
@overwrite(var[(t == int) | (t == float)], var[(t == int) | (t == float)])
def add(a, b):
return a + b
@when(var[t == str], v... | 3.0625 | 3 |
RepositoryBootstrap/EnvironmentDiffs.py | davidbrownell/v3-Common_Environment | 0 | 11775 | # ----------------------------------------------------------------------
# |
# | EnvironmentDiffs.py
# |
# | <NAME> <<EMAIL>>
# | 2018-06-02 22:19:34
# |
# ----------------------------------------------------------------------
# |
# | Copyright <NAME> 2018-22.
# | Distributed under the Boost Software... | 1.609375 | 2 |
tests/model/test_ocrd_mets.py | wrznr/pyocrd | 0 | 11776 | from datetime import datetime
from os.path import join
from tests.base import TestCase, main, assets, copy_of_directory
from ocrd_utils import (
initLogging,
VERSION,
MIMETYPE_PAGE
)
from ocrd_models import OcrdMets
# pylint: disable=protected-access,deprecated-method,too-many-public-methods
class TestOcr... | 2.21875 | 2 |
robo_gym/envs/ur/ur_avoidance_basic.py | psFournier/robo-gym | 236 | 11777 | """
Environment for basic obstacle avoidance controlling a robotic arm from UR.
In this environment the obstacle is only moving up and down in a vertical line in front of the robot.
The goal is for the robot to stay within a predefined minimum distance to the moving obstacle.
When feasible the robot should continue to... | 3.6875 | 4 |
hear_me_django_app/accounts/management/commands/initial_users.py | kamil1marczak/hear_me_django_app | 0 | 11778 | <filename>hear_me_django_app/accounts/management/commands/initial_users.py
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.core.management.base import BaseCommand
from ._private import populate_user
User = get_user_model()
class Command(BaseCommand):
... | 2.28125 | 2 |
config/constants.py | flopezag/fiware-tsc-dashboard | 0 | 11779 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2017 FIWARE Foundation, e.V.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | 1.304688 | 1 |
tensornetwork/backends/backend_test.py | ashoknar/TensorNetwork | 0 | 11780 | <gh_stars>0
"""Tests for graphmode_tensornetwork."""
import builtins
import sys
import pytest
import numpy as np
from tensornetwork import connect, contract, Node
from tensornetwork.backends.base_backend import BaseBackend
from tensornetwork.backends import backend_factory
def clean_tensornetwork_modules():
for mod... | 1.921875 | 2 |
src/GUI/Plotter.py | sbooeshaghi/pegasus | 1 | 11781 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyqtgraph as pg
import numpy as np
class CustomWidget(pg.GraphicsWindow):
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
def __init__(self, parent=None, **kargs):
pg.GraphicsWindow.__init__(self, **kargs)
sel... | 3.078125 | 3 |
tests/test_collapsible.py | TehMillhouse/sphinxawesome-theme | 17 | 11782 | """Tests for collapsible definition lists.
When the option ``html_collapsible_definitions``
is ``True``, some HTML classes should be added
to some definition lists but not all of them.
"""
from pathlib import Path
import pytest
from sphinx.application import Sphinx
from .util import parse_html
@pytest.mark.sphinx... | 2.625 | 3 |
Iris Network/Conclusion/task.py | jetbrains-academy/Machine-Learning-101 | 0 | 11783 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from network import NN
from evaluate import accuracy
def read_data(fpath):
iris = pd.read_csv(fpath)
iris.loc[iris['species'] == 'virginica', 'species'] = 0
iris.loc[iris['species'] == 'versicolor', 'species'] = 1
iris.loc[iris['sp... | 3.09375 | 3 |
agentless/crypto.py | tinyauth/agentless | 0 | 11784 | <gh_stars>0
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
backend = default_backend()
def generate_private_key():
key = rsa.generate_private_key(
public_exponent=... | 2.46875 | 2 |
test/programytest/storage/entities/test_nodes.py | cdoebler1/AIML2 | 345 | 11785 | import unittest
import unittest.mock
from programy.storage.entities.nodes import NodesStore
class NodesStoreTest(unittest.TestCase):
def test_load(self):
store = NodesStore()
with self.assertRaises(NotImplementedError):
collector = unittest.mock.Mock()
store.load(collecto... | 2.65625 | 3 |
sphinx/source/tutorial/exercises/stocks.py | minrk/bokeh | 0 | 11786 | <reponame>minrk/bokeh
import numpy as np
import pandas as pd
from bokeh.plotting import *
# Here is some code to read in some stock data from the Yahoo Finance API
AAPL = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000",
parse_dates=['Date'])
GOOG = pd.read_csv(
"http://ichart.yahoo... | 3.375 | 3 |
nni/retiarii/converter/visualize.py | qfyin/nni | 3 | 11787 | import graphviz
def convert_to_visualize(graph_ir, vgraph):
for name, graph in graph_ir.items():
if name == '_training_config':
continue
with vgraph.subgraph(name='cluster'+name) as subgraph:
subgraph.attr(color='blue')
cell_node = {}
ioput = {'_inpu... | 2.765625 | 3 |
Python/Tests/TestData/TestDiscoverer/ConfigUnittest/Product/prefix_not_included.py | techkey/PTVS | 404 | 11788 | import unittest
class PrefixNotIncluded(unittest.TestCase):
def test_not_included(self):
pass
if __name__ == '__main__':
unittest.main()
| 1.820313 | 2 |
customBackground.py | VisweshK/Jashmup | 0 | 11789 | '''
This is the class to create a scrolling background.
Because the background was so large, it was made to be a .jpg.
'''
import pygame, os
class Background(pygame.sprite.Sprite):
# Initialize the sprite.
def __init__(self,disp):
pygame.sprite.Sprite.__init__(self)
self.image = pygame... | 3.921875 | 4 |
src/python/squarepants/file_utils.py | ericzundel/mvn2pants | 8 | 11790 | <filename>src/python/squarepants/file_utils.py
import os
import shutil
from contextlib import contextmanager
from tempfile import mkdtemp, mktemp
@contextmanager
def temporary_dir():
"""Returns a temporary directory that gets cleaned up when the context manager exits."""
tempdir = mkdtemp()
try:
yield tempd... | 3.21875 | 3 |
docs/DSDC/miniprez/miniprez/continuous_integration.py | thoppe/Presentation_Topics | 2 | 11791 | <filename>docs/DSDC/miniprez/miniprez/continuous_integration.py<gh_stars>1-10
import asyncio
import os
from parser import miniprez_markdown, build_body
import logging
logger = logging.getLogger("miniprez")
async def file_watcher(target_file, sleep_time=0.5):
"""
Watchs a file. If modified, yield the filenam... | 2.78125 | 3 |
rl_algorithms/dqn/linear.py | yonghangzhou/rl_algorithms | 1 | 11792 | # -*- coding: utf-8 -*-
"""Linear module for dqn algorithms
- Author: <NAME>
- Contact: <EMAIL>
"""
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from rl_algorithms.common.helper_functions import numpy2floattensor
device = torch.device("cuda:0" if torch.cuda.is_a... | 2.8125 | 3 |
2015/day7/2015-day7-part2.py | matt-the-ogre/advent-of-code | 1 | 11793 | # Advent of Code - 2015 - Day 7
# --- Day 7: Some Assembly Required ---
# This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit.
# Each wire has an identifier (some lowerca... | 3.484375 | 3 |
flink-ai-flow/examples/workflow_on_event/workflows/init/init.py | lisy09/flink-ai-extended | 0 | 11794 | <reponame>lisy09/flink-ai-extended
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version... | 1.453125 | 1 |
platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/bobcat/profiles/Profile_WiSUN.py | SiliconLabs/Gecko_SDK | 82 | 11795 | <filename>platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/bobcat/profiles/Profile_WiSUN.py
from pyradioconfig.parts.ocelot.profiles.Profile_WiSUN import Profile_WiSUN_Ocelot
from pyradioconfig.parts.common.profiles.bobcat_regs import build_modem_regs_bobcat
from pyradioconfig.parts.common.profiles.profil... | 1.96875 | 2 |
tests/dgds_functions_test.py | openearth/hydro-engine-service | 4 | 11796 | import logging
import pytest
from . import auth
from hydroengine_service import dgds_functions
logger = logging.getLogger(__name__)
class TestDGDSFunctions:
@pytest.mark.parametrize('source, start_date, end_date, limit',
[
('projects/dgds-gee/bathym... | 2.171875 | 2 |
smol_opyt/logistic_problem.py | abelsiqueira/smol-opyt | 0 | 11797 | <filename>smol_opyt/logistic_problem.py
from math import log
import numpy as np
from numpy import linalg as la
class LogisticProblem:
"""Class for the logistic regression method for classification."""
def __init__(self, feat_mtx, y):
"""Create a Logistic Problem with matrix `feat_mtx` n by p and vecto... | 3.46875 | 3 |
TeamClassificationUtils.py | Neerajj9/Computer-Vision-based-Offside-Detection-in-soccer | 8 | 11798 | <gh_stars>1-10
import numpy as np
# TODO : add code for referee
def get_team_classifications(teamColor1, teamColor2, refColor, keeper1Color, keeper2Color, pose_estimations):
for pose in pose_estimations:
if len(pose[1]) < 2:
pose.append('color not found')
continue
c... | 2.359375 | 2 |
examples/PTSD/mpi_tmp/PTSD_cognet.py | zeroknowledgediscovery/cognet | 0 | 11799 | <gh_stars>0
from mpi4py.futures import MPIPoolExecutor
import numpy as np
import pandas as pd
from quasinet.qnet import Qnet, qdistance, load_qnet, qdistance_matrix
from quasinet.qsampling import qsample, targeted_qsample
qnet=load_qnet('../results/PTSD_cognet_test.joblib')
w = 304
h = w
p_all = pd.read_csv("tmp_sampl... | 2.296875 | 2 |