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 |
|---|---|---|---|---|---|---|
'''
use case handlers package
'''
from .find_average_temperature_handler import FindAverageTemperatureHandler
__all__ = [
'FindAverageTemperatureHandler'
]
| core/handlers/__init__.py | 161 | use case handlers package | 25 | en | 0.364844 |
#
# Copyright 2019 The FATE 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 appli... | python/fate_flow/tests/check_fate_python_requirement.py | 7,487 | Copyright 2019 The FATE 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 agreed t... | 608 | en | 0.850051 |
import itertools
import logging
import warnings
from abc import abstractmethod
from collections import Counter
from pathlib import Path
from typing import Union, List, Tuple, Dict, Optional
import torch.nn
from torch.utils.data.dataset import Dataset
from tqdm import tqdm
import flair
from flair import file_utils
fro... | flair/nn/model.py | 27,081 | Abstract base class for all Flair models that do classification, both single- and multi-label.
It inherits from flair.nn.Model and adds a unified evaluate() function so that all classification models
use the same evaluation routines and compute the same numbers.
Currently, the SequenceTagger implements this class direc... | 4,969 | en | 0.801567 |
#!/usr/bin/python
import sys
import json
import numpy as np
import cv2
import zmq
import time
from keras.models import Sequential
from keras.layers.core import Dense, Dropout
from keras.optimizers import sgd
from os import listdir
from os.path import isfile, join
#-- Constants
imageSize = (128, 128)
hidden_size=200... | src/modules/bd.py | 2,968 | !/usr/bin/python-- Constants"192.168.14"-- Functions-- Main Functionif (len(sys.argv) > 2): filename = sys.argv[2]else: filename = "model"brain.load(filename)listener.setsockopt(zmq.SUBSCRIBE, b'') Recieveing Data Save recieved data Send responceif (len(sys.argv) > 2): filename = sys.argv[2]else: filename = "model"brai... | 396 | en | 0.247587 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Databa... | sdk/python/pulumi_gcp/sql/database.py | 4,427 | Create a Database resource with the given unique name, props, and options.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] project: The ID of the project in which the resource belongs.
If it is not provided, the provider ... | 1,358 | en | 0.765368 |
"""
Django settings for django_app project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from path... | django_app/settings.py | 3,095 | Django settings for django_app project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
Build paths insi... | 984 | en | 0.691599 |
# -*- coding: utf-8 -*-
SET_SUGGESTIONS = '='
| core/shell/shellSuggestion.py | 47 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Copyright 2017 Google.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | setup.py | 4,347 | Setuptools-based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
Copyright 2017 Google. 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 Licen... | 2,849 | en | 0.814266 |
# This sample verifies that the exception type validation
# handles the case where the exception type is a Type[X] object.
from typing import Type
exc: Type[Exception] = Exception
try:
1 / 0
except exc:
print("exc")
| packages/pyright-internal/src/tests/samples/tryExcept3.py | 240 | This sample verifies that the exception type validation handles the case where the exception type is a Type[X] object. | 118 | en | 0.783309 |
import argparse
import copy
import os
import pickle
import random
import sys
from types import SimpleNamespace
import numpy as np
from domains.npuzzle import NPuzzle, macros
from experiments import search, iw, bfws
def parse_args():
"""Parse input arguments
Use --help to see a pretty description of the argu... | experiments/npuzzle/solve.py | 5,462 | Parse input arguments
Use --help to see a pretty description of the arguments
Instantiate an N-Puzzle and solve with the specified macro-actions and search algorithm
Set up the scramble Define the macros / models Set up the search problem%% Run the search%% Save the results | 277 | en | 0.620819 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import datetime
from frappe.utils import formatdate, fmt_money, flt, cstr, cint, format_datetime, format_time, format_duration
from frappe.model.meta import get_fiel... | frappe/utils/formatters.py | 3,202 | Format value based on given fieldtype, document reference, currency reference.
If docfield info (df) is not given, it will try and guess based on the datatype of the value
Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors MIT License. See license.txt Convert dict to object if necessary this is requir... | 460 | en | 0.725689 |
import FWCore.ParameterSet.Config as cms
from RecoEgamma.PhotonIdentification.isolationCalculator_cfi import *
from RecoEgamma.PhotonIdentification.mipVariable_cfi import *
from RecoEcal.EgammaClusterProducers.hybridSuperClusters_cfi import *
from RecoEcal.EgammaClusterProducers.multi5x5BasicClusters_cfi import *
#
# ... | RecoEgamma/EgammaPhotonProducers/python/photons_cfi.py | 7,990 | producer for photons photonCollection = cms.string(''),candidateP4type = cms.string("fromRegression"), | 104 | en | 0.560688 |
#
# Copyright 2019 The FATE 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 appli... | python/fate_arch/storage/mysql/_table.py | 5,034 | Copyright 2019 The FATE 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 agreed t... | 602 | en | 0.860858 |
import requests
from . import FeedSource, _request_headers
# pylint: disable=no-member
class WorldCoinIndex(FeedSource): # Weighted average from WorldCoinIndex
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.timeout = getattr(self, 'timeout', 15)
if not hasattr... | bitshares_pricefeed/sources/worldcoinindex.py | 1,152 | pylint: disable=no-member Weighted average from WorldCoinIndex | 62 | en | 0.761682 |
# Copyright 2016, VIXL authors
# 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 list of conditions and the ... | tools/known_test_failures.py | 3,308 | Copyright 2016, VIXL authors 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 list of conditions and the following discla... | 1,482 | en | 0.890503 |
from batchgenerators.utilities.file_and_folder_operations import *
import numpy as np
if __name__ == '__main__':
# input_file = '/home/fabian/data/nnUNet_preprocessed/Task004_Hippocampus/nnUNetPlansv2.1_plans_3D.pkl'
# output_file = '/home/fabian/data/nnUNet_preprocessed/Task004_Hippocampus/nnUNetPlansv2.1_LIS... | nnunet/experiment_planning/change_batch_size.py | 1,657 | input_file = '/home/fabian/data/nnUNet_preprocessed/Task004_Hippocampus/nnUNetPlansv2.1_plans_3D.pkl' output_file = '/home/fabian/data/nnUNet_preprocessed/Task004_Hippocampus/nnUNetPlansv2.1_LISA_plans_3D.pkl' a = load_pickle(input_file) a['plans_per_stage'][0]['batch_size'] = int(np.floor(6 / 9 * a['plans_per_stage'][... | 467 | en | 0.430093 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import RK45
f_out = "E:\\1\\P_rk4.txt" # address file for output
f2 = open(f_out,"w+")
def du_dx(x,y):
wa=1 # atomic frequency
wp=0.6 # field frequency
g=0.6 # coupling strength
n = 1 # number of photons
A = n*... | RK45 - Copy.py | 1,642 | address file for output atomic frequency field frequency coupling strength number of photons initial value print("y_0 = ",y_0) 4 answer of dydx_1,...,dydx_4 print(type(v)) print("v.t[0] = ",v.t[0]) print(len(v.t)) print("------------------") print(v.y) print(len(v.t)) print("------------------") y_1 = v.y[:,0] print... | 905 | en | 0.348858 |
"""
Utility functions for the btcpayserver client
"""
import pickle
from app.db import get_db
from config import Config
def get_client():
"""
Loads the serialized client from database
"""
db = get_db()
pickled_client = db.execute(
"SELECT pickled_client FROM btc_pay_server_client ORDER BY ... | app/btcpayserver_helper.py | 1,526 | Creates a new invoice and returns invoice id
:param price: a given price (default is bitcoin)
:param currency: currency ticker from bitpay API: 'USD', 'EUR', 'BTC' etc
:return: invoice_id -> str
Loads the serialized client from database
Get an invoice by ID
Returns the most return invoice created
Utility functions for ... | 343 | en | 0.693527 |
DEFAULT_INIT = "variance_scaling_initializer(mode='fan_in', distribution='uniform', scale=0.78)"
# Patchining in some alternate conformer arcitectures
def add_SE_block(network, in_layer, name_prefix, se_act="swish"):
# This adds and SE block anywhere
# Returns the output layer name
network[name_prefix + "_SE_r... | users/schupp/hybrid_hmm_nn/network_builders/layers/conformer_SE_block_layer_dynamic_oneact.py | 29,411 | Patchining in some alternate conformer arcitectures This adds and SE block anywhere Returns the output layer name Hack but does the trick first ffn with residual connection MHSA module query per head (B, T, H, D/H) (B, enc-T, D) split the key and value vectors for each head (B, enc-T, H, D/H) (B, enc-T, H, D'/H) encode... | 2,790 | en | 0.448129 |
# --------------------------------------------------------------------------
# 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.
# Changes may cause incor... | src/fidalgo/azext_fidalgo/generated/_params.py | 568 | -------------------------------------------------------------------------- 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. Changes may cause incorrect behavior ... | 506 | en | 0.551802 |
import os
import re
import json
import uuid
from string import Template
from iocbuilder.iocinit import IocDataStream
def debug_print(message, level):
if int(os.getenv("ODIN_BUILDER_DEBUG", 0)) >= level:
print(message)
ADODIN_ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__))... | etc/builder/util.py | 4,035 | Read Odin paths on import | 25 | en | 0.72692 |
"""
Remote platform
This platform uses physical ethernet interfaces.
"""
# Update this dictionary to suit your environment.
remote_port_map = {
(0, 0): "eth0",
(0, 1): "eth1",
(0, 2): "eth2",
(0, 3): "eth3",
(0, 4): "eth4",
(0, 5): "eth5",
(0, 6): "eth6",
(0, 7): "eth7",
(0, 8): "e... | src/ptf/platforms/remote.py | 1,105 | Update configuration for the remote platform
@param config The configuration dictionary to use/update
Remote platform
This platform uses physical ethernet interfaces.
Update this dictionary to suit your environment. | 219 | en | 0.566956 |
import numpy as np
import pandas as pd
import torch
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LogisticRegression
from sklearn import svm
from torch.utils.data import DataLoader
from sklearn.ensemble import ExtraTreesClassifier
from parameters import *
from training.evaluation i... | training/train.py | 4,330 | Define Processor Preprocess Data validation data train data utils.clean_save_data(data_train_path, data_test_path, data_valid_path, required_columns, clean_data_path) Load Datalen(train_test.y.unique()) Train/Test Split Define Model model = md.RNN(x_train.shape[1], output_dim, hidden2, 2) model = md.Model1(x_train.shap... | 1,404 | en | 0.351123 |
import argparse
import configparser
import pexpect
import re
import os
from ipykernel.kernelbase import Kernel
from . import __version__
""" Macaulay2 Jupyter Kernel
"""
class M2Config:
""""""
def __init__(self, execpath, configpath=os.getenv('M2JK_CONFIG')):
""""""
parser = argparse.Argume... | m2_kernel/kernel.py | 11,722 | an interpreter for Macaulay2
the M2 kernel for Jupyter
kernel init - calls __init__ on the parent and sets up the M2Interp object
kernel entry point for the execution of each cell
REPL
If `self.debug==True` then result is the raw list of lines of bytes,
otherwise, it is a list of (... | 1,241 | en | 0.629152 |
#!/usr/bin/env python3
import argparse
import common
import functools
import multiprocessing
import os
import os.path
import pathlib
import re
import subprocess
import stat
import sys
import traceback
import shutil
import paths
EXCLUDED_PREFIXES = ("./generated/", "./thirdparty/", "./build", "./.git/", "./bazel-", ".... | tools/check_format.py | 39,608 | Run checkFormat and return the traceback of any exception.
Run checkFormat in parallel for the given files.
Args:
arg: a tuple (pool, result_list, owned_directories, error_messages)
pool and result_list are for starting tasks asynchronously.
owned_directories tracks directories listed in the CODEOWNERS file.... | 6,648 | en | 0.88576 |
#!usr/bin/env python
import pyeapi
import yaml
from getpass import getpass
from pprint import pprint
from jinja2 import Template
## Loading the yaml file
with open("arista_connect1.yml") as f:
device_dict = yaml.load(f)
new_list = []
### Keys in the dictionary stored in a list
for k in device_dict.keys():
new_... | arista_exercise/ex4_example.py | 2,567 | !usr/bin/env python Loading the yaml file Keys in the dictionary stored in a list data and connect for 4 arista switches For arista switch 2 Arista switch 3 For arista switch 4 | 176 | en | 0.627227 |
#!C:\Users\Claudia\PycharmProjects\BlackJack\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.7'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys... | venv/Scripts/pip3.7-script.py | 421 | !C:\Users\Claudia\PycharmProjects\BlackJack\venv\Scripts\python.exe EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.7' | 135 | en | 0.396494 |
# -*- coding: utf-8 -*-
"""
Source: https://github.com/awesto/django-shop/blob/12e246b356dbc1bc5bbdc8f056e3cb109c617997/shop/money/__init__.py
"""
from .money_maker import MoneyMaker, AbstractMoney
# The default Money type for this shop
Money = MoneyMaker()
| backend/edw_shop/money/__init__.py | 259 | Source: https://github.com/awesto/django-shop/blob/12e246b356dbc1bc5bbdc8f056e3cb109c617997/shop/money/__init__.py
-*- coding: utf-8 -*- The default Money type for this shop | 175 | en | 0.566926 |
# -*- coding: utf-8 -*-
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# imports ######################################################################
import rsa
... | other/tests/rsa-example.py | 1,350 | -*- coding: utf-8 -*- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. imports participants side of sender side of receiver END | 274 | en | 0.907824 |
# 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.
# Changes may ... | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/v2016_04_01/aio/_policy_client.py | 4,405 | To manage and control access to your resources, you can define customized policies and assign
them at a scope.
:ivar policy_assignments: PolicyAssignmentsOperations operations
:vartype policy_assignments:
azure.mgmt.resource.policy.v2016_04_01.aio.operations.PolicyAssignmentsOperations
:ivar policy_definitions: Polic... | 2,190 | en | 0.641903 |
from typing import Tuple, Union
from discord import Embed, Member, PermissionOverwrite, TextChannel, VoiceChannel, VoiceState
from discord.ext.commands import bot_has_guild_permissions
from discord_slash import (
Button,
ComponentContext,
Modal,
ModalContext,
Select,
SelectOption,
SlashComm... | source/cogs/private_rooms.py | 18,513 | Creating a private voice channel | 32 | en | 0.889131 |
from flask import request
from flask_restplus import Resource
from app.project.auth import auth
from app.project.auth.auth_service import AuthService
from app.project.user.user_dto import UserDto
from app.project.user.user_service import UserService
api = UserDto.api
_user = UserDto.user
@api.route('/')
class UserL... | app/project/user/user_controller.py | 1,377 | List all registered users
get a user given its identifier
Creates a new User(only for admin) | 92 | en | 0.716425 |
from django.core.management.base import BaseCommand
# Third-Party
import requests
class Command(BaseCommand):
help = "Command to upload from dropbox."
def add_arguments(self, parser):
parser.add_argument(
'dropbox',
nargs='?',
)
def handle(self, *args, **options)... | project/apps/core/management/commands/upload_file.py | 812 | Third-Party Parse URL input open in binary mode get request write to file | 73 | en | 0.801998 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | qiskit/circuit/gate.py | 10,144 | Unitary gate.
Create a new gate.
Args:
name: The Qobj name of the gate.
num_qubits: The number of qubits the gate acts on.
params: A list of parameters.
label: An optional label for the gate.
Expands a single argument.
For example: [q[0], q[1]] -> [q[0]], [q[1]]
Assemble a QasmQobjInstruction
Validati... | 3,827 | en | 0.634997 |
import numpy as np
def make_exp_kernel(L0):
def exp_kernel(x1, x2):
x1 = np.expand_dims(x1, 2) # Append a singleton dimension
x2 = x2.T
return np.exp(-np.mean(np.abs(x1 - x2), axis=1) / L0)
return exp_kernel
def make_sq_exp_kernel(L0):
def sq_exp_kernel(x1, x2):
x1 = np.exp... | cpu_ver/hypergrad/kernel_methods.py | 991 | Computes the negative log prob per data point.
Append a singleton dimension Append a singleton dimension | 106 | en | 0.431311 |
import os
import sys
import torch
import numpy as np
import datetime
import logging
import provider
import importlib
import shutil
import argparse
from pathlib import Path
from tqdm import tqdm
from data_utils.PCDLoader import *
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = BASE_DIR
sys.path.appe... | train_realMulti-DA-Loss_classification.py | 16,334 | PARAMETERS
Not Implement domain_adaptation_dataset = PCDPointCloudData(tactile_data_path, folder='Train', random_num=True, list_num_point=[10,20,30,40,50]) Load pretrained model with real dataset Freeze Conv Multi-layer Loss F... | 1,202 | en | 0.316942 |
# Copyright 2020 Determined AI. 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 o... | yogadl/dataref/_local_lmdb_dataref.py | 2,832 | Create a stream from a cache.
Copyright 2020 Determined AI. 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 ap... | 683 | en | 0.820085 |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class UserNotificationSubject(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | gitee/models/user_notification_subject.py | 4,996 | 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
UserNotificationSubject - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the latest_comment_url of this UserNotificationS... | 1,547 | en | 0.682969 |
import datetime as dt
import matplotlib.pyplot as plt
import lifetimes
import numpy as np
import os
import pandas as pd
import seaborn as sns
def numcard(x):
return x.nunique(), len(x)
def todateclean(x):
return pd.to_datetime(x, errors='coerce').dt.date.astype('datetime64')
"""
- info, shape, dtypes
- df.isn... | clvscript00.py | 12,716 | 4 floats. Eyeball distribution of frequency (calculated) Lec21 similar to lifelines no regularization param. See https://www.youtube.com/watch?v=guj2gVEEx4s and https://www.youtube.com/watch?v=gx6oHqpRgpY residual lifetime value is more useful construct lec 24: set an outer time boundary and predict cumulative purchase... | 3,036 | en | 0.850282 |
# Copyright 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fcntl
import hashlib
import os
import shutil
import subprocess
import sys
# Allow use of this module even if termcolor is missing. There are ma... | lib/webports/util.py | 13,629 | Lock used when building a package (essentially a lock on OUT_DIR)
Per-directory flock()-based context manager
This class will raise an exception if another process already holds the
lock for the given directory.
Lock used when installing/uninstalling package
Check validity of NACL_SDK_ROOT.
Returns True if the current... | 3,026 | en | 0.825113 |
from . import sean_common as common
import torch.nn as nn
import torch
from basicsr.utils.registry import ARCH_REGISTRY
class LFF(nn.Module):
def __init__(self, scale, n_colors, conv=common.default_conv, n_feats=64):
super(LFF, self).__init__()
kernel_size = 3
n_layes = 5
act = nn.... | basicsr/archs/seanet_arch.py | 14,881 | define head module define body module define tail module import torch.nn as nn import torch from basicsr.utils.registry import ARCH_REGISTRY import math import torch import torch.nn as nn def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel... | 8,952 | en | 0.401985 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
... | docs/source/conf.py | 2,189 | Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- If extensions (or mod... | 1,570 | en | 0.696663 |
# Lint as: python2, python3
# Copyright 2019 Google 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/LICENSE-2.0
#
# Unless req... | tfx/components/trainer/fn_args_utils_test.py | 3,674 | Tests for tfx.components.trainer.fn_args_utils.
Lint as: python2, python3 Copyright 2019 Google 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/l... | 839 | en | 0.805423 |
# 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
from .. import _utilities, _tables
from ... | sdk/python/pulumi_azure_native/portal/user_settings.py | 4,236 | Response to get user settings
API Version: 2018-10-01.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['UserPropertiesArgs']] properties: The cloud shell user settings properties.
:param pulumi.Input[str] user_settin... | 904 | en | 0.725692 |
# Copyright 2020. Allen Institute. All rights reserved
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the follow... | bmtk/utils/reports/spike_trains/plotting.py | 16,245 | Helper function for parsing the 'node_groups' params
Helper function to figure out which population of nodes to use.
Make sure SpikeTrainsAPI object is always returned
will create a raster plot (plus optional histogram) from a SpikeTrains object or SONATA Spike-Trains file. Will
return the figure
By default will displ... | 7,980 | en | 0.728804 |
import time
import pygame
def manual_control(**kwargs):
from .knights_archers_zombies import env as _env
env = _env(**kwargs)
env.reset()
done = False
cur_agent = 0
frame_count = 0
# frame_limit = 500
quit_game = 0
while not done:
# while frame_count < frame_limit: # Unco... | pettingzoo/gamma/knights_archers_zombies/manual_control.py | 1,988 | frame_limit = 500 while frame_count < frame_limit: Uncomment this if you want the game to run for fame_limit amount of frames instead of ending by normal game conditions (useful for testing purposes) If you want to do manual input 5 is do nothing, 0 is up, 1 is down, 2 is turn CW, 3 is CCW, 4 is attack Backspace to re... | 339 | en | 0.884702 |
import sys, getopt
from .summarizer import summarize
from .keywords import keywords
# Types of summarization
SENTENCE = 0
WORD = 1
def exit_with_error(err):
print("Error: " + str(err))
usage()
sys.exit(2)
def get_arguments():
try:
opts, args = getopt.getopt(sys.argv[1:], "t:s:r:w:h", ["text... | summa/textrank.py | 2,017 | Types of summarization | 22 | en | 0.853054 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | pipeline_plugins/components/collections/controller.py | 6,061 | Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
Y... | 825 | en | 0.696723 |
__version__ = "0.1.0"
import mmap
import os
# from .ext import load_file, parse
#-------------------------------------------------------------------------------
def parse_file(path, **kw_args):
fd = os.open(path, os.O_RDONLY)
try:
map = mmap.mmap(fd, 0, prot=mmap.PROT_READ)
return parse(ma... | src/fixprs/__init__.py | 370 | from .ext import load_file, parse------------------------------------------------------------------------------- | 114 | en | 0.201762 |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2022 Osyris contributors (https://github.com/nvaytet/osyris)
# flake8: noqa
from .array import Array
from .datagroup import Datagroup
from .dataset import Dataset
from .plot import Plot
from .ism_physics import get_eos, get_opacities
| src/osyris/core/__init__.py | 292 | SPDX-License-Identifier: BSD-3-Clause Copyright (c) 2022 Osyris contributors (https://github.com/nvaytet/osyris) flake8: noqa | 125 | en | 0.395197 |
from filelock import FileLock
import torch
import pandas as pd
from .tools import BuildingTemperatureDataset
import os
def train(model, device, dataloader, optimizer):
"""
Performs one epoch of training.
Order of rooms in building and in data must match otherwise model will fit wrong rooms to data.
"""... | src/rcmodel/optimisation.py | 7,497 | Parameters
----------
model : object
RCModel class object.
csv_path : string
Path to .csv file containing room temperature data.
Data will be sorted if not done already and saved to a new file with the tag '_sorted'
sample_size : int
Length of indexes to sample from dataset per batch.
dt : int
Times... | 2,284 | en | 0.806912 |
# -*- coding: utf-8 -*-
#
# 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
#... | tests/providers/amazon/aws/operators/test_hive_to_dynamodb.py | 5,060 | -*- coding: utf-8 -*- 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... | 864 | en | 0.896673 |
# protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | tools/protodoc/protodoc.py | 27,312 | Base error class for the protodoc module.
Visitor to generate a RST representation from a FileDescriptor proto.
See visitor.Visitor for visitor method docs comments.
Enum cross reference label.
Enum value cross reference label.
Field cross reference label.
File cross reference label.
Format a label as an Envoy API RST... | 6,495 | en | 0.613065 |
# coding=utf-8
# *** WARNING: this file was generated by test. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from . import _utilities
import typing
# Export this package's modules as members:
from .foo import *
from .provider import *
_utilities.register(
resource_modules="""... | pkg/codegen/testing/test/testdata/simple-methods-schema-single-value-returns/python/pulumi_example/__init__.py | 590 | coding=utf-8 *** WARNING: this file was generated by test. *** *** Do not edit by hand unless you're certain you know what you are doing! *** Export this package's modules as members: | 183 | en | 0.966705 |
from django import forms
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden, HttpResponse
from django.short... | src/profiles/views.py | 9,246 | messagescreatedef form_valid(self, form): user = self.request.user form.instance.user = user valid_data = super(nomedaview, self).form_valid(form) adicione qq coisa apos a mensagem criada return valid_data Create your views here. CREATE saving the user firstuser = User.objects.create_user(self.request.POST.get('name'),... | 879 | en | 0.471129 |
# pylint: disable=R,C,W
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author : Nasir Khan (r0ot h3x49)
Github : https://github.com/r0oth3x49
License : MIT
Copyright (c) 2018-2025 Nasir Khan (r0ot h3x49)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associa... | udemy/internal.py | 8,378 | Author : Nasir Khan (r0ot h3x49)
Github : https://github.com/r0oth3x49
License : MIT
Copyright (c) 2018-2025 Nasir Khan (r0ot h3x49)
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 res... | 1,229 | en | 0.824612 |
import argparse
import datetime
import time
import torch
from torch import distributed as dist
from torch.nn import DataParallel
from torch.nn.parallel.distributed import DistributedDataParallel
from distillation.tool import DistillationBox
from models import load_ckpt, get_model, save_ckpt, set_bottleneck_transforme... | src/mimic_fix.py | 5,929 | distributed training parameters torch.cuda.empty_cache() | 56 | en | 0.300212 |
#!/usr/bin/env python3
from fairseq import models
from fairseq.data import FairseqDataset, data_utils
from fairseq.models import FairseqMultiModel
from fairseq.tasks.multilingual_translation import MultilingualTranslationTask
from pytorch_translate.data import iterators as ptt_iterators
class PyTorchTranslateMultiTa... | pytorch_translate/tasks/pytorch_translate_multi_task.py | 2,202 | Return None to allow model to dictate max sentence length allowed
!/usr/bin/env python3 get indices ordered by example size filter examples that are too large create mini-batches with given size constraints return a reusable, sharded iterator | 243 | en | 0.789392 |
#!/usr/bin/python
#
# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
#
"""
Swift upload image file.
This file contains implementation of gett
swift download URL for the uploaded image file
"""
from builtins import object
from builtins import str
from future import standard_library
standard_library.i... | src/config/fabric-ansible/ansible-playbooks/library/swift_fileutil.py | 8,077 | Init routine.
Swift upload image file.
This file contains implementation of gett
swift download URL for the uploaded image file
!/usr/bin/python Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. noqa pragma: no cover | 231 | en | 0.881459 |
import sys
import logging
logger = logging.getLogger(__name__)
import base64
import json
import datetime
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric... | mqfactory/message/security/rsa.py | 3,135 | utility functions wrapping cryptography functions unicode -> str | 64 | en | 0.464802 |
# Copyright 2019 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | tests/st/ops/ascend/vector/test_expm1_001.py | 2,796 | clean environment
:return:
run case.#
:return:
run case.#
:return:
################################################
Testcase_PrepareCondition:
Testcase_TestSteps:
Testcase_ExpectedResult:
Copyright 2019 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use thi... | 875 | en | 0.63936 |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from gfx.models import Material, Mesh, Shader, Model
import subprocess
import os
import base64
import platform
def get_mesh( request, mesh_id):
mesh = get_object_or_404(Mesh, pk=mesh_id)
"""
TODO: Make it grab it from t... | gfx/views.py | 2,127 | exportedMesh.findwith( mesh_id )): Can't find it, then grab the mesh, and export it | 83 | en | 0.735304 |
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import argparse
def plot():
results_dir = './'
results_files = [result for result in os.listdir(results_dir) if 'MAESTROeX' in result]
n_gpus_per_node = 6
throughput_list = []
nnodes_list = []
... | Exec/test_problems/reacting_bubble/scaling/sc20/plot.py | 2,448 | Determine the number of MPI ranks and thus the number of nodes. For each step, add up the number of zones advanced and the walltime for that step. Now we have all the results, so plot them. | 189 | en | 0.876496 |
import math
# 1
area_of_circle = lambda r: math.pi * r ** 2
print(area_of_circle(10))
# 2
calculation = lambda x, y: ((x + y), (x - y))
print(calculation(4, 2))
# 3
def product(n):
if n == 1:
return 1
else:
return n * product(n - 1)
print(product(5))
# 4
time = lambda milli: (
round(m... | nus-bead/examples/Workshop01.py | 1,292 | 1 2 3 4 5 6 7 8 data.sort() | 27 | fr | 0.096059 |
import threading
import time
class PyMbsThread(threading.Thread):
def __init__(self, function, realTime=False):
threading.Thread.__init__(self)
self.execute = False
self.function = function
self.realTime = realTime
self.scaling = 1
# Start-Time (Model)
self... | pymbs/ui/thread.py | 1,721 | Start-Time (Model) Start-Time (Real) Initialise Offsets Debug print "Starting Thread " + str(id(self)) Endless Loop synchronise with real time Real Elapsed Time Model Elapsed Time Difference Execute next step Debug print "Finished Thread " + str(id(self)) Debug print "Stopped Thread " + str(id(self)) | 301 | en | 0.714176 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cloudblue.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Impo... | manage.py | 629 | Django's command-line utility for administrative tasks.
!/usr/bin/env python | 77 | en | 0.656913 |
"""Config flow for Coronavirus integration."""
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.data_entry_flow import FlowResult
from . import get_coordinator
from .const import DOMAIN, OPTION_WORLDWIDE
class ConfigFlow... | homeassistant/components/coronavirus/config_flow.py | 1,647 | Handle a config flow for Coronavirus.
Config flow for Coronavirus integration. | 78 | en | 0.583121 |
from django_cradmin import crinstance, crapp
from django_cradmin.crinstance import reverse_cradmin_url
from devilry.apps.core.models import Period
from devilry.devilry_account.models import PeriodPermissionGroup
from devilry.devilry_admin.cradminextensions import devilry_crmenu_admin
from devilry.devilry_cradmin impor... | devilry/devilry_admin/views/period/crinstance_period.py | 4,430 | Get the devilryrole for the requesting user on the current
period (request.cradmin_instance).
The return values is the same as for
:meth:`devilry.devilry_account.models.PeriodPermissionGroupQuerySet.get_devilryrole_for_user_on_period`,
exept that this method raises ValueError if it does not find a role.
Get a short ti... | 398 | en | 0.690114 |
# qubit number=4
# total number=42
import cirq
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from ma... | benchmark/startQiskit_QC2449.py | 4,456 | qubit number=4 total number=42 implement the oracle O_f NOTE: use multi_control_toffoli_gate ('noancilla' mode) https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-... | 802 | en | 0.395193 |
# from nonbonded.cli.project.project import project
#
# __all__ = [project]
| nonbonded/cli/projects/__init__.py | 76 | from nonbonded.cli.project.project import project __all__ = [project] | 69 | en | 0.536717 |
# Copyright 2022 The Kubeflow 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 ... | pkg/suggestion/v1beta1/internal/trial.py | 3,854 | Copyright 2022 The Kubeflow 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 writing, software ... | 605 | en | 0.852357 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# capmetrics-etl documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 11 00:08:57 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in th... | docs/conf.py | 9,314 | !/usr/bin/env python3 -*- coding: utf-8 -*- capmetrics-etl documentation build configuration file, created by sphinx-quickstart on Mon Jan 11 00:08:57 2016. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated fi... | 7,889 | en | 0.637284 |
import string
from app.chatterbot import languages
from spacy.lang.zh import Chinese
class LowercaseTagger(object):
"""
Returns the text in lowercase.
"""
def __init__(self, language=None):
self.language = language or languages.ENG
def get_text_index_string(self, text):
return te... | app/chatterbot/tagging.py | 2,159 | Returns the text in lowercase.
Return a string of text containing part-of-speech, lemma pairs.
punc = punc.decode("utf-8") if not bigram_pairs: bigram_pairs = [ token.lemma_.lower() for token in document ] return ' '.join(bigram_pairs) | 253 | en | 0.315019 |
import torch_xla.test.test_utils as test_utils
import torch_xla.distributed.xla_multiprocessing as xmp
import torch_xla.core.xla_model as xm
import torch_xla.utils.utils as xu
import torch_xla.distributed.parallel_loader as pl
import torch_xla.debug.metrics as met
import torch_xla
import torchvision.transforms as trans... | test_train_mp_wds_local.py | 15,091 | Split urls_ correctly per accelerator node
:param urls:
:return: slice of urls_
Split urls per worker
Selects a subset of urls based on Torch get_worker_info.
Used as a shard selection function in Dataset.
replaces wds.split_by_worker
import warnings warnings.filterwarnings("ignore") profiler_port=9012 import gcsdata... | 3,141 | en | 0.306259 |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoinlimitededition Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the REST API."""
from test_framework.test_framework import BitcoinlimitededitionTes... | test/functional/interface_rest.py | 15,219 | Test the REST API.
!/usr/bin/env python3 Copyright (c) 2014-2017 The Bitcoinlimitededition Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.allows simple http get callsallows simple http post calls with a request bodybal... | 2,305 | en | 0.788556 |
import random
import turtle
import time
def menu():
x = input('would you like to start the game? \n (YES/NO) \n would you like to quit the menu bar? \n (QUIT) \n *PLEASE USE CAPITAL LETTERS \n YOUR ANSWER: ')
if x == 'NO' or x == 'QUIT':
quit()
elif x == 'YES':
print('')
menu()
print('are... | jennifer & Laith/laith_eatit.py | 8,751 | listsbird = turtle.clone()turtle.addshape('bird.gif')bird.shape('bird.gif')turtle.hideturtle()''' if x_pos >= RIGHT_EDGE: turtle.goto(RIGHT_EDGE - 10, y_pos) if x_pos <= LEFT_EDGE: turtle.goto(LEFT_EDGE + 10, y_pos) if y_pos >= UP_EDGE: turtle.goto(x_pos, UP_EDGE + 10)''' if wit... | 1,730 | en | 0.222785 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ['baidu_download']
from ..common import *
from .embed import *
from .universal import *
def baidu_get_song_data(sid):
data = json.loads(get_html(
'http://music.baidu.com/data/music/fmlink?songIds=%s' % sid, faker=True))['data']
if data['xcode'... | src/you_get/extractors/baidu.py | 12,107 | !/usr/bin/env python -*- coding: utf-8 -*- inside china mainland outside china mainland embedded videos images handle albums raise NotImplementedError("Password required!") | 172 | en | 0.528254 |
# coding: utf-8
"""
Decision Lens API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
impor... | python/test/test_field_description_updated_event.py | 1,021 | FieldDescriptionUpdatedEvent unit test stubs
Test FieldDescriptionUpdatedEvent
Decision Lens API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf... | 501 | en | 0.495645 |
#!/usr/bin/env python
import jinja2
import os
import re
import shlex
import sys
import mkdocs.build
from mkdocs.build import build
from mkdocs.config import load_config
from urllib2 import urlopen
import subprocess
def line_containing(lines, text):
for i in range(len(lines)):
if text.lower() in lines[i].lower(... | docs/buildsite.py | 3,663 | !/usr/bin/env python Wrap some functions to allow custom commands in markdown Import external markdownTry as a URL invalid URL, try as a file Run a shell command Source code embedsTry as a URL invalid URL, try as a file Short hand for specifying a region If line_containing failsTODO: Also allow regex matching Trim "OMI... | 620 | en | 0.660064 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of moses. Its use is licensed under the GNU Lesser General
# Public License version 2.1 or, at your option, any later version.
from __future__ import print_function, unicode_literals
import logging
import argparse
import subprocess
import sys
import... | examples/mosesdecoder-master/scripts/training/rdlm/train_rdlm.py | 10,825 | !/usr/bin/env python -*- coding: utf-8 -*- This file is part of moses. Its use is licensed under the GNU Lesser General Public License version 2.1 or, at your option, any later version. ../bilingual-lm Create output dir if necessary | 233 | en | 0.814978 |
# qubit number=3
# total number=14
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collectio... | benchmark/startQiskit_noisy696.py | 2,543 | qubit number=3 total number=14 circuit begin number=1 number=11 number=12 number=13 number=8 number=3 number=4 number=5 number=6 number=9 number=10 circuit end prog.draw('mpl', filename=(kernel + '.png')) | 204 | en | 0.159633 |
"""Provides the MenuItem class."""
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union
from attr import attrs
from ..action import ActionFunctionType
from ..mixins import RegisterEventMixin
if TYPE_CHECKING:
from ..types import TitleFunction
@attrs(auto_attribs=True)
class MenuItem(Regi... | earwax/menus/menu_item.py | 2,490 | An item in a :class:`~earwax.menu.Menu`.
This class is rarely used directly, instead
:meth:`earwax.menu.Menu.add_item` or :meth:`earwax.menu.Menu.item` can be
used to return an instance.
:ivar ~earwax.MenuItem.func: The function which will be called when this
item is activated.
:ivar ~earwax.MenuItem.title: The ... | 1,516 | en | 0.745645 |
# -*- coding: utf-8 -*-
from django.urls import path
app_name = 'login'
urlpatterns = []
| apps/login/urls.py | 95 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
from datetime import datetime
import numpy as np
import re
from bamboo.core.frame import RESERVED_KEYS
from bamboo.core.parser import Parser
from bamboo.lib.exceptions import ArgumentError
from bamboo.lib.mongo import reserve_encoded
CARDINALITY = 'cardinality'
OLAP_TYPE = 'olap_type'
SIMPLETYPE = 'simpletype'
LABEL... | bamboo/lib/schema_builder.py | 8,261 | olap_types simpletypes map from numpy objects to olap_types map from numpy objects to simpletypes merge new schema with existing schema use existing labels for existing columns E.g. dates with and without offset can not be compared and raise a type error. | 255 | en | 0.58207 |
import numpy as np
import theano.tensor as tt
from pymc3.util import get_variable_name
from ..math import logsumexp
from .dist_math import bound
from .distribution import Discrete, Distribution, draw_values, generate_samples
from .continuous import get_tau_sd, Normal
def all_discrete(comp_dists):
"""
Determi... | pymc3/distributions/mixture.py | 7,725 | Mixture log-likelihood
Often used to model subpopulation heterogeneity
.. math:: f(x \mid w, \theta) = \sum_{i = 1}^n w_i f_i(x \mid \theta_i)
======== ============================================
Support :math:`\cap_{i = 1}^n \textrm{support}(f_i)`
Mean :math:`\sum_{i = 1}^n w_i \mu_i`
======== ===========... | 2,260 | en | 0.591713 |
'''
Class containing a Massey-style model and rankings of a season.
todo: documentation
todo: type hints
todo: inherit from Model?
'''
class Massey:
def __init__(self):
'''
todo: this. what fields does it need?
'''
pass
def rank(self) -> List[Team]:
'''
Giv... | src/models/Massey.py | 802 | todo: this. what fields does it need?
todo: docs
todo: weighting param?
parse teams and games from file
create matrix from teams and games
Given a ranking of the teams, and the draw for the bracket, predict who wins and stuff
Given a matrix, create a power ranking of the teams
Class containing a Massey-style model and... | 406 | en | 0.833604 |
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# directory.py - parse directory information
# -----------------------------------------------------------------------------
# $Id$
#
# ---------------------------------------------------------------------------... | external/metadata/misc/directory.py | 3,236 | Simple parser for reading a .directory file.
-*- coding: iso-8859-1 -*- ----------------------------------------------------------------------------- directory.py - parse directory information ----------------------------------------------------------------------------- $Id$ ------------------------------------------... | 1,499 | en | 0.625666 |
from Transform.Transform import *
qhost = '10.0.0.10'
qport = 5100
bucket_name = 's3a://insighttmpbucket1/'
index_name = bucket_name + 'index.txt'
tickers = get_stock_list(index_name)
q_con, flint_con, spark_con = connect(qhost, qport)
#push_raw_table(q_con, spark_con, flint_con, bucket_name, tickers)
push_returns(q... | src/main.py | 370 | push_raw_table(q_con, spark_con, flint_con, bucket_name, tickers) | 65 | en | 0.426143 |
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS).
# Last modified by David J Turner (david.turner@sussex.ac.uk) 21/01/2021, 11:45. Copyright (c) David J Turner
from .fit import single_temp_apec, power_law, single_temp_apec_profile
from .run import execute_c... | xga/xspec/__init__.py | 338 | This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). Last modified by David J Turner (david.turner@sussex.ac.uk) 21/01/2021, 11:45. Copyright (c) David J Turner | 216 | en | 0.735622 |
for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
print((pow(int(pow(10, i)//9), 2)))
| Python/Math/triangle_quest_2.py | 160 | More than 2 lines will result in 0 score. Do not leave a blank line also | 72 | en | 0.945748 |
"""trefechanwen URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | trefechanwen/urls.py | 1,745 | trefechanwen URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... | 638 | en | 0.657507 |
#!/usr/bin/env python
# coding: utf-8
# # Exploring JHU COVID Case, Death, and Vaccine Information
# This notebook takes the live, updated data from JHU CSSE and GovEx, formats and simplifies it for my purposes, and saves it in csv files in the same directory. The two data sources use slightly different conventions an... | .scripts/dataprep.py | 5,839 | !/usr/bin/env python coding: utf-8 Exploring JHU COVID Case, Death, and Vaccine Information This notebook takes the live, updated data from JHU CSSE and GovEx, formats and simplifies it for my purposes, and saves it in csv files in the same directory. The two data sources use slightly different conventions and provide... | 3,049 | en | 0.839176 |
from typing import Tuple
import math
import torch
from torch.optim.optimizer import Optimizer
def linear_warmup_and_cosine_protocol(
f_values: Tuple[float, float, float],
x_milestones: Tuple[int, int, int, int]):
"""
There are 5 regions:
1. constant at f0 for x < x0
2. linear increase ... | src/tissue_purifier/models/_optim_scheduler.py | 6,863 | Extends SGD in PyTorch with LARS scaling from the paper
'Large batch training of Convolutional Networks <https://arxiv.org/pdf/1708.03888.pdf>'_.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
momentum (float, optional): mome... | 2,662 | en | 0.659926 |
'''
Title : Shape and Reshape
Subdomain : Numpy
Domain : Python
Author : codeperfectplus
Created : 06 May 2020
'''
import numpy as np
arr = list(map(int,input().split()))
arr = np.array(arr)
print(np.reshape(arr,(3,3)))
| HackerRank/PythonHackerRankSolutions/Numpy/ShapeandReshape.py | 235 | Title : Shape and Reshape
Subdomain : Numpy
Domain : Python
Author : codeperfectplus
Created : 06 May 2020 | 118 | en | 0.483868 |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Wallet encryption"""
import time
from test_framework.test_framework import enzoTestFramework
fro... | test/functional/wallet_encryption.py | 3,797 | Test Wallet encryption
!/usr/bin/env python3 Copyright (c) 2016-2017 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Make sure the wallet isn't encrypted first Encrypt the wallet Test that the wallet is enc... | 622 | en | 0.752559 |
#!/usr/bin/env python3
# Copyright (c) 2017 The Eurodollar Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import EurodollarTestFramework
from ... | test/functional/rpc_deprecated.py | 1,268 | Test deprecation of RPC calls.
!/usr/bin/env python3 Copyright (c) 2017 The Eurodollar Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. | 236 | en | 0.567127 |
#
# PySNMP MIB module CISCO-EVC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EVC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:57:43 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/CISCO-EVC-MIB.py | 122,691 | PySNMP MIB module CISCO-EVC-MIB (http://snmplabs.com/pysmi) ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EVC-MIB Produced by pysmi-0.3.4 at Wed May 1 11:57:43 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.370429 |
# -*- coding: utf-8 -*-
from django.db import models
from django.shortcuts import render,redirect
from django.views import View
from django.contrib.auth import authenticate, login , logout as django_logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http imp... | TBS/b2b/views.py | 1,101 | -*- coding: utf-8 -*- Create your views here. | 45 | en | 0.897093 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a self-generating script that contains all of the iso3166-1 data.
To regenerate, a CSV file must be created that contains the latest data. Here's
how to do that:
1. Visit https://www.iso.org/obp
2. Click the "Country Codes" radio option and click the search bu... | django_countries/data.py | 17,818 | The following code can be used for self-generation of this file.
It requires a UTF-8 CSV file containing the short ISO name and two letter
country code as the first two columns.
This is a self-generating script that contains all of the iso3166-1 data.
To regenerate, a CSV file must be created that contains the latest... | 1,068 | en | 0.809766 |
import unittest
from tori.decorator.common import *
class TestDecoratorCommonSingletonClass(unittest.TestCase):
""" Test the 'singleton' decorator. """
class DummyTest(object):
def __init__(self):
self.number = 0
def take_action(self):
self.number += 1
def get_n... | test/ut/test_decorator_common_singleton.py | 8,169 | Test the 'singleton' decorator.
Negative test for @singleton with class_reference provided for the constructor
Test if the target class is with null singleton attribute.
Test if the target class has already had an attribute `_singleton_instance` but it is not compatible.
Positive test for @singleton with parameters... | 1,468 | en | 0.851087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.