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 |
|---|---|---|---|---|---|---|
# example of except/from exception usage
try:
1 / 0
except Exception as E:
raise NameError('bad') from E
"""
Traceback (most recent call last):
File "except_from.py", line 4, in <module>
1 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Trac... | python_learning/except_from.py | 610 | example of except/from exception usage *implicit related exception try: 1 / 0 except: wrongname NameError raise <exceptionnsme> from None complitly stops relation of exception | 184 | en | 0.644168 |
# 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... | doc/v2/howto/cluster/src/word2vec/api_train_v2_cluster.py | 5,340 | 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... | 625 | en | 0.852706 |
import graphene
import datetime
import urllib
import json
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.signing import TimestampSigner
from django.shortcuts import render
from .registry import registry
from .signals import pre... | grapple/models.py | 6,404 | Classes used to define what the Django field should look like in the GQL type Mixin for pages that want extra Grapple benefits: Check token is valid | 148 | en | 0.877484 |
"""
Lemur
=====
Is a TLS management and orchestration tool.
:copyright: (c) 2015 by Netflix, see AUTHORS for more
:license: Apache, see LICENSE for more details.
"""
from __future__ import absolute_import
import sys
import json
import os.path
import datetime
from distutils import log
from distutils.core import Comm... | setup.py | 6,621 | Installs Lemur into the Python environment.
If the package indicator is missing, this will also force a run of
`build_static` which is required for JavaScript assets and other things.
Lemur
=====
Is a TLS management and orchestration tool.
:copyright: (c) 2015 by Netflix, see AUTHORS for more
:license: Apache, see LI... | 575 | en | 0.90938 |
from base_sss import SubsetSelectionStrategy
import base_sss
import random
import torch
class BALDDropoutStrategy(SubsetSelectionStrategy):
def __init__(self, size, Y_vec, n_drop=10, previous_s=None):
self.previous_s = previous_s
self.n_drop = n_drop
super(BALDDropoutStrategy, self).__init_... | mexmi/subset_selection_strategy/bayesian_disagreement_dropout_sss.py | 1,229 | random.setstate(base_sss.sss_random_state)unlabelled copy mdeol outputsdropoutnp.unique(Y) print("points,", points) | 115 | en | 0.326722 |
from .fis import FIS
import numpy as np
try:
import pandas as pd
except ImportError:
pd = None
try:
from sklearn.model_selection import GridSearchCV
except ImportError:
GridSearchCV = None
def _get_vars(fis):
"""Get an encoded version of the parameters of the fuzzy sets in a FIS"""
for vari... | zadeh/tune.py | 5,264 | An exhaustive FIS tuner
A parametrizable Fuzzy Inference System with a scikit-learn-like interface
Splitter with single split no training data and full test data
Args:
fis (FIS): The Fuzzy Inference System to tune
params (dict of str to list): A mapping from encoded parameters to the list of values to explore.
... | 1,157 | en | 0.651222 |
#!/usr/bin/env python
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (C) Google LLC, 2018
#
# Author: Tom Roeder <tmroeder@google.com>
#
"""A tool for generating compile_commands.json in the Linux kernel."""
import argparse
import json
import logging
import os
import re
_DEFAULT_OUTPUT = 'compile_commands.json'
_DE... | ubuntu-bionic-hwe-edge/scripts/gen_compile_commands.py | 5,695 | Walks through the directory and finds and parses .cmd files.
Sets up and parses command-line arguments.
Returns:
log_level: A logging level to filter log output.
directory: The directory to search for .cmd files.
output: Where to write the compile-commands JSON file.
Extracts information from a .cmd line a... | 1,810 | en | 0.877834 |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Namespace browser widget"""
import os.path as osp
import socket
from spyderlib.qt.QtGui import (QWidget, QVBoxLayout, QHBoxLayout, QMenu,
... | spyderlib/widgets/externalshell/namespacebrowser.py | 25,142 | Namespace browser (global variables explorer widget)
Return socket connection
Collapse
Return array's ndim
Return array's shape
Return internal shell data types filter:
* check_all: check all elements data types for sequences
(dict, list, tuple)
* mode (string): 'editable' or 'picklable'
Return sequence l... | 1,713 | en | 0.531938 |
from typing import Optional
from inan.types.blockchain_format.coin import Coin
from inan.types.blockchain_format.program import Program
from inan.types.blockchain_format.sized_bytes import bytes32
from inan.wallet.puzzles.load_clvm import load_clvm
MOD = load_clvm("genesis-by-coin-id-with-0.clvm", package_or_requirem... | inan/wallet/puzzles/genesis_by_coin_id_with_0.py | 1,447 | Given a specific genesis coin id, create a `genesis_coin_mod` that allows
both that coin id to issue a cc, or anyone to create a cc with amount 0.
Given a `genesis_coin_checker` program, pull out the genesis coin id. | 216 | en | 0.699419 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
import tensorflow as tf
from edward.inferences.monte_carlo import MonteCarlo
from edward.models import RandomVariable, Empirical
from edward.util import copy
try:
from edward.models import Normal... | edward/inferences/sghmc.py | 4,918 | Stochastic gradient Hamiltonian Monte Carlo (Chen et al., 2014).
#### Notes
In conditional inference, we infer $z$ in $p(z, \beta
\mid x)$ while fixing inference over $\beta$ using another
distribution $q(\beta)$.
`SGHMC` substitutes the model's log marginal density
$\log p(x, z) = \log \mathbb{E}_{q(\beta)} [ p(x, ... | 1,664 | en | 0.663742 |
import torch.nn as nn
import numpy as np
import pytest
from test.utils import convert_and_test
class LayerSigmoid(nn.Module):
"""
Test for nn.layers based types
"""
def __init__(self):
super(LayerSigmoid, self).__init__()
self.sig = nn.Sigmoid()
def forward(self, x):
x = ... | test/layers/activations/test_sigmoid.py | 1,178 | Test for nn.functional types
Test for nn.layers based types | 59 | en | 0.912132 |
#!/usr/bin/env python
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au>
#
# 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... | lib/ansiblelint/__main__.py | 7,368 | !/usr/bin/env python Copyright (c) 2013-2014 Will Thames <will@thames.id.au> 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, cop... | 1,097 | en | 0.863252 |
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... | sdk/netapp/azure-mgmt-netapp/setup.py | 2,572 | !/usr/bin/env python------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information.-------------------------------------------------------------------------- C... | 514 | en | 0.638221 |
from typing import List, Optional
from discord.ext import commands
from fastapi import APIRouter
from pydantic import BaseModel
from bot.utils import ConnectionUtil, get_conn
class PartialAnswer(BaseModel):
"""Represents the model for an incomplete 8ball answer."""
response: Optional[str]
weight: Option... | bot/extensions/misc/eight_ball.py | 2,318 | Represents an already inserted 8ball answer, is usually returned.
Represents the model for an incomplete 8ball answer.
Weighted random selection FastAPI converts it into a list of Answers FastAPI handles convering it into an Answer | 233 | en | 0.919728 |
#!/usr/bin/env python3
import os
import subprocess
import sys
import serial
import numpy as np
import datetime
iterations = 1
def run(scheme, precomp_bitslicing, use_hardware_crypto):
os.system("make clean")
path = f"crypto_sign/{scheme}/m4"
binary = f"crypto_sign_{scheme}_m4_stack.bin"
if precomp_bitslicing:... | run_all_stack.py | 3,295 | !/usr/bin/env python3 get serial output and wait for '' | 55 | en | 0.492004 |
# python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... | acme/core.py | 5,044 | Interface for an agent that can act.
This interface defines an API for an Actor to interact with an EnvironmentLoop
(see acme.environment_loop), e.g. a simple RL loop where each step is of the
form:
# Make the first observation.
timestep = env.reset()
actor.observe_first(timestep.observation)
# Take a step a... | 3,302 | en | 0.853206 |
from random import randrange
from autokeras.bayesian import SearchTree, contain
from autokeras.net_transformer import transform
from autokeras.search import Searcher
class RandomSearcher(Searcher):
""" Class to search for neural architectures using Random search strategy.
Attributes:
search_tree: The... | nas/random.py | 2,508 | Class to search for neural architectures using Random search strategy.
Attributes:
search_tree: The network morphism search tree
Generate the next neural architecture.
Args:
multiprocessing_queue: the Queue for multiprocessing return value.
Returns:
list of 2-element tuples: generated_graph and other_info... | 686 | en | 0.791631 |
import cv2
from util.image_type import ColorImage
class VideoWriter:
"""
This class wraps a cv2.VideoWriter object,
preset some parameters so simpler to use.
"""
def __init__(self, video_path: str, fps: float = 10.0) -> None:
"""
Arguments:
video_path: The path to out... | util/video_writer.py | 972 | This class wraps a cv2.VideoWriter object,
preset some parameters so simpler to use.
Arguments:
video_path: The path to output the video.
fps: If higher than the writing rate, the video will be fast-forwarded.
Returns True if video writer has been successfully initialized.
Closes the video writer.
Writes the ne... | 335 | en | 0.815725 |
"""
The automcomplete example rewritten for bottle / gevent.
- Requires besides bottle and gevent also the geventwebsocket pip package
- Instead of a future we create the inner stream for flat_map_latest manually
"""
from bottle import request, Bottle, abort
import gevent
from geventwebsocket import WebSocketError
from... | examples/autocomplete/bottle_autocomplete.py | 2,366 | The automcomplete example rewritten for bottle / gevent.
- Requires besides bottle and gevent also the geventwebsocket pip package
- Instead of a future we create the inner stream for flat_map_latest manually
Only if text is longer than 2 characters Pause for 750ms Only if the value has changed like {'term': '<curren... | 381 | en | 0.734769 |
import pytest
from jina.drivers.rank import Chunk2DocRankDriver
from jina.executors.rankers import Chunk2DocRanker
from jina.hub.rankers.MaxRanker import MaxRanker
from jina.hub.rankers.MinRanker import MinRanker
from jina.proto import jina_pb2
class MockLengthRanker(Chunk2DocRanker):
def __init__(self, *args, *... | tests/unit/drivers/test_chunk2doc_rank_drivers.py | 7,542 | doc: 1 |- chunk: 2 | |- matches: (id: 4, parent_id: 40, score.value: 4), | |- matches: (id: 5, parent_id: 50, score.value: 5), | |- chunk: 3 |- matches: (id: 6, parent_id: 60, score.value: 6), |- matches: (id: 7, parent_id: 70, score.value: 7) to be used by MaxRanker and MinRanker doc: (id: 100, granularity=0) ... | 1,136 | en | 0.646141 |
import os
import sys
import numpy as np
import pandas as pd
import random
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import torch.nn.functional as F
import albumentations as A
from albumentations.pytorch.transforms impo... | src/test.py | 4,994 | orignal res for B5 test = '../data_256/test' train_labels = '../data/train_combined.csv' external = '../data/external_mal.csv' torch.cuda.manual_seed_all(seed) df_train = pd.read_csv(train_labels) df_ext = pd.read_csv(external) df_train = pd.concat([df_train, df_ext], ignore_index=True) Sex Features Age Features test_t... | 993 | en | 0.457876 |
import sublime
import os
import queue
import unittest
import unittesting
import tempfile
from Tutkain.api import edn
from Tutkain.src import repl
from Tutkain.src.repl import formatter
from Tutkain.src import base64
from Tutkain.src import test
from .mock import JvmBackchannelServer, JvmServer
from .util import Packa... | tests/test_client_jvm.py | 29,228 | @unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest@unittest.SkipTest TODO: ns here is unintuitive, should be baz.quux maybe? foo.bar baz.quux@unittest.SkipTest@unittest.SkipTest missing clos... | 2,205 | en | 0.495801 |
import os
import re
import sys
import json
import glob
import hashlib
import requests
import concurrent.futures as futures
from tqdm import tqdm
from zipfile import ZipFile
from datetime import datetime
from abd_model.core import load_config, Logs
from abd_model.tiles import tiles_from_csv, tiles_to_granules
def a... | abd_model/src/abd_model/tools/_sat.py | 8,679 | 42 related to Theia MD issue, dirty workaround Already Downloaded Auth issue Write issue | 88 | en | 0.93705 |
"""
GTSAM Copyright 2010-2020, Georgia Tech Research Corporation,
Atlanta, Georgia 30332-0415
All Rights Reserved
See LICENSE for the license information
Rules and classes for parsing a module.
Author: Duy Nguyen Ta, Fan Jiang, Matthew Sklar, Varun Agrawal, and Frank Dellaert
"""
# pylint: disable=unnecessary-lambd... | wrap/gtwrap/interface_parser/module.py | 1,591 | Module is just a global namespace.
E.g.
```
namespace gtsam {
...
}
```
Parse the source string and apply the rules.
GTSAM Copyright 2010-2020, Georgia Tech Research Corporation,
Atlanta, Georgia 30332-0415
All Rights Reserved
See LICENSE for the license information
Rules and classes for parsing a module.
Autho... | 565 | en | 0.526405 |
# Copyright (c) 2016 Mirantis 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, so... | tests/lib/copy_engines/test_bbcp_copier.py | 3,957 | Copyright (c) 2016 Mirantis 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, software distribut... | 546 | en | 0.887953 |
#!/usr/bin/env python
"""
Memory Loss
github.com/irlrobot/memory_loss
"""
from __future__ import print_function
from random import choice, shuffle
from alexa_responses import speech_with_card
from brain_training import QUESTIONS
def handle_answer_request(player_answer, session):
"""check if the answer is right, ad... | src/handle_answer_request.py | 1,664 | check if the answer is right, adjust score, and continue
log all questions answered incorrectly so i can analyze later
Memory Loss
github.com/irlrobot/memory_loss
!/usr/bin/env python | 184 | en | 0.790056 |
# Copyright 2015 OpenStack Foundation.
# 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... | neutron/tests/unit/common/test_rpc.py | 20,363 | Copyright 2015 OpenStack Foundation. 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 ... | 1,149 | en | 0.913593 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2017-02-17 20:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("scripts", "0007_auto_20150403_2339"), ("comms", "0010_auto_20161206_1912")]
operations = [
migrations.AddField(
mod... | evennia/comms/migrations/0011_auto_20170217_2039.py | 1,029 | -*- coding: utf-8 -*- Generated by Django 1.9.11 on 2017-02-17 20:39 | 68 | en | 0.680907 |
#
# (C) Copyright IBM Corp. 2018
#
# 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 writi... | pywren_ibm_cloud/compute/backends/ibm_cf/entry_point.py | 940 | (C) Copyright IBM Corp. 2018 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 distrib... | 550 | en | 0.865811 |
# libraries imported
import os
import pathlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# uses predict folder code to run predictor on entire folders
from predict_folder import predict_dir
def predict_dirs(model_type, target_prediction):
directory_name ... | predict_all_data.py | 7,054 | libraries imported uses predict folder code to run predictor on entire folders list holding all folders to use finds the directories puts all txt files' names in a list runs the prediction code for each folder prints the average metrics for all datasets bar chart properties data for plotting bar chart formats the lists... | 678 | en | 0.72494 |
#!/usr/bin/env python3
"""Example code that demonstrates using a button connected through the hat.
The button uses a hat pin through the sysfs driver illustrating the edge
detection polling.
The demo will light up the on board LED whenever PIN_D is drawn high.
"""
from signal import pause
from gpiozero import Button
... | src/examples/vision/gpiozero/bonnet_button.py | 864 | Example code that demonstrates using a button connected through the hat.
The button uses a hat pin through the sysfs driver illustrating the edge
detection polling.
The demo will light up the on board LED whenever PIN_D is drawn high.
!/usr/bin/env python3 Set up a gpiozero LED using the first onboard LED on the vis... | 588 | en | 0.81601 |
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
"""This is the IP Analyzer program for the AlteMatrix module."""
| AlteMatrix/ipanalyzer/__init__.py | 144 | Use of this source code is governed by the MIT license. | 55 | en | 0.725546 |
#!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utilities for PyAuto."""
import logging
import os
import shutil
import sys
import tempfile
import zipfile
class ExistingPathRepl... | chrome/test/pyautolib/pyauto_utils.py | 4,318 | !/usr/bin/python Copyright (c) 2010 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. dir to which existing content is backed up take a backup Reinstate, if backed up. Create intermediate dirs if needed. Extract files. dir file S... | 388 | en | 0.872688 |
"""
URLConf for OCR presets.
"""
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from ocradmin.presets import views
urlpatterns = patterns('',
(r'^builder/?$', login_required(views.builder)),
(r'^builder/(?P<pid>[^/]+)/?$', login_required(views.builder_doc_edit)),
... | ocradmin/presets/urls.py | 1,218 | URLConf for OCR presets. | 24 | en | 0.661796 |
import collections
import itertools
import re
import yaml
from ansible.errors import AnsibleError
from cumulus_vxconfig.utils.filters import Filters
from cumulus_vxconfig.utils import File, Network, Link, Inventory, Host
filter = Filters()
mf = File().master()
inventory = Inventory()
class CheckVars:
'''
Pr... | cumulus_vxconfig/utils/checkvars.py | 17,688 | Pre-Check of variables defined in master.yml
Check for bonds member conflict Check for bonds name conflict Check if assign vids exist in tenant vlans Check vlan subnet against base_networks Interfaces in links Interface in mlag bonds Interfaces peerlink Check for duplicate bonds per host Check if bond exist in rack p... | 457 | en | 0.72673 |
# Copyright 2020 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 agreed to... | model_zoo/mass/src/transformer/__init__.py | 1,330 | Transformer model module.
Copyright 2020 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... | 666 | en | 0.797047 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | google/cloud/talent_v4beta1/services/job_service/client.py | 46,231 | A service handles job management, including job CRUD,
enumeration and search.
Metaclass for the JobService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
Instantiate the job service client.
Args:
credentials (Op... | 23,910 | en | 0.773496 |
from ...Classes.Material import Material
from ...Functions.Material.compare_material import compare_material
def replace_material_pyleecan_obj(obj, mat1, mat2, comp_name_path=True):
"""
replace first material by the second in the object
Parameters
----------
obj: Pyleecan object
mat1: Materia... | pyleecan/Functions/Material/replace_material_pyleecan_obj.py | 2,010 | replace first material by the second in the object
Parameters
----------
obj: Pyleecan object
mat1: Material
material to replace
mat2: Material
new material
comp_name_path: bool
replace strictly mat1 or replace materials without comparing mat1.path and mat1.name
Returns
-------
is_change: bool
True if... | 577 | en | 0.501489 |
# Copyright (c) 2021 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 appli... | paddlex/ppdet/modeling/assigners/utils.py | 8,157 | Args:
points (Tensor, float32): shape[L, 2], "xy" format, L: num_anchors
bboxes (Tensor, float32): shape[B, n, 4], "xmin, ymin, xmax, ymax" format
eps (float): Default: 1e-9
Returns:
is_in_bboxes (Tensor, float32): shape[B, n, L], value=1. means selected
For each anchor, find the GT with the largest IOU... | 2,955 | en | 0.665141 |
#!/usr/bin/env python3
import sys
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'Hello from Python %s' % sys.version.encode('utf-8')]
| uwsgi-nginx-container/root/app/main.py | 203 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
import os
import logging
from mtkclient.Library.utils import LogBase
class damodes:
DEFAULT = 0
XFLASH = 1
class chipconfig:
def __init__(self, var1=None, watchdog=None, uart=None, brom_payload_addr=None,
da_payload_addr=None, pl_payload_addr=None, cqdma_base=None, sej_base=None, dxcc_b... | mtkclient/config/brom_config.py | 51,731 | Credits to cyrozap and Chaosmaster for some values var1 uart brom_payload_addr da_payload_addr gcpu_base sej_base cqdma_base ap_dma_mem blacklist var1 todo:check todo:check blacklist var1 watchdog uart brom_payload_addr da_payload_addr gcpu_base sej_base cqdma_base ap_dma_mem blacklist Smartwatch, confirmed no gcpu_bas... | 5,234 | en | 0.341946 |
import collections
from tensorflow.keras.losses import SparseCategoricalCrossentropy, BinaryCrossentropy
from tensorflow.keras.metrics import Mean, Accuracy
optimizer = SGD(lr=0.01, momentum=0.9, nesterov=True)
cce = SparseCategoricalCrossentropy()
bce = BinaryCrossentropy()
model.compile(
optimizer=optimizer,... | labs/10_unsupervised_generative_models/solutions/grl_training.py | 2,721 | Keras provide helpful classes to monitor various metrics: Fetch all trainable variables but those used uniquely for the digits classification: Training digits classifier & domain classifier on source: Training domain classifier on target: | 238 | en | 0.69002 |
"""Test module for detecting uncollectable garbage in PyTables.
This test module *must* be loaded in the last place. It just checks for
the existence of uncollectable garbage in ``gc.garbage`` after running
all the tests.
"""
import gc
from tables.tests import common
class GarbageTestCase(common.PyTablesTestCase... | tables/tests/test_garbage.py | 1,506 | Test for uncollectable garbage.
Return a test suite consisting of all the test cases in the module.
Checking for uncollectable garbage.
Test module for detecting uncollectable garbage in PyTables.
This test module *must* be loaded in the last place. It just checks for
the existence of uncollectable garbage in ``gc.ga... | 408 | en | 0.692662 |
import logging
import random
import re
from uuid import UUID
import dateutil.parser
import w3lib.url
from yarl import URL
from .captcha import CaptchaSolver
from .starbelly_pb2 import (
PatternMatch as PbPatternMatch,
PolicyRobotsTxt as PbPolicyRobotsTxt,
PolicyUrlRule as PbPolicyUrlRule
)
logger = logg... | starbelly/policy.py | 27,175 | A container for subpolicies.
Policy for authenticated crawling.
Limits on crawl size/duration.
Filter responses by MIME type.
Modify which proxies are used for each request.
Designate how robots.txt affects crawl behavior.
Customize URL normalization.
Customize link priorities based on URL.
Specify user agent s... | 6,046 | en | 0.566042 |
import os
from datetime import date, datetime, timedelta
from enum import Enum
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import Group
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.core.exceptions... | evap/staff/tools.py | 15,176 | Merges other_user into main_user
delete navbar cache from base.html for internal users only the part before the @ must be the same to match a user to an email pylint: disable=too-many-branches,too-many-locals user_file must have one user per line in the format "{username},{email}" This is much stuff to do. However, s... | 954 | en | 0.939928 |
"""
Consensus Algorithm for 6 Mobile robots using MLP Model for Line Graph Implementation
Inputs: Mx, My
Outputs: Ux, Uy
"""
import torch
import MLP_Model
import math
import numpy as np
import rclpy
from rclpy.node import Node
from tf2_msgs.msg import TFMessage
from std_msgs.msg import Float32
import time
L = 1
d =... | Real Topology Graph/GNN Model 1/Cyclic Graph/Main_MLP_line.py | 16,030 | Calculate Mx1, My1, ...... Mx6, My6
Consensus Algorithm for 6 Mobile robots using MLP Model for Line Graph Implementation
Inputs: Mx, My
Outputs: Ux, Uy
distance = 2 Adjancency Matrix fully connected case 6x6 6x1 controller vector 6x1 controller vector load model using dict in radiansChange according to topic in chi... | 2,290 | en | 0.740956 |
# Accessor functions for control properties
from Controls import *
import struct
# These needn't go through this module, but are here for completeness
def SetControlData_Handle(control, part, selector, data):
control.SetControlData_Handle(part, selector, data)
def GetControlData_Handle(control, part, selecto... | front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/Carbon/ControlAccessor.py | 1,902 | Accessor functions for control properties These needn't go through this module, but are here for completeness | 109 | en | 0.910312 |
# coding: utf-8
from __future__ import unicode_literals
from .spike import ParamountNetworkIE
class TVLandIE(ParamountNetworkIE):
IE_NAME = 'tvland.com'
_VALID_URL = r'https?://(?:www\.)?tvland\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
_FEED_URL = 'http://www.tvland.com/feeds/mrss/'
_... | youtube_dl/extractor/tvland.py | 1,468 | coding: utf-8 Geo-restricted. Without a proxy metadata are still there. With a proxy it redirects to http://m.tvland.com/app/ | 125 | en | 0.879787 |
from ..options import Option, OptionHandler
class LocaleOptionsMixin(OptionHandler):
"""
Mixin which adds a locale option to option handlers.
"""
# The locale to use
locale = Option(
help="the locale to use for parsing the numbers",
default="en_US"
)
| src/wai/spectralio/mixins/_LocaleOptionsMixin.py | 293 | Mixin which adds a locale option to option handlers.
The locale to use | 72 | en | 0.827626 |
"""Sets of metrics to look at the SRD metrics.
"""
import numpy as np
import healpy as hp
import rubin_sim.maf.metrics as metrics
import rubin_sim.maf.slicers as slicers
import rubin_sim.maf.stackers as stackers
import rubin_sim.maf.plots as plots
import rubin_sim.maf.metricBundles as mb
from .colMapDict import ColMapD... | rubin_sim/maf/batches/srdBatch.py | 18,317 | Metrics for evaluating proper motion and parallax.
Parameters
----------
colmap : dict or None, optional
A dictionary with a mapping of column names. Default will use OpsimV4 column names.
runName : str, optional
The name of the simulated survey. Default is "opsim".
nside : int, optional
Nside for the heal... | 3,786 | en | 0.652847 |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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 appl... | tensorflow_datasets/image_classification/i_naturalist2018/__init__.py | 748 | i_naturalist2018 dataset.
coding=utf-8 Copyright 2021 The TensorFlow Datasets 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... | 610 | en | 0.845809 |
# Copyright 2016, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | nuitka/codegen/ListCodes.py | 5,119 | Code generation for lists.
Right now only the creation is done here. But more should be added later on.
Copyright 2016, Kay Hayen, mailto:kay.hayen@gmail.com Part of "Nuitka", an optimizing Python compiler that is compatible and integrates with CPython, but also works on its own. Licensed under the A... | 921 | en | 0.899534 |
ADD_USER_ROLE = '''
INSERT INTO UserRole(roleId, userId) VALUES (
(SELECT id FROM Role WHERE name = :roleName),
:userId
)
'''
#
# User table queries
#
ADD_USER = '''
INSERT OR IGNORE INTO User(id, username) VALUES(:userId, :username)
'''
UPDATE_USERNAME = '''
UPDATE User... | bot/queries.py | 1,036 | User table queries Tag queries Image queries | 44 | en | 0.740261 |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... | intersight/model/compute_vmedia_relationship.py | 71,585 | 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... | 10,118 | en | 0.789239 |
import time
import RPi.GPIO as GPIO
from adafruit_servokit import ServoKit
'''GPIO.setmode(GPIO.BCM)
GPIO.setup(11,GPIO.OUT)
servo1=GPIO.PWM(11,50)
servo1.start(2)'''
h = ServoKit(channels=16)
#servo1.ChangeDutyCycle(12)
#kit.servo[0].angle
init = [0,90,20,0,180,160,170,180,60,0,0,150]
limitLo = [0,0,20,0,0,40,0,... | Store/robot-test-old/hand_shake.py | 1,341 | servo1.ChangeDutyCycle(12)kit.servo[0].angle function closedupshakedown | 71 | en | 0.092672 |
""" Modified from offical repo and mmlab's repo of HRNet
MIT License
Copyright (c) 2019 Microsoft
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 t... | ever/module/_hrnet.py | 24,850 | 3x3 convolution with padding
Modified from offical repo and mmlab's repo of HRNet
MIT License
Copyright (c) 2019 Microsoft
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, inclu... | 1,438 | en | 0.837701 |
from __future__ import print_function
import glob
import os
import datetime
import argparse
import json
import csv
import re
import pdb
import copy
import subprocess
import fnmatch
import textwrap
import sys
import tempfile
DEFAULT_BUILD_TAGS = "darwin,linux,windows"
# Get the beats repo root directory, making sure ... | script/generate_notice.py | 5,842 | read_go_deps returns a list of module dependencies in JSON format.
Main modules are excluded; only dependencies are returned.
Unlike `go list -m all`, this function excludes modules that are only
required for running tests.
Get the beats repo root directory, making sure it's downloaded first. notice_overrides holds ... | 629 | en | 0.767407 |
"""
Facebook platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.facebook/
"""
import logging
from aiohttp.hdrs import CONTENT_TYPE
import requests
import voluptuous as vol
from homeassistant.components.notify import (
... | homeassistant/components/notify/facebook.py | 2,757 | Implementation of a notification service for the Facebook service.
Initialize the service.
Get the Facebook notification service.
Send some message.
Facebook platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.facebook/
... | 459 | en | 0.807972 |
#!/usr/bin/env pvpython
# -*- Python -*- (syntax highlighting)
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infr... | examples/3d/subduction/viz/plot_faultdir.py | 4,442 | !/usr/bin/env pvpython -*- Python -*- (syntax highlighting) ---------------------------------------------------------------------- Brad T. Aagaard, U.S. Geological Survey Charles A. Williams, GNS Science Matthew G. Knepley, University at Buffalo This code was developed as part of the Computational Infrastructure for Ge... | 1,490 | en | 0.585914 |
import os
import shutil
from unittest import TestCase
from osbot_utils.utils.Files import folder_exists, temp_folder, file_exists, folder_temp, folder_delete_all, temp_file, \
file_copy
from cdr_plugin_folder_to_folder.pre_processing.utils.file_service import File_Service
from cdr_plugin_folder_to_folder.utils.te... | tests/unit/pre_processing/utils/test_File_service.py | 2,593 | test_folder="./test_data/test_files"new_folder=os.path.join(test_folder, "sample") | 82 | en | 0.178671 |
# -*- coding: utf-8 -*-
"""\
Copyright (c) 2015-2018, MGH Computational Pathology
"""
from __future__ import print_function
from calicoml.core.metrics import ppv, npv, ROC
from calicoml.core.metrics import compute_averaged_metrics, accuracy_from_confusion_matrix, ConditionalMeansSelector
from calicoml.core.metrics ... | tests/test_metrics.py | 8,423 | Tests the ROC for a single set of predictions. Mostly sanity checks since all the computation is done
by scikit, which we assume is correct
Test utility
test accuracy computations from confusion matrix
Validates the AUC confidence interval by comparing with R's pROC
Tests compute_averaged_metrics function
test Conditi... | 790 | en | 0.836485 |
# Copyright (C) 2016 Li Cheng at Beijing University of Posts
# and Telecommunications. www.muzixing.com
# Copyright (C) 2016 Huang MaChi at Chongqing University
# of Posts and Telecommunications, China.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compl... | build/lib.linux-x86_64-2.7/ryu/app/experiments/RUN-master/EFattree/network_monitor.py | 15,176 | Copyright (C) 2016 Li Cheng at Beijing University of Posts and Telecommunications. www.muzixing.com Copyright (C) 2016 Huang MaChi at Chongqing University of Posts and Telecommunications, China. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Licen... | 1,198 | en | 0.827132 |
"""engine.SCons.Tool.f03
Tool-specific initialization for the generic Posix f03 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2... | pdb2pqr-1.9.0/scons/scons-local-2.3.0/SCons/Tool/f03.py | 2,055 | engine.SCons.Tool.f03
Tool-specific initialization for the generic Posix f03 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, ... | 1,482 | en | 0.810919 |
"""add ondelete set null to question_repyl, tabled_committee_report and call_for_comment tables
Revision ID: 122a38429a58
Revises: 29cf770ce19b
Create Date: 2015-02-10 10:13:58.437446
"""
# revision identifiers, used by Alembic.
revision = '122a38429a58'
down_revision = '29cf770ce19b'
branch_labels = None
depends_on... | migrations/versions/122a38429a58_add_ondelete_set_null_to_question_repyl_.py | 1,118 | add ondelete set null to question_repyl, tabled_committee_report and call_for_comment tables
Revision ID: 122a38429a58
Revises: 29cf770ce19b
Create Date: 2015-02-10 10:13:58.437446
revision identifiers, used by Alembic. | 222 | en | 0.452473 |
#!/usr/bin/env python3
from aws_cdk import core
from arm64_wheel_tester_stack.arm64_wheel_tester_stack import Arm64WheelTesterStack
app = core.App()
Arm64WheelTesterStack(app, "arm64-github-testers", env={'region': 'us-east-1'})
app.synth()
| app.py | 246 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
#
# This file is part of pyasn1-alt-modules software.
#
# Created by Russ Housley
# Copyright (c) 2020-2022, Vigil Security, LLC
# License: http://vigilsec.com/pyasn1-alt-modules-license.txt
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import enc... | tests/test_rfc8737.py | 2,995 | This file is part of pyasn1-alt-modules software. Created by Russ Housley Copyright (c) 2020-2022, Vigil Security, LLC License: http://vigilsec.com/pyasn1-alt-modules-license.txt | 178 | en | 0.779681 |
from __future__ import absolute_import
import datetime
import jwt
import re
import json
import logging
from hashlib import md5 as _md5
from six.moves.urllib.parse import parse_qs, urlparse, urlsplit
from sentry.utils.cache import cache
from django.utils.encoding import force_bytes
from sentry.integrations.atlassian_... | src/sentry/integrations/jira/client.py | 8,225 | Contains the jira-cloud specifics that a JiraClient needs
in order to communicate with jira
Basic Caching mechanism for Jira metadata which changes infrequently
Use the request_hook method for our specific style of Jira to
add authentication data and transform parameters.
Used by Jira Client to apply the jira-cloud aut... | 1,266 | en | 0.897367 |
# Copyright 2020 The TensorFlow 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 applica... | tutorials/dp_optimizer_adp.py | 8,447 | Differentially private subclass of given class cls.
The class tf.keras.optimizers.Optimizer has two methods to compute
gradients, `_compute_gradients` and `get_gradients`. The first works
with eager execution, while the second runs in graph mode and is used
by canned estimators.
Internally, DPOptimizerClass stores hy... | 2,423 | en | 0.728372 |
# -*- coding: utf-8 -*-
# Copyright (C) 2014 ysitu <ysitu@users.noreply.github.com>
# All rights reserved.
# BSD license.
#
# Author: ysitu <ysitu@users.noreply.github.com>
"""
Algebraic connectivity and Fiedler vectors of undirected graphs.
"""
from functools import partial
import networkx as nx
from networkx.utils im... | venv/Lib/site-packages/networkx/linalg/algebraicconnectivity.py | 18,907 | Cholesky factorization.
To solve Ax = b:
solver = _CholeskySolver(A)
x = solver.solve(b)
optional argument `tol` on solve method is ignored but included
to match _PCGsolver API.
LU factorization.
To solve Ax = b:
solver = _LUSolver(A)
x = solver.solve(b)
optional argument `tol` on solve method is ig... | 8,842 | en | 0.737335 |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass, field as _field
from functools import partial
from ...config import custom_scalars, datetime
from numbers import Number
from typing import Any, AsyncGenerator, Dict, List, Generator, Optional
from dataclasses_jso... | cli/psym/graphql/input/edit_location_type_input.py | 781 | !/usr/bin/env python3 @generated AUTOGENERATED file. Do not Change! | 67 | en | 0.467907 |
"""
Test to verify performance of attaching number of pods as a bulk, each pod attached to one pvc only
The test results will be uploaded to the ES server
"""
import logging
import os
import pytest
import pathlib
import time
from concurrent.futures import ThreadPoolExecutor
from ocs_ci.framework.testlib import perform... | tests/e2e/performance/csi_tests/test_bulk_pod_attachtime_performance.py | 8,244 | Test to measure performance of attaching pods to pvc in a bulk
A setup phase for the test
Args:
interface_type: Interface type
storageclass_factory: A fixture to create everything needed for a storage class
Initialize the full results object which will send to the ES server
Args:
full_results (obj): an em... | 1,525 | en | 0.871708 |
import datetime
import logging
import os
import elastalert.elastalert
import elastalert.utils.util
import mock
import pytest
from elastalert import config
from elastalert.ruletypes import AnyRule
from elastalert.utils.time import dt_to_ts, ts_to_dt
writeback_index = "wb"
def pytest_addoption(parser):
parser.add... | tests/conftest.py | 9,509 | py.test fixture to get a fresh mutable environment.
Prevent logging handlers from capturing temporary file handles.
For example, a test that uses the `capsys` fixture and calls
`logging.exception()` will initialize logging with a default handler that
captures `sys.stderr`. When the test ends, the file handles will be... | 596 | en | 0.765023 |
"""A Couchbase CLI subcommand"""
import getpass
import inspect
import ipaddress
import json
import os
import platform
import random
import re
import string
import subprocess
import sys
import urllib.parse
import tempfile
import time
from typing import Optional, List, Any, Dict
from argparse import ArgumentError, Arg... | cbmgr.py | 267,215 | The analytics link setup subcommand
BackupService class is a subcommand that will contain other commands to configure the service as well as manage
it. This approach attempts to make the interface more intuitive by keeping a hierarchical structure where the
service can have all its options under one command instead of ... | 12,170 | en | 0.786019 |
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import datetime
import json
import os
import random
import time
from collections import namedtuple
from copy import deepcop... | main.py | 26,866 | Helper function to build the list of evaluators for a given dataset
Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved Dataset specific Training hyper-parameters Model parameters Backbone Tran... | 1,375 | en | 0.783051 |
from lark import Lark
_name_parser = Lark("""
?start : name
name : var*
var : gen _extras
_extras : (sub _extras_sub) | (sup _extras_sup) | (prime _extras) | ()
_extras_sub : (sup [prime]) | (prime _extras_sub) | ()
_extras_sup : (sub [prime]) | (prime _extras_sup) | ()
prime :... | python_ext/webserver/spectralsequences_webserver/name_tools.py | 3,286 | Write x^n but handle special cases x^0 ==> 1 and x^1 ==> x if var.find("'") > -1: var = f"({var})" | 102 | en | 0.374598 |
# ---------------------------------------------------------------------
#
# Copyright (c) 2012 University of Oxford
#
# 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, incl... | datastage/web/documentation/urls.py | 1,448 | --------------------------------------------------------------------- Copyright (c) 2012 University of Oxford 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 ... | 1,204 | en | 0.814259 |
#!/usr/bin/python
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
im... | tests/python/pants_test/tasks/false.py | 417 | !/usr/bin/python coding=utf-8 Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). Licensed under the Apache License, Version 2.0 (see LICENSE).This works just like /bin/false, but Windows users might not have that | 226 | en | 0.73735 |
from django.http import HttpRequest
from typing import Optional, Text
from zerver.lib.actions import check_send_stream_message, \
check_send_private_message
from zerver.lib.exceptions import StreamDoesNotExistError
from zerver.lib.request import REQ, has_request_variables
from zerver.models import UserProfile
@h... | zerver/lib/webhooks/common.py | 1,353 | A PM will be sent to the bot_owner by check_message, notifying that the webhook bot just tried to send a message to a non-existent stream, so we don't need to re-raise it since it clutters up webhook-errors.log | 210 | en | 0.908801 |
# -*- coding: utf-8 -*-
import json
from urllib import quote
from twisted.internet.defer import inlineCallbacks
from vumi.message import TransportUserMessage
from vumi.tests.helpers import VumiTestCase
from vumi.transports.httprpc.tests.helpers import HttpRpcTransportHelper
from vumi.tests.utils import LogCatcher
fr... | vxaat/tests/test_ussd.py | 13,607 | -*- coding: utf-8 -*- Send initial request Send initial request Send initial request | 84 | en | 0.706115 |
# Copyright 2012 Nebula, 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 agree... | horizon/forms/fields.py | 15,960 | A subclass of ``ChoiceField`` with additional properties that make
dynamically updating its elements easier.
Notably, the field declaration takes an extra argument, ``add_item_link``
which may be a string or callable defining the URL that should be used
for the "add" link associated with the field.
A subclass of the `... | 4,847 | en | 0.778312 |
"""
Timings against numpy/itk/nibabel/etc where appropriate
"""
import os
import nibabel as nib
import itk
import ants
import time
def time_nifti_to_numpy(N_TRIALS):
"""
Times how fast a framework can read a nifti file and convert it to numpy
"""
datadir = os.path.join(os.path.dirname(os.path.realpa... | tests/timings.py | 1,534 | Times how fast a framework can read a nifti file and convert it to numpy
Timings against numpy/itk/nibabel/etc where appropriate | 128 | en | 0.829144 |
'''In Repetition Based on User Input, you saw a loop that prompted users until they typed quit. This code won’t work if users type Quit, or QUIT, or any other version that isn’t exactly quit. Modify that loop so that it terminates if a user types that word with any capitalization.'''
text = ""
while text.lower()!= ... | chapter09/exercise06.py | 508 | In Repetition Based on User Input, you saw a loop that prompted users until they typed quit. This code won’t work if users type Quit, or QUIT, or any other version that isn’t exactly quit. Modify that loop so that it terminates if a user types that word with any capitalization. | 280 | en | 0.86576 |
# -*- coding: utf-8 -*- #
# Copyright 2021 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 requir... | lib/surface/vmware/nodetypes/__init__.py | 1,153 | Show node types in Google Cloud VMware Engine.
Show node types in Google Cloud VMware Engine.
The command group for the vmware nodetypes CLI.
-*- coding: utf-8 -*- Copyright 2021 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compl... | 735 | en | 0.847148 |
"""
This file offers the methods to automatically retrieve the graph Elusimicrobia bacterium RIFOXYC2_FULL_34_12.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING ... | bindings/python/ensmallen/datasets/string/elusimicrobiabacteriumrifoxyc2full3412.py | 3,583 | Return new instance of the Elusimicrobia bacterium RIFOXYC2_FULL_34_12 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True
Whether to ... | 2,756 | en | 0.698828 |
import os
import math
import argparse
import pickle
import torch
import torch.distributed as dist
from torch.nn import Parameter
import torch.nn.functional as F
from sparse_coo_tensor_cpp import sparse_coo_tensor_gpu, spmm_gpu
import utils
from dist_data import DistData
run = 0
def outer_product2(inputs, ag):
... | 1D_CAGNET/dist_1d.py | 12,369 | (H^(l-1))^T * (A * G^l), 'comp'), 'comm') g_logger.log('p2p bcast skip', src, dst) non zero g_logger.log('p2p data ready', src, dst, 'needed size',p2p_buf.size(0), 'full size', t.size(0)) g_logger.log('p2p bcast done', src, dst) g_logger.log('p2p dst done', src, dst) layer2_use_cache = False g_logger.log(cur_epoch, i,... | 1,132 | en | 0.307772 |
#This code aims to return an "n" result of the Fibonnachi Sequence.
#Below are two fucntions, each of which return the same results by following different algorithms.
def getFibNExt (n):
fibAr = [0, 1, 0]
for i in range(n-1):
fibAr[2] = fibAr[0]
fibAr[0] += fibAr[1]
fibAr[1] = fibAr[2]
... | fibonnachiSequence.py | 1,431 | This code aims to return an "n" result of the Fibonnachi Sequence.Below are two fucntions, each of which return the same results by following different algorithms.Since the fibonnachi numbers are a recursive sum of all the numbers of the set prior to them we can rely on recursion to get the value of the set. | 309 | en | 0.916815 |
# 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 warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | sdk/python/pulumi_okta/group_memberships.py | 9,984 | The set of arguments for constructing a GroupMemberships resource.
:param pulumi.Input[str] group_id: ID of a Okta group.
:param pulumi.Input[Sequence[pulumi.Input[str]]] users: The list of Okta user IDs which the group should have membership managed for.
Input properties used for looking up and filtering GroupMembersh... | 3,988 | en | 0.777791 |
#-*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import logging
import os
import posixpath
import warnings
import django
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import UploadedFile
from django.db import models
from django.template.defaultfil... | private_storage/fields.py | 4,202 | Filefield with private storage, custom filename and size checks.
Extra settings:
- ``upload_subfolder``: a lambda to find the subfolder, depending on the instance.
- ``content_types``: list of allowed content types.
- ``max_file_size``: maximum file size.
-*- coding: utf-8 -*- content_type is only available for uploa... | 771 | en | 0.873613 |
import torch.nn as nn
import math
import torch
import torch.nn.functional as F
def conv_bn(inp, oup, stride, k_size=3):
return nn.Sequential(
nn.Conv2d(inp, oup, k_size, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.PReLU()
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
... | mobileFacenet_48_PReLU.py | 8,838 | self.depthwise = nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=(7,6),stride=1, padding=0, groups=in_channels, bias=False)x = self.batch_norm_in(x) add some channelwise gating? add some channelwise gating?self.conv.append(nn.MaxPool2d(kernel_size=(3, 3), stride=stride, padding=1))self.conv.app... | 939 | en | 0.542453 |
# Databricks notebook source
# COMMAND ----------
# Instrument for unit tests. This is only executed in local unit tests, not in Databricks.
if 'dbutils' not in locals():
import databricks_test
databricks_test.inject_variables()
# COMMAND ----------
assert dbutils.widgets.get("input") == "input_value"
| Python/packages/databricks-test/tests/patch_notebook.py | 315 | Databricks notebook source COMMAND ---------- Instrument for unit tests. This is only executed in local unit tests, not in Databricks. COMMAND ---------- | 153 | en | 0.796791 |
import subprocess
from collections import OrderedDict
from io import StringIO
from itertools import product
def _parse_categorical(line):
# Categorical Lines consist of:
#
# <name><w*>{<values>}<w*>[<default>]<*w>#Comment
# where:
# <name> - name of parameter.
# <values> - comma seperated list... | autotabular/metalearning/optimizers/optimizer_base.py | 3,097 | Build a grid represented as a list of parameter dictionaries.
Categorical Lines consist of: <name><w*>{<values>}<w*>[<default>]<*w>Comment where: <name> - name of parameter. <values> - comma seperated list of values (i.e. a,b,c,d...,z) <default> - default value enclosed in braces. <w*> - zero or more whitespace chara... | 741 | en | 0.544178 |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from builtins import str
from collections import namedtuple
from textwrap impor... | tests/python/pants_test/build_graph/test_build_file_parser.py | 15,296 | Exception handling code depends on the fact that all explicit exceptions from BuildFileParser
are subclassed from the BuildFileParserError base class.
Demonstrate that unicode characters causing parse errors raise real parse errors.
Demonstrates that a string containing unicode should work in a BUILD file.
coding=utf... | 975 | en | 0.843166 |
from __future__ import absolute_import, division, print_function
import six
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
from mpl_toolkits.axes_grid1 import host_subplot
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid... | venv/lib/python2.7/site-packages/mpl_toolkits/tests/test_axes_grid1.py | 6,121 | the random data the scatter plot: create new axes on the right and on the top of the current axes The first argument of the new_vertical(new_horizontal) method is the height (width) of the axes to be created in inches. now determine nice limits by hand: Purely cosmetic font changes (avoid overlap) Unmodified host subpl... | 692 | en | 0.825909 |
"""
Off Multipage Cheatsheet
https://github.com/daniellewisDL/streamlit-cheat-sheet
@daniellewisDL : https://github.com/daniellewisDL
"""
import streamlit as st
from pathlib import Path
import base64
from modules.toc import *
# Initial page config
st.set_page_config(
page_title='Code Compendium Intro Page',
... | .history/pages/intro_20220303154534.py | 8,853 | Off Multipage Cheatsheet
https://github.com/daniellewisDL/streamlit-cheat-sheet
@daniellewisDL : https://github.com/daniellewisDL
Initial page config initial_sidebar_state="expanded", col2.title("Table of contents") col2.write("http://localhost:8502/display-progress-and-status") toc.header("Header 1") toc.header("He... | 5,967 | en | 0.25633 |
"""This module contains common functions-helpers of the client and agents.
Copyright (c) 2018 http://reportportal.io .
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/... | reportportal_client/helpers.py | 2,563 | Generate list of attributes for the API request.
Example of input list:
['tag_name:tag_value1', 'tag_value2']
Output of the function for the given input list:
[{'key': 'tag_name', 'value': 'tag_value1'}, {'value': 'tag_value2'}]
:param rp_attributes: List of attributes(tags)
:return: Correctly created li... | 1,359 | en | 0.719846 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-08 12:24
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [("campusonline", "0010_auto_20171002_1450")]
forward = [
"""
... | src/outpost/django/campusonline/migrations/0011_events.py | 1,911 | -*- coding: utf-8 -*- Generated by Django 1.11.5 on 2017-09-08 12:24 | 68 | en | 0.697131 |
def neighbord_analysis(x_as, column = 0):
"""
Given an array xas this function compute the distance between the elements the mean distance and the variance
Author: Michele Monti
Args:
x_as: the name of the list or data set that you want:
Kwargs:
column: is the column of the data set that you need to ana... | amolf/numerical_data_analysis/NeighbourAnalysis.py | 843 | Given an array xas this function compute the distance between the elements the mean distance and the variance
Author: Michele Monti
Args:
x_as: the name of the list or data set that you want:
Kwargs:
column: is the column of the data set that you need to analyze
Returns:
mean_distanc... | 504 | en | 0.901992 |
"""
Copyright (c) 2018 Doyub Kim
I am making my contributions/submissions to this project solely in my personal
capacity and am not conveying any rights to any intellectual property of any
third parties.
"""
import pyjet
import unittest
import numpy as np
class ParticleSystemData2Tests(unittest.TestCase):
def t... | src/tests/python_tests/particle_system_data_tests.py | 4,790 | Copyright (c) 2018 Doyub Kim
I am making my contributions/submissions to this project solely in my personal
capacity and am not conveying any rights to any intellectual property of any
third parties. | 200 | en | 0.869416 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
The RPM-related plugins need to be composed in a specific way with one
another, and with the plugin that handles sh... | antlir/nspawn_in_subvol/plugins/rpm.py | 6,074 | The RPM-related plugins need to be composed in a specific way with one
another, and with the plugin that handles shadowing proxied binaries.
This here is the easiest implementation, which is simple at the cost of
tight coupling.
TECH DEBT ALERT: As we add support for other plugins and package managers,
this will no l... | 2,402 | en | 0.887959 |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.backend.python.subsystems.ipython import IPython
from pants.backend.python.util_rules.local_dists import LocalDistsPex, LocalDistsPexRequest
from pants.backend.python.... | src/python/pants/backend/python/goals/repl.py | 5,683 | Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). Licensed under the Apache License, Version 2.0 (see LICENSE). Note that we get an intermediate PexRequest here (instead of going straight to a Pex) so that we can get the interpreter constraints for use in local_dists_request. Note that we get an intermed... | 472 | en | 0.840249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.