content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2018.5
# Email : muyanru345@163.com
###################################################################
from dayu_widgets.item_model import MSortFilterModel, MTableModel
from d... | dayu_widgets/item_view_set.py | 3,120 | Enable search line edit visible.
!/usr/bin/env python -*- coding: utf-8 -*- Author: Mu yanru Date : 2018.5 Email : muyanru345@163.com | 135 | en | 0.263348 |
# Generated by Django 2.2 on 2019-05-08 20:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fie... | app/core/migrations/0001_initial.py | 1,699 | Generated by Django 2.2 on 2019-05-08 20:45 | 43 | en | 0.559877 |
import time
import datetime
import json
import hashlib
from .env import Env
from .server import Server
from .hardware import Hardware
class Metric(object):
def __init__(self):
# format of report data
self._version = '0.1'
self._type = 'metric'
self.run_id = None
self.mode =... | tests/benchmark/milvus_benchmark/metrics/models/metric.py | 1,516 | format of report data Get current time as run id, which uniquely identifies this test Set the deployment mode of milvus including: metric, suite_metric Set the final result of the test run: RUN_SUCC or RUN_FAILED | 212 | en | 0.852689 |
from credentials import credentials
import unittest
import pyperclip
class TestUser(unittest.TestCase):
'''
Test that defines test cases for the User class
Args:
unitest.Testcase: Testcase that helps in creating test cases for class User.
'''
def setUp(self):
'''
Set up me... | credentials_test.py | 918 | Test that defines test cases for the User class
Args:
unitest.Testcase: Testcase that helps in creating test cases for class User.
Set up method to run before each test case
test__init__ test case to test if the object is initialized properly
test to see if the user is saved | 279 | en | 0.783039 |
import inspect
import sys
from enum import IntEnum
from pathlib import Path
from time import time
from logging import getLevelName
from typing import Tuple, Union, Any, List, Iterable, TextIO, Optional
from . import logging
from .logging import _set_log_level, _set_log_file, RootLogger
_VERBOSITY_TO_LOGLEVEL = {
... | scanpy/_settings.py | 14,034 | Config manager for scanpy.
Determines whether run from Ipython.
Only affects progress bars.
Automatically save figures in :attr:`~scanpy._settings.ScanpyConfig.figdir` (default `False`).
Do not show plots/figures interactively.
Automatically show figures if `autosave == False` (default `True`).
There is no need... | 3,199 | en | 0.574073 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | docs/source/conf.py | 5,046 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions ... | 3,704 | en | 0.621105 |
from typing import Optional
import torch
from torch import Tensor
@torch.jit._overload # noqa
def fps(src, batch=None, ratio=None, random_start=True): # noqa
# type: (Tensor, Optional[Tensor], Optional[float], bool) -> Tensor
pass # pragma: no cover
@torch.jit._overload # noqa
def fps(src, batch=None, ... | torch_cluster/fps.py | 2,374 | "A sampling algorithm from the `"PointNet++: Deep Hierarchical Feature
Learning on Point Sets in a Metric Space"
<https://arxiv.org/abs/1706.02413>`_ paper, which iteratively samples the
most distant point with regard to the rest points.
Args:
src (Tensor): Point feature matrix
:math:`\mathbf{X} \in \mathb... | 1,193 | en | 0.474461 |
import pytest
import click
from click.testing import CliRunner
from click._compat import PY2
# Use the most reasonable io that users would use for the python version.
if PY2:
from cStringIO import StringIO as ReasonableBytesIO
else:
from io import BytesIO as ReasonableBytesIO
def test_runner():
@click.... | vendor/packages/click/tests/test_testing.py | 2,994 | Use the most reasonable io that users would use for the python version. | 71 | en | 0.939259 |
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API '''
''' nonstoptimm@gmail.com '''
# Import required packages
import os
import glob
import json
import logging
import codecs
import helper as he
import azure.cognitiveservices.speech as speechsdk
import params as pa
# Load and set configuration parameters
pa.get_config()
... | src/stt.py | 5,176 | Main function for STT-functionality
Args:
speech_files: Directory of audio files to be transcribed
output_directory: Output directory for the file
lexical: Boolean to enable extended lexical version of STT-result
enable_proxy: Boolean to enable proxy function in case you need it
*argv: Proxy informa... | 1,733 | en | 0.72817 |
# Generated by Django 3.2.8 on 2021-11-29 09:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('budget', '0004_auto_20211125_1330'),
]
operations = [
migrations.DeleteModel(
name='VehicleLog',
),
]
| django_budget/budget/migrations/0005_delete_vehiclelog.py | 298 | Generated by Django 3.2.8 on 2021-11-29 09:01 | 45 | en | 0.697935 |
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang
# Mingshuang Luo)
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... | egs/librispeech/ASR/tdnn_lstm_ctc/train.py | 17,862 | Compute CTC loss given the model and its inputs.
Args:
params:
Parameters for training. See :func:`get_params`.
model:
The model for training. It is an instance of TdnnLstm in our case.
batch:
A batch of data. See `lhotse.dataset.K2SpeechRecognitionDataset()`
for the content in it.
graph_compil... | 5,388 | en | 0.815464 |
from collections import OrderedDict, defaultdict
from typing import Optional, Dict, Tuple, List
import ariadne
from irrd.rpki.status import RPKIStatus
from irrd.rpsl.fields import RPSLFieldListMixin, RPSLTextField, RPSLReferenceField
from irrd.rpsl.rpsl_objects import (lookup_field_names, OBJECT_CLASS_MAPPING, RPSLAu... | irrd/server/graphql/schema_generator.py | 12,840 | The schema generator generates a GraphQL schema.
The purpose is to provide a schema to which resolvers are then
attached, which is then given to Ariadne, and for resolvers to
have information about expected types.
For RPSL queries and types, this is dynamically generated based on
the RPSL objects from irrd.rpsl. Other... | 1,859 | en | 0.9122 |
"""
Argo Workflows API
Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes. For more information, please see https://argoproj.github.io/argo-workflows/ # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-g... | sdks/python/client/argo_workflows/model/lifecycle_handler.py | 12,058 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the a... | 6,233 | en | 0.796123 |
import grpc
import threading
import proto.connection_pb2_grpc
from libs.core.Log import Log
from libs.core.Switch import Switch
from libs.core.Event import Event
from libs.Configuration import Configuration
class SwitchConnection:
def __init__(self, grpc_address=None):
self.channel = grpc.insecure_channe... | Controller-Implementation/libs/core/SwitchConnection.py | 1,364 | Add a table entry to the switch
Remove a table entry from the switch | 68 | en | 0.466569 |
from torch import jit
from syft.execution.placeholder import PlaceHolder
from syft.execution.translation.abstract import AbstractPlanTranslator
class PlanTranslatorTorchscript(AbstractPlanTranslator):
"""Performs translation from 'list of ops' Plan into torchscript Plan"""
def __init__(self, plan):
s... | syft/execution/translation/torchscript.py | 2,056 | Performs translation from 'list of ops' Plan into torchscript Plan
jit.trace clones input args and can change their type, so we have to skip types check TODO see if type check can be made less strict, e.g. tensor/custom tensor/nn.Parameter could be considered same type To avoid storing Plan state tensors in torchscr... | 476 | en | 0.881727 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tornado.gen
import bcrypt
__all__ = ["create_new_user"]
@tornado.gen.coroutine
def get_next_id(db, collection):
counter = yield db.counters.find_and_modify(
{"_id": "{}id".format(collection)},
{"$inc": {"seq": 1}},
new=True,
)
... | trebol/interface.py | 640 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import sys
import numpy as np
import pandas as pd
def run(args):
data = pd.read_csv(sys.stdin)
# Find maximum rank value and increase by one to use as a fill_value
# on the pivot with cluster by day
# notfound_value = grouped['rank'].max()... | scripts/pivot_cluster_day.py | 1,122 | !/usr/bin/env python -*- coding: utf-8 -*- Find maximum rank value and increase by one to use as a fill_value on the pivot with cluster by day notfound_value = grouped['rank'].max()+1 create pivot table and fill non existing with high number i.e:200 Write output Parse command-line arguments. | 292 | en | 0.679139 |
import sys
import random
from collections import deque
def printGrid(grid, wallChar, emptyChar):
finalstr = ""
finalstr += "\n"
for i in range(len(grid[0])):
for j in range(len(grid)):
if grid[j][i]==1:
finalstr += wallChar
else:
finalstr += e... | cellularcaves.py | 4,658 | reminder to test with: for index, value in enumerate(grid) test with list comprehension instead??find a random empty space, hope it's the biggest caveif we're not out of boundsif it's an empty spacemark visitedchance = 100 - int(input("Enter the percentage chance of randomly generating a wall: "))count = int(input("Ent... | 541 | en | 0.750347 |
## ********Day 55 Start**********
## Advanced Python Decorator Functions
class User:
def __init__(self, name):
self.name = name
self.is_logged_in = False
def is_authenticated_decorator(function):
def wrapper(*args, **kwargs):
if args[0].is_logged_in == True:
function(args[... | Day_55/sandbox.py | 532 | ********Day 55 Start********** Advanced Python Decorator Functions | 66 | en | 0.480668 |
#!/usr/bin/env python
import io
import sys
from datetime import datetime
# To make sure all packet types are available
import scapy.all # noqa
import scapy.packet
from scapy.layers.l2 import Ether
import pcapng
from pcapng.blocks import EnhancedPacket, InterfaceDescription, SectionHeader
def col256(text, fg=None,... | examples/dump_pcapng_info_pretty.py | 7,368 | !/usr/bin/env python To make sure all packet types are available noqa Assume it is already a color col256('endianness:', bold=True), col256('NIC:', bold=True), col256(str(block.interface_id), fg='145'), col256('Size:', bold=True), print(repr(block.packet_data)) print(col256(repr(Ether(block.packet_data)), fg='255')) pr... | 597 | en | 0.375558 |
# -*- coding: utf-8 -*-
# Copyright 2013-2021 CERN
#
# 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 a... | lib/rucio/core/replica.py | 171,357 | Bulk add new dids.
:param dids: the list of files.
:param account: The account owner.
:param session: The database session in use.
:returns: True is successful.
Bulk add new dids.
:param dids: the list of new files.
:param account: The account owner.
:param session: The database session in use.
:returns: True is succ... | 25,928 | en | 0.768203 |
import numpy as np
import pytest
from sklearn.datasets import make_classification, make_regression
# To use this experimental feature, we need to explicitly ask for it:
from sklearn.experimental import enable_hist_gradient_boosting # noqa
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.ensembl... | lib/python3.6/site-packages/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py | 5,922 | To use this experimental feature, we need to explicitly ask for it: noqa use scorer use scorer on train data same with default scorer use loss use loss on training data no early stopping just for coverage easier to overfit fast use scorer use scorer on training data same with default scorerscor use loss use loss on tra... | 632 | en | 0.864333 |
# coding: utf-8
"""
Control-M Services
Provides access to BMC Control-M Services # noqa: E501
OpenAPI spec version: 9.20.220
Contact: customer_support@bmc.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class ErrorList(... | controlm_py/models/error_list.py | 3,051 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
ErrorList - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the errors of this ErrorList. # noqa: E501
:return: The err... | 841 | en | 0.635102 |
# Rainbow 2, by Al Sweigart al@inventwithpython.com
# Shows a simple squiggle rainbow animation.
import time, random, sys
try:
import bext
except ImportError:
print("""This program requires the bext module, which you can install by
opening a Terminal window (on macOS & Linux) and running:
python3 -m pip ... | src/gamesbyexample/rainbow2.py | 1,121 | Rainbow 2, by Al Sweigart al@inventwithpython.com Shows a simple squiggle rainbow animation. How many spaces to indent. Increase the number of spaces: Decrease the number of spaces: Add a slight pause. | 201 | en | 0.69054 |
'''
Defines the link functions to be used with GLM and GEE families.
'''
import numpy as np
import scipy.stats
FLOAT_EPS = np.finfo(float).eps
class Link(object):
"""
A generic link function for one-parameter exponential family.
`Link` does nothing, but lays out the methods expected of any subclass.
... | statsmodels/genmod/families/links.py | 26,362 | The use the CDF of a scipy.stats distribution
CDFLink is a subclass of logit in order to use its _clean method
for the link and its derivative.
Parameters
----------
dbn : scipy.stats distribution
Default is dbn=scipy.stats.norm
Notes
-----
The CDF link is untested.
The complementary log-log transform
CLogLog i... | 13,904 | en | 0.462085 |
# qubit number=2
# total number=8
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as... | data/p2DJ/New/program/qiskit/class/startQiskit_Class137.py | 3,080 | qubit number=2 total number=8 implement the oracle O_f^\pm NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate or multi_control_Z_gate (issue 127) oracle.barrier() oracle.draw('mpl', filename='circuit/deutsch-oracle.png') circuit begin inverse last one (can be omitted if using O_f^\pm) apply H to get superpositio... | 538 | en | 0.416839 |
# Created by SylvanasSun in 2017.10.17
# !/usr/bin/python
# -*- coding: utf-8 -*-
import collections
import jieba
from jieba import analyse
# TODO: Change default hash algorithms to the other algorithms of high-performance.
def _default_hashfunc(content, hashbits):
"""
Default hash function is variable-lengt... | algorithms/hash/simhash.py | 7,893 | Class Simhash implements simhash algorithms of the Google for filter duplicate content.
Simhash algorithms idea is will reduce the dimension of content and compares the
difference of the "Hamming Distance" implements filter duplicate content.
About simhash algorithms the more introduction: https://en.wikipedia.org/wiki... | 2,590 | en | 0.706733 |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | luigi/contrib/scalding.py | 10,702 | JobRunner for `pyscald` commands. Used to run a ScaldingJobTask.
A job task for Scalding that define a scala source and (optional) main method.
requires() should return a dictionary where the keys are Scalding argument
names and values are sub tasks or lists of subtasks.
For example:
.. code-block:: python
{'in... | 1,825 | en | 0.778817 |
"""
file system and database initialization.
tables:
- polls:
- id PRIMARY KEY
- owner_id => users.id
- topic
- users:
- id PRIMARY KEY
- first_name
- last_name
- username
- answers:
- id PRIMARY KEY
- poll_id => polls.id
- text
- votes:
- user_id => users.id
- poll_id => polls.id
- answer... | src/app/fs.py | 1,101 | apply yoyo migrations
file system and database initialization.
tables:
- polls:
- id PRIMARY KEY
- owner_id => users.id
- topic
- users:
- id PRIMARY KEY
- first_name
- last_name
- username
- answers:
- id PRIMARY KEY
- poll_id => polls.id
- text
- votes:
- user_id => users.id
- poll_id => ... | 385 | en | 0.553792 |
# -*- coding: UTF-8 -*-
import os # File and path handling
import numpy
import copy # for deepcopy
import math
from .image import ImageFile, Image, ImageROI, ImageStack
from .geometry import Geometry
from .processing.pipeline import Pipeline
from .processing.step import Step
from .helpers import *
d... | ctsimu/test.py | 2,197 | General class for test scenario evaluations: get image(s), run and store evaluation.
Plot results of evaluation.
Set an individual name for the (sub) test.
Save intermediate projections as RAW instead of TIFF?
Set the location where test results should be saved.
-*- coding: UTF-8 -*- File and path handling for d... | 429 | en | 0.908531 |
"""
Custom dataset processing/generation functions should be added to this file
"""
import pathlib
from sklearn.datasets import fetch_20newsgroups
from functools import partial
from src import workflow, paths
from src.log import logger
import src.log.debug
from tqdm.auto import tqdm
from .. import paths
from ..log ... | src/data/process_functions.py | 1,500 | Process 20 newsgroups into (data, target, metadata) format.
Parameters
----------
unpack_dir: path
The interim parent directory the dataset files have been unpacked into.
extract_dir: str
Name of the directory of the unpacked files relative to the unpack_dir. Note that
opts: dict default {"subset":"all", "rem... | 563 | en | 0.437662 |
#!/usr/bin/python
# Copyright (c) 2017, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... | plugins/modules/oci_vault_secret_actions.py | 15,464 | Supported actions:
cancel_secret_deletion
schedule_secret_deletion
!/usr/bin/python Copyright (c) 2017, 2021 Oracle and/or its affiliates. This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. GNU General Public License v3.0+ (see COPYING or https://www.gnu.or... | 458 | en | 0.727582 |
import os
import sys
import json
from .version import __version__
from satsearch import Search
from satstac import Items
from satsearch.parser import SatUtilsParser
import satsearch.config as config
def main(items=None, printmd=None, printcal=False, found=False,
save=None, download=None, requestor_pays=Fals... | satsearch/main.py | 1,911 | Main function for performing a search
if there are no items then perform a search otherwise, load a search from a file print metadata print calendar save all metadata in JSON file download files given `download` keys get complete set of assets if a filename, read the GeoJSON file | 283 | en | 0.670781 |
from argparse import ArgumentParser
import datetime
import dateutil
import sys, re
from os import path
def parseArgs():
parser = ArgumentParser(add_help=False)
parser.add_argument("-a", "--action", help="Please select an option out of <discover, manage, settings>", type=str, required=True)
parser.add_argum... | stages/utils/utils.py | 5,686 | for debugging TODO: remove later Remove URLs Remove Multi-Whitespaces Not-Empty-Constraints Unify Date format - reformat to %Y-%m-%d %H:%M:%S clean signatures, clauses Find lowest greetings or end clause index and strip off everything that comes after it needle and haystack both in lowercase to ignore case Find lowest ... | 515 | en | 0.731304 |
#!/usr/bin/env python3.8
import importlib
import typing
from enum import Enum
import discord
from discord.ext import commands
from discord.types.interactions import ApplicationCommandOption
import common.paginator as paginator
import common.star_classes as star_classes
import common.utils as utils
class OwnerCMDs(c... | cogs/core/cmds/owner_cmds.py | 4,805 | !/usr/bin/env python3.8 type: ignore | 36 | en | 0.188428 |
# Copyright (c) 2015-2016, 2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Ceridwen <ceridwenv@gmail.com>
# Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid... | venv/Lib/site-packages/astroid/brain/brain_nose.py | 2,282 | Get an iterator of names and bound methods.
Custom transform for the nose.tools module.
Hooks for nose library.
Copyright (c) 2015-2016, 2018, 2020 Claudiu Popa <pcmanticore@gmail.com> Copyright (c) 2016 Ceridwen <ceridwenv@gmail.com> Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com> Licensed under the LGPL: h... | 562 | en | 0.70018 |
# Lint as: python3
# Copyright 2020 The DMLab2D Authors.
#
# 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 ... | dmlab2d/settings_helper.py | 2,207 | Helper function for flatten_args. See `flatten_args` below for details.
Converts a dictionary of dictionarys and lists into a flat table.
Args:
args_in: dictionary containing a hierachy of dictionaries and lists. Leaf
values can be strings, bools, numbers..
Returns:
A flat dictionary with keys separated by '.... | 963 | en | 0.784729 |
import os
import numpy as np
import scipy.sparse as sp
import pickle
import torch
from torch.utils.data import DataLoader
from dgl.data.utils import download, _get_dgl_url, get_download_dir, extract_archive
import random
import time
import dgl
def ReadTxtNet(file_path="", undirected=True):
""" Read the txt network... | examples/pytorch/ogb/line/reading_data.py | 7,107 | Read the txt network file.
Notations: The network is unweighted.
Parameters
----------
file_path str : path of network file
undirected bool : whether the edges are undirected
Return
------
net dict : a dict recording the connections in the graph
node2id dict : a dict mapping the nodes to their embedding indices
id2... | 1,229 | en | 0.673955 |
"""Tests for the DirecTV component."""
from http import HTTPStatus
from homeassistant.components.directv.const import CONF_RECEIVER_ID, DOMAIN
from homeassistant.components.ssdp import ATTR_SSDP_LOCATION
from homeassistant.const import CONF_HOST, CONTENT_TYPE_JSON
from homeassistant.core import HomeAssistant
from tes... | tests/components/directv/__init__.py | 3,982 | Mock the DirecTV connection for Home Assistant.
Tests for the DirecTV component. | 80 | en | 0.707659 |
from random import shuffle
from models.RainbowModelLeaveRecsOut import RainbowModelLeaveRecsOut
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout # type: ignore
from tensorflow.keras.models import Sequential # type: ignore
import numpy as np
from utils.Recording import Recording
from ... | archive/model_archive/ConvModel.py | 2,032 | Convolutional model
:param kwargs:
window_size: int
stride_size: int
test_percentage: float
n_features: int
n_outputs: int
type: ignore type: ignore hyper params to instance vars create model window_size, n_features, n_outputs = X.shape[1], X.shape[2], y.shape[1] | 285 | en | 0.513144 |
import json
from django.contrib.messages.storage.base import BaseStorage
from django.contrib.messages.storage.cookie import (
MessageDecoder, MessageEncoder,
)
from django.utils import six
class SessionStorage(BaseStorage):
"""
Stores messages in the session (that is, django.contrib.sessions).
"""
... | django/contrib/messages/storage/session.py | 1,714 | Stores messages in the session (that is, django.contrib.sessions).
Retrieves a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
Stores a list of messages to the request's session. | 270 | en | 0.712072 |
from django.contrib import admin
# Register your models here.
from account.models import UserProfile
from blog.models import BlogArticles
class BlogArticlesAdmin(admin.ModelAdmin):
list_display = ("title", "author", "publish")
list_filter = ("publish", "author")
search_fields = ("title", "body")
raw_... | blog/admin.py | 640 | Register your models here. | 26 | en | 0.957485 |
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.constants import pi
__all__ = [
# functional api
"rad2deg",
"deg2rad",
"pol2cart",
"cart2pol",
"convert_points_from_homogeneous",
"convert_points_to_homogeneous",
"convert_affinematr... | kornia/geometry/conversions.py | 29,153 | Convert an angle axis to a quaternion.
The quaternion vector has components in (x, y, z, w) format.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
angle_axis (torch.Tensor): tensor with angle axis.
Return:
torch.Tensor: tensor with quaternion.
Shape:
- Input: :math:`(*, 3)` ... | 9,642 | en | 0.569194 |
#!/usr/bin/env python3
# In this example, we demonstrate how Korali samples the posterior distribution
# in a bayesian problem where the likelihood is calculated by providing
# reference data points and their objective values.
# Importing the computational model
import sys
sys.path.append('./_model')
from model impor... | examples/bayesian.inference/reference/run-nested.py | 1,836 | !/usr/bin/env python3 In this example, we demonstrate how Korali samples the posterior distribution in a bayesian problem where the likelihood is calculated by providing reference data points and their objective values. Importing the computational model Creating new experiment Setting up the reference likelihood for th... | 566 | en | 0.782448 |
import os
import cv2
from PIL import Image
import torch
import mmcv
import numpy as np
from torch.utils.data import Dataset
import torchvision.transforms as T
from torchvision.datasets import ImageFolder
class ImageNetDataset(Dataset):
def __init__(self,
data_root,
test_mode=Fa... | mmdet/datasets/classify/imagenet.py | 1,903 | Set flag according to image aspect ratio.
Images with aspect ratio greater than 1 will be set as group 1,
otherwise group 0.
normalize = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) | 205 | en | 0.79646 |
# Copyright 2018 The TensorFlow Probability Authors.
#
# 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 o... | tensorflow_probability/python/distributions/zipf_test.py | 15,329 | Copyright 2018 The TensorFlow Probability Authors. 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 wri... | 1,205 | en | 0.797023 |
"""Implements interface for OSv unikernels."""
from backend.vm import VMConfig
from os import path
from .imgedit import set_cmdline
class OSv:
cmdline_template = "--ip=eth0,{ipv4_addr},255.255.255.0 --nameserver=10.0.125.0 {extra_cmdline}"
@staticmethod
def configure(image, config, nic_name):
c... | backend/unikernel/osv/__init__.py | 827 | Implements interface for OSv unikernels. | 40 | en | 0.667147 |
# coding=utf-8
# Copyright 2019 The Tensor2Robot Authors.
#
# 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 ... | utils/train_eval_test.py | 14,062 | Summation of the categorical hinge loss for labels and logits.
Tests that a simple model trains and exported models are valid.
Tests that a simple model trains and exported models are valid.
Tests that a simple model trains and exported models are valid.
Tests for tensor2robot.train_eval.
coding=utf-8 Copyright 2019 ... | 3,335 | en | 0.913462 |
"""Support for Agent camera streaming."""
from datetime import timedelta
import logging
from agent import AgentError
from homeassistant.components.camera import SUPPORT_ON_OFF
from homeassistant.components.mjpeg.camera import (
CONF_MJPEG_URL,
CONF_STILL_IMAGE_URL,
MjpegCamera,
filter_urllib3_logging,... | homeassistant/components/agent_dvr/camera.py | 6,497 | Representation of an Agent Device Stream.
Initialize as a subclass of MjpegCamera.
Return True if entity is available.
Return True if entity is connected.
Return the device info for adding the entity to the agent object.
Return the Agent DVR camera state attributes.
Return the icon to use in the frontend, if any.
Retur... | 681 | en | 0.694886 |
# -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# 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/l... | src/unittest/python/plugins/python/test_plugin_helper_tests.py | 3,270 | -*- coding: utf-8 -*- This file is part of PyBuilder Copyright 2011-2015 PyBuilder Team 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 Un... | 631 | en | 0.87201 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | sdk/python/pulumi_azure_native/synapse/v20200401preview/sql_pools_v3.py | 13,465 | The set of arguments for constructing a SqlPoolsV3 resource.
:param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive.
:param pulumi.Input[str] workspace_name: The name of the workspace.
:param pulumi.Input[str] location: The geo-location where the resource lives
:param... | 2,663 | en | 0.631135 |
import cv2
from PIL import ImageGrab
import numpy as np
def main():
while True:
# bbox specifies specific region (bbox= x,y,width,height)
img = ImageGrab.grab(bbox=(0, 40, 1075, 640))
vanilla = img_np = np.array(img)
img_np = np.array(img)
gray = cv2.cvtColor(img_np, cv2.CO... | main.py | 857 | bbox specifies specific region (bbox= x,y,width,height) cv2.waitKey(0) | 70 | en | 0.329442 |
from timetableparser import TimeTableParser
from timetablewriter import TimeTableWriter
parser = TimeTableParser(False)
writer = TimeTableWriter(True)
# parser.decrypt_pdf("test/a.pdf", "out_a.pdf")
# parser.decrypt_pdf("test/b.pdf", "out_b.pdf")
csv_file_a = "test/output_week_a.csv"
csv_file_b = "test/output_week_b.c... | Pdf2TimeTable/test.py | 589 | parser.decrypt_pdf("test/a.pdf", "out_a.pdf") parser.decrypt_pdf("test/b.pdf", "out_b.pdf") parser.extract_table_from_pdf("out_a.pdf", csv_file_a) parser.extract_table_from_pdf("out_b.pdf", csv_file_b) | 201 | de | 0.109817 |
# -*-coding:Utf-8 -*
# Copyright (c) 2014 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | src/secondaires/navigation/equipage/objectifs/rejoindre.py | 11,757 | Objectif rejoindre.
Cet objectif demande à un équipage de rejoindre un point précisé
en coordonnées. Le point indiqué doit être statique (il existe un
objectif particulier pour les points mobiles, comme les navires, qui
intègrent leur propre calcul).
Cet objectif est responsable de trouver un chemin entre le point
ac... | 3,866 | fr | 0.849197 |
"""
724. Minimum Partition
https://www.lintcode.com/problem/minimum-partition/description
01背包
算法班2020 C27 01背包变形
第1种dp定义
dp[i][j]: considering previous i items to fill <=j, what the maximum value
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - nums[i - 1]] + nums[i - 1])
dp[0][0] = 0
dp[i][0] = 0
answer
max(dp[n])
2d... | lintcode/724.1.py | 1,962 | @param nums: the given array
@return: the minimum difference between their sums
724. Minimum Partition
https://www.lintcode.com/problem/minimum-partition/description
01背包
算法班2020 C27 01背包变形
第1种dp定义
dp[i][j]: considering previous i items to fill <=j, what the maximum value
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - ... | 447 | en | 0.524982 |
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from django import forms
from taggit.forms import TagField
from dcim.models import Device
from extras.forms import (
AddRemoveTagsForm, CustomFieldBulkEditForm, CustomFieldFilterForm, CustomFieldModelForm, CustomFieldModelCSVForm,
)
from utiliti... | netbox/secrets/forms.py | 6,592 | Validate the format and type of an RSA key.
Secret roles Secrets A plaintext value is required when creating a new Secret Verify that the provided plaintext values match UserKeys Validate the RSA key format. | 209 | en | 0.528187 |
import tensorflow as tf
import numpy as np
def _tf_fspecial_gauss(size, sigma, ch=1):
"""Function to mimic the 'fspecial' gaussian MATLAB function
"""
x_data, y_data = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]
x_data = np.expand_dims(x_data, axis=-1)
x_data = np.expand_dims(x_d... | ssim.py | 2,989 | Function to mimic the 'fspecial' gaussian MATLAB function
window shape [size, size] depth of image (255 in case the image has a differnt scale) list to tensor of dim D+1 | 176 | en | 0.782164 |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above... | base-image/rosbridge/rosbridge_library/src/rosbridge_library/rosbridge_protocol.py | 2,940 | Adds the handlers for the rosbridge opcodes
Software License Agreement (BSD License) Copyright (c) 2012, Willow Garage, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source... | 1,652 | en | 0.874466 |
from __future__ import print_function
import sys
import os
import getopt
import re
import string
import errno
import six
from jsbeautifier.__version__ import __version__
#
# The MIT License (MIT)
# Copyright (c) 2007-2013 Einar Lielmanis and contributors.
# Permission is hereby granted, free of charge, to any person... | python/jsbeautifier/__init__.py | 68,865 | The MIT License (MIT) Copyright (c) 2007-2013 Einar Lielmanis and contributors. 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 restriction, including without limitation the rights to use, ... | 7,453 | en | 0.805807 |
'''Module to manage and advanced game state'''
from collections import defaultdict
import numpy as np
from . import constants
from . import characters
from . import utility
class ForwardModel(object):
"""Class for helping with the [forward] modeling of the game state."""
def run(self,
num_times... | pommerman/forward_model.py | 29,143 | Class for helping with the [forward] modeling of the game state.
Returns actions for each agent in this list.
Args:
agents: A list of agent objects.
obs: A list of matching observations per agent.
action_space: The action space for the environment using this model.
is_communicative: Whether the action depends ... | 6,254 | en | 0.940042 |
import copy
import datetime
import glob
import json
import os
import sys
import threading
from os import path
from urllib.parse import urlparse, urljoin, ParseResult
import xmltodict
import yaml
from bs4 import BeautifulSoup
from flask import Flask, render_template, Response, send_from_directory, request
from flask.vi... | kotlin-website.py | 17,589 | Handle requests which urls don't end with '.html' (for example, '/doc/')
We don't need any generator here, because such urls are equivalent to the same urls
with 'index.html' at the end.
:param page_path: str
:return: str
NOTE. This call depends on `request.path`, cannot cache get_nav() has side effect to copy and ... | 526 | en | 0.88326 |
# -*- coding: utf-8 -*-
class TestInvalidPathTweenFactory:
def test_it_400s_if_the_requested_path_isnt_utf8(self, app):
app.get("/%c5", status=400)
| tests/functional/test_tweens.py | 162 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
"""
Simple million word count program.
main idea is Python pairs words
with the number of times
that number appears in the triple quoted string.
Credit to William J. Turkel and Adam Crymble for the word
frequency code used below. I just merged the two ideas.
"""
wordstring = '''SCENE I. Yorkshire. Gaultree Forest.
Ent... | CountMillionCharacter.py | 10,991 | Simple million word count program.
main idea is Python pairs words
with the number of times
that number appears in the triple quoted string.
Credit to William J. Turkel and Adam Crymble for the word
frequency code used below. I just merged the two ideas. | 254 | en | 0.891765 |
""" YQL out mkt cap and currency to fill out yahoo table """
""" TODO: retreive lists of 100 symbols from database and update"""
""" Results are intented to use while matching yahoo tickers, which one has mkt cap? which ones has sector? """
import mysql.connector
import stockretriever
import sys
import time
from rand... | script/StockScraper-master/update_market_cap_yahoo.py | 2,002 | print "Typerror {0}: {1}".format(e.errno, e.strerror) | 53 | en | 0.081891 |
# Copyright (c) 2014 eBay Software Foundation
# Copyright 2015 HP Software, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.o... | trove_dashboard/content/database_clusters/panel.py | 1,044 | Copyright (c) 2014 eBay Software Foundation Copyright 2015 HP Software, LLC All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENS... | 646 | en | 0.861553 |
# Generated by Django 2.2.1 on 2019-07-06 21:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publish', '0031_bundle_description'),
]
operations = [
migrations.CreateModel(
name='Docset',
fields=[
... | sfdoc/publish/migrations/0032_docset.py | 591 | Generated by Django 2.2.1 on 2019-07-06 21:53 | 45 | en | 0.529291 |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram 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 S... | ENV/lib/python3.5/site-packages/pyrogram/api/types/channel_admin_log_event_action_toggle_pre_history_hidden.py | 1,574 | Attributes:
ID: ``0x5f5c95f1``
Args:
new_value: ``bool``
Pyrogram - Telegram MTProto API Client Library for Python Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance> This file is part of Pyrogram. Pyrogram is free software: you can redistribute it and/or modify it under the terms of the GNU Less... | 862 | en | 0.851332 |
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
import numpy as np
def mean_precision_k(y_true, y_score, k=10):
"""Mean ... | voc_classifier/metrics_for_multilabel.py | 10,465 | Average precision at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
Rank.
Returns
-------
average precision @k : float
Discounted cumulative gain (DCG) at rank k
Parameters
------... | 3,955 | en | 0.500208 |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | python/paddle/fluid/tests/unittests/dygraph_to_static/test_ptb_lm.py | 11,862 | Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agree... | 583 | en | 0.863545 |
# Generated by Django 3.2.9 on 2022-01-03 10:15
import cloudinary.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('neighbourhood', '0003_auto_20211222_2324'),
]
operations = [
migrations.CreateMode... | neighbourhood/migrations/0004_auto_20220103_1315.py | 1,708 | Generated by Django 3.2.9 on 2022-01-03 10:15 | 45 | en | 0.730283 |
import deepSI
from deepSI.systems.system import System_ss, System_data
import numpy as np
class NarendraLiBenchmark(System_ss): #https://arxiv.org/pdf/2003.14162.pdf
"""docstring for NarendraLiBenchmark"""
def __init__(self):
'''Noise, system setting and x0 settings'''
super(NarendraLiBenchmark... | deepSI/systems/narendra_li_benchmark.py | 1,494 | docstring for NarendraLiBenchmark
Noise, system setting and x0 settings
https://arxiv.org/pdf/2003.14162.pdf sys_fit, score, kwargs = fit_systems.fit_system_tuner(SYS, sys_data, dict(na=range(0,7),nb=range(1,7))) | 213 | en | 0.397673 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to implement an AWS Lambda function that publishes messages to an
AWS IoT Greengrass connector.
"""
# snippet-start:[greengrass.python.connector-modbus-rtu-usage.complete]
import json
impo... | python/example_code/greengrass/snippets/connector_modbus_rtu_usage.py | 989 | Purpose
Shows how to implement an AWS Lambda function that publishes messages to an
AWS IoT Greengrass connector.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 snippet-start:[greengrass.python.connector-modbus-rtu-usage.complete] In this example, the required ... | 423 | en | 0.646866 |
#!/usr/bin/env python
# file trying to apply and test the pid controller on carla.
import glob
import os
import sys
import time
import matplotlib.pyplot as plt
from PID_controller import PID
import numpy as np
import speed_profile_reader as spr
try:
sys.path.append(glob.glob('../**/*%d.%d-%s.egg' % (
sys.... | PythonAPI/carissma_project/PID_apply_static_sp.py | 6,114 | !/usr/bin/env python file trying to apply and test the pid controller on carla. For 10 m/s "Kp": 0.055734, "Ki": 0.0130169, "Kd": .000006 "Kp": 1, "Ki": 0.0112, "Kd": 0.000006 raise SystemExit | 192 | en | 0.565658 |
{% if cookiecutter.use_celery == 'y' %}
from __future__ import absolute_import
import os
from celery import Celery
from django.apps import AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SET... | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/taskapp/celery.py | 2,410 | set the default Django settings module for the 'celery' program. pragma: no cover Using a string here means the worker will not have to pickle the object when using Windows. Celery signal registration pragma: no cover Use this as a starting point for your project with celery. If you are not using celery, you can remove... | 329 | en | 0.818092 |
import logging
import os
from typing import Generator
import pytest
@pytest.fixture(scope="module", autouse=True)
def change_to_resources_dir(test_resources, request):
os.chdir(test_resources)
yield
os.chdir(request.config.invocation_dir)
@pytest.fixture()
def test_filename(
change_to_resources_dir... | tests/accsr/test_remote_storage.py | 7,258 | Pushes files and dirs with colliding names to remote storage, yields files pushed
and deletes everything at cleanup
Pushes a directory to remote storage, yields its name and then deletes it from remote storage
Pushes a file to remote storage, yields its filename and then deletes it from remote storage
we need lstrip ... | 490 | en | 0.905044 |
"""Performs face alignment and stores face thumbnails in the output directory."""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# 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 witho... | facenet/align/align_dataset_mtcnn.py | 8,302 | Performs face alignment and stores face thumbnails in the output directory.
MIT License Copyright (c) 2016 David Sandberg 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 restriction, in... | 1,383 | en | 0.852149 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'MessageContact'
db.create_table('umessages_messagecontact', (
('id', self.gf('... | userena/contrib/umessages/migrations/0001_initial.py | 8,080 | encoding: utf-8 Adding model 'MessageContact' Adding unique constraint on 'MessageContact', fields ['from_user', 'to_user'] Adding model 'MessageRecipient' Adding model 'Message' Removing unique constraint on 'MessageContact', fields ['from_user', 'to_user'] Deleting model 'MessageContact' Deleting model 'MessageRecipi... | 349 | en | 0.408663 |
#!/bin/env python
import csv
from datetime import datetime
import os
import xml.etree.ElementTree as ET
import xml
# https://stackabuse.com/reading-and-writing-xml-files-in-python/
# xmlformatter:
# https://www.freeformatter.com/xml-formatter.html#ad-output
infile = "./RAJAPerf-timing.csv"
def read_infile(infile)... | scripts/csv_xml.py | 4,448 | STUB -- xml_element will be an element of perf_report;
timing_dict = a map of variant names to test run times
STUB - suite_name is a string = Basic, KokkosMechanics, etc.;
suite_data_list will be the values for a key, Basic or KokkosMechanics
STUB
STUB
STUB
!/bin/env python https://stackabuse.com/reading-and-writing-x... | 1,473 | en | 0.463663 |
#!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2016 The Electrum developers
#
# 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... | qtum_electrum/plugins/hw_wallet/qt.py | 8,946 | An interface between the GUI (here, QT) and the device handling
logic for handling I/O.
This dialog box should be usable even if the user has
forgotten their PIN or it is in bootloader mode.
!/usr/bin/env python2 -*- mode: python -*- Electrum - lightweight Bitcoin client Copyright (C) 2016 The Electrum developers Per... | 1,610 | en | 0.886344 |
"""Python Crypto Bot consuming Coinbase Pro or Binance APIs"""
import functools
import os
import sched
import sys
import time
import pandas as pd
from datetime import datetime
from models.PyCryptoBot import PyCryptoBot, truncate as _truncate
from models.AppState import AppState
from models.Trading import TechnicalAnal... | pycryptobot.py | 41,319 | Trading bot job which runs at a scheduled interval
Python Crypto Bot consuming Coinbase Pro or Binance APIs
minimal traceback connectivity check (only when running live) poll every 5 minute increment state.iterations retrieve the app.getMarket() data analyse the market data data frame should have 250 rows, if not ret... | 2,050 | en | 0.798867 |
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Tomoki Hayashi (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Automatic speech recognition model training script."""
import logging
import os
import random
import subprocess
import sys
from distutils.version import LooseVe... | espnet/bin/asr_train.py | 20,058 | Get default arguments.
Run the main training function.
Automatic speech recognition model training script.
!/usr/bin/env python3 encoding: utf-8 Copyright 2017 Tomoki Hayashi (Nagoya University) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) NOTE: you need this func to generate our sphinx doc general config... | 929 | en | 0.55731 |
#(c) 2016 by Authors
#This file is a part of ABruijn program.
#Released under the BSD license (see LICENSE file)
"""
Runs repeat/contigger binary
"""
from __future__ import absolute_import
import subprocess
import logging
import os
from flye.utils.utils import which
REPEAT_BIN = "flye-modules"
CONTIGGER_BIN = "flye... | flye/assembly/repeat_graph.py | 3,285 | Runs repeat/contigger binary
(c) 2016 by AuthorsThis file is a part of ABruijn program.Released under the BSD license (see LICENSE file)if args.kmer_size: cmdline.extend(["--kmer", str(args.kmer_size)])if args.kmer_size: cmdline.extend(["--kmer", str(args.kmer_size)]) | 275 | en | 0.712033 |
import json
import typing
import collections
from matplotlib import cm
from matplotlib.colors import Normalize, to_hex, CSS4_COLORS, BASE_COLORS
import matplotlib.pyplot as plt
from clldutils.color import qualitative_colors, sequential_colors, rgb_as_hex
from cldfviz.multiparameter import CONTINUOUS, CATEGORICAL, Par... | src/cldfviz/colormap.py | 3,386 | Wrap clldutils.color.rgb_as_hex to provide unified error handling.
reorder the domain of the parameter (and prune it to valid values): Initialize matplotlib colormap and normalizer: | 183 | en | 0.296911 |
import torch
class KFold:
def __init__(self, dataset, n_fold=10, batch_size=32, num_workers=0, pin_memory=False):
self.fold = 0
self.batch_size = batch_size
self.num_workers = num_workers
self.pin_memory = pin_memory
self.dataset = dataset
self.n_fold = n_fold
... | pymatch/utils/KFold.py | 2,558 | Loading a specific fold as train and test data loader. If no fold number is provided it returns the next fold. It returns a randomly sampled subset of
the original data set.
Args:
fold: fold number to return
Returns:
(train data loader, test data loader)
Splitting the folds.
Args:
random_seed: Random see... | 509 | en | 0.745565 |
# -*- coding: utf-8 -*- #
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | whoami.py | 970 | -*- coding: utf-8 -*- Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http:www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing... | 568 | en | 0.867166 |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nemo/package_info.py | 1,402 | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agree... | 648 | en | 0.886921 |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | py/test/selenium/webdriver/common/page_load_timeout_tests.py | 1,649 | Licensed to the Software Freedom Conservancy (SFC) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The SFC licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this fi... | 754 | en | 0.875826 |
from bs4 import BeautifulSoup
from django.forms import (
BaseForm,
BaseFormSet,
BoundField,
CheckboxInput,
CheckboxSelectMultiple,
DateInput,
EmailInput,
FileInput,
MultiWidget,
NumberInput,
PasswordInput,
RadioSelect,
Select,
SelectDateWidget,
TextInput,
... | env/lib/python3.8/site-packages/bootstrap4/renderers.py | 21,882 | A content renderer.
Default field renderer.
Default form renderer.
Default formset renderer.
Inline field renderer.
If Django is set up without a database, importing this widget gives RuntimeError These widgets will not be wrapped in a form-control class Find the placeholder in kwargs, even if it's empty If not found... | 1,278 | en | 0.788749 |
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
from tqdm import tqdm
class RBM(object):
def __init__(self,num_visible,num_hidden,visible_unit_type='bin',main_dir='/Users/chamalgomes/Documents/Python/GitLab/DeepLearning/KAI PROJECT/rbm/models',
model_na... | Unsupervised-Learning/rbm.py | 19,123 | "
INPUT PARAMETER 1) num_visible: number of visible units in the RBM
INPUT PARAMETER 2) num_hidden: number of hidden units in the RBM
INPUT PARAMETER 3) main_dir: main directory to put the models, data and summary directories
INPUT PARAMETER 4) model_name: name of the model you wanna save the data
INPUT PARAMETER 5) ... | 6,397 | en | 0.584818 |
from data_processing_calibration import DataProcessingCalibration
if __name__ == "__main__":
# Start processing
dp_ST = DataProcessingCalibration()
print("Initialize is successful.")
# Open .csv file with data
data_from_sensor = dp_ST.openFile('C://static_test.csv')
print("Data was ... | static_test/main.py | 887 | Start processing Open .csv file with data Filter and processing, and convert data in Euler angles Use method of Allan Variation for data Create plots | 149 | en | 0.743079 |
"""
Support for Smappee energy monitor.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/smappee/
"""
import logging
from datetime import datetime, timedelta
import re
import voluptuous as vol
from requests.exceptions import RequestException
from homeassi... | homeassistant/components/smappee.py | 12,733 | Stores data retrieved from Smappee sensor.
Initialize the data.
Get the average of all instantaneous cosfi values.
Get current active Amps.
Get sum of all instantaneous active power values from local hub.
Get current active Voltage.
Turn off actuator.
Turn on actuator.
Update data from Smappee.
Update data from Smappee... | 1,678 | en | 0.817099 |
import os
import math
from decimal import Decimal
import utility
import torch
import torch.nn.utils as utils
from tqdm import tqdm
class Trainer():
def __init__(self, args, loader, my_model, my_loss, ckp):
self.args = args
self.scale = args.scale
self.ckp = ckp
self.loader_train ... | src/trainer.py | 6,548 | To avoid "UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`." The 0 gradient value will not update any parameter of the model to train. TEMP return epoch >= self.args.epochs | 201 | en | 0.389717 |
#
# PySNMP MIB module NOKIA-HWM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-HWM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:23:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | pysnmp-with-texts/NOKIA-HWM-MIB.py | 14,112 | PySNMP MIB module NOKIA-HWM-MIB (http://snmplabs.com/pysmi) ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-HWM-MIB Produced by pysmi-0.3.4 at Wed May 1 14:23:29 2019 On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) | 320 | en | 0.402725 |
class NoNodeData(Exception):
pass
class AVLNode(object):
def __init__(self, key=None, value=None) -> None:
"""Initializes the AVL Node.
Args:
data (dict, optional): {Key:Value} pair. Defaults to None.
"""
super().__init__()
self.key = key
self.valu... | avltree/AVLNode.py | 1,178 | Initializes the AVL Node.
Args:
data (dict, optional): {Key:Value} pair. Defaults to None.
Prints single AVL Node to stdout
Raises:
NoNodeData: If no data is present in the node
Returns:
str: output string
returns the key of the node
Returns:
str: the key in (key, value) pair
returns the value of th... | 375 | en | 0.432373 |
# -*- coding: utf-8 -*-
from benedict.core import clone as _clone
from benedict.core import traverse as _traverse
import unittest
class traverse_test_case(unittest.TestCase):
def test_traverse(self):
i = {
'a': {
'x': 2,
'y': 3,
'z': {
... | tests/core/test_traverse.py | 1,452 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
from logging import getLogger
from .onnx_model import OnnxModel
from typin... | examples/fastformers/onnx_graph_optimizer/fusion_utils.py | 2,421 | ------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.-------------------------------------------------------------------------- Avoid consequent Cast nodes. | 267 | en | 0.360903 |
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
__all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161']
model_urls = {
'densenet121': 'https://download.pytorch.org/models/densenet... | cvlib/models/densenet.py | 9,993 | Densenet-BC model class, based on
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
Args:
growth_rate (int) - how many filters to add each layer (`k` in paper)
block_config (list of 4 ints) - how many layers in each pooling block
num_init_features (int) - the number of fi... | 2,368 | en | 0.782025 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: storyboard_node.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.prot... | container_sdk/model/next_builder/storyboard_node_pb2.py | 8,372 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: storyboard_node.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:next_builder.StoryboardNode) @@protoc_insertion_point(module_scope) | 247 | en | 0.509459 |
#!/usr/bin/env python3
import asyncio
import logging
from collections import defaultdict
from functools import partial
from box import Box
_l = logging.getLogger(__name__)
_instances = dict()
_events = defaultdict(asyncio.Event)
_event_queues = list()
_event_callbacks = defaultdict(list)
class Component:
"""... | pipekit/component.py | 8,113 | A stateful element in a workflow that can be configured, run, and uniquely named.
Return the msg prefixed with this component's ID and type.
Return `True` if the aborted event was emitted.
Register a callback that will be called upon the given event.
Return a new `Queue` object that will see all events.
Return `True` i... | 553 | en | 0.841527 |
# sqlite/base.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
r"""
.. dialect:: sqlite
:name: SQLite
:full_support: 3.21, 3.28+
:norma... | lib/sqlalchemy/dialects/sqlite/base.py | 87,820 | Represent a Python date object in SQLite using a string.
The default string storage format is::
"%(year)04d-%(month)02d-%(day)02d"
e.g.::
2011-03-15
The storage format can be customized to some degree using the
``storage_format`` and ``regexp`` parameters, such as::
import re
from sqlalchemy.diale... | 37,816 | en | 0.709143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.