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 |
|---|---|---|---|---|---|---|
import setuptools
import label_studio
print('Label Studio', label_studio.__version__)
# Readme
with open('README.md', 'r') as f:
long_description = f.read()
# Module dependencies
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name='label-studio',
version=l... | setup.py | 1,079 | Readme Module dependencies | 26 | en | 0.097728 |
from caffe_all import *
def parseProtoString(s):
from google.protobuf import text_format
proto_net = pb.NetParameter()
text_format.Merge(s, proto_net)
return proto_net
def get_param(l, exclude=set(['top', 'bottom', 'name', 'type'])):
if not hasattr(l,'ListFields'):
if hasattr(l,'__delitem... | src/load.py | 1,956 | Guess the input dimension | 25 | en | 0.52384 |
import secrets
import os
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort
from blog import app, db, bcrypt, mail
from blog.forms import (RegistrationForm, LoginForm, UpdateAccountForm, PostForm, \
RequestResetForm, ResetPasswordForm)
from blog.mod... | blog/routes.py | 7,755 | accessible only if logged in recipients=[user.email]) | 53 | en | 0.508633 |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | pytorch_lightning/trainer/training_loop.py | 43,077 | Extract required information from batch or epoch end results.
Args:
outputs: A 3-dimensional list of ``Result`` objects with dimensions:
[optimizer outs][batch outs][tbptt steps].
batch_mode: If True, ignore the batch output dimension.
Returns:
The cleaned outputs with ``Result`` objects converte... | 8,406 | en | 0.732106 |
# coding: utf-8
import gettext
# Make the gettext function _() available in the global namespace, even if no i18n is in use
gettext.install("bookworm", names=["ngettext"])
| bookworm/__init__.py | 174 | coding: utf-8 Make the gettext function _() available in the global namespace, even if no i18n is in use | 104 | en | 0.578149 |
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from ...utils.api_object import APIObject
if TYPE_CHECKING:
from ..message.emoji import Emoji
@dataclass
class... | pincer/objects/message/reaction.py | 630 | Represents a Discord Reaction object
:param count:
times this emoji has been used to react
:param me:
whether the current user reacted using this emoji
:param emoji:
emoji information
Copyright Pincer 2021-Present Full MIT License can be found in `LICENSE` at the project root. | 294 | en | 0.701296 |
"""
.. module:: category_encoders
:synopsis:
:platform:
"""
from category_encoders.backward_difference import BackwardDifferenceEncoder
from category_encoders.binary import BinaryEncoder
from category_encoders.count import CountEncoder
from category_encoders.hashing import HashingEncoder
from category_encoders.h... | category_encoders/__init__.py | 1,448 | .. module:: category_encoders
:synopsis:
:platform: | 55 | en | 0.091829 |
# Copyright 2017 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... | tensorflow/python/kernel_tests/signal/spectral_ops_test.py | 15,849 | Computes the gradient of the STFT with respect to `signal`.
Test that spectral_ops.stft has a working gradient.
Test that inverse_stft_window_fn has unit gain at each window phase.
Test inverse_stft_window_fn in special overlap = 3/4 case.
Test that spectral_ops.stft/inverse_stft match a NumPy implementation.
Tests for... | 2,624 | en | 0.863775 |
import pytest
from api.providers.permissions import GroupHelper
from osf_tests.factories import (
ReviewActionFactory,
AuthUserFactory,
PreprintFactory,
PreprintProviderFactory,
)
from osf.utils import permissions as osf_permissions
@pytest.mark.django_db
class ReviewActionCommentSettingsMixin(object... | api_tests/reviews/mixins/comment_settings.py | 3,089 | admin always sees comment/creator moderator always sees comment/creator node admin sees what the settings allow | 111 | en | 0.848968 |
import unittest
from streamlink.buffers import Buffer, RingBuffer
class TestBuffer(unittest.TestCase):
def setUp(self):
self.buffer = Buffer()
def test_write(self):
self.buffer.write(b"1" * 8192)
self.buffer.write(b"2" * 4096)
self.assertEqual(self.buffer.length, 8192 + 4096... | tests/test_buffer.py | 3,638 | Objects should be reusable after write() | 40 | en | 0.893759 |
import os
import rasterio
import mercantile
import numpy as np
import pytest
from tempfile import NamedTemporaryFile, TemporaryDirectory
from affine import Affine
from unittest import TestCase
from unittest.mock import patch
from datetime import datetime
from shapely.geometry import Polygon
from rasterio.enums impo... | tests/test_georaster_tiling.py | 24,594 | manual testing To be run manually only.
GeoRaster2 get tile tests.
GeoRaster2 Tiles general tests.
See https://publicgitlab.satellogic.com/telluric/telluric/issues/58 load the image data load the image data in pixels r1 == r2 doesn't work, see https://github.com/satellogic/telluric/issues/79 r1c == r2c doesn't wo... | 848 | en | 0.802135 |
from plotly.basedatatypes import BaseTraceType
import copy
class Splom(BaseTraceType):
# customdata
# ----------
@property
def customdata(self):
"""
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note that,
"scatt... | venv/lib/python3.7/site-packages/plotly/graph_objs/_splom.py | 54,315 | Construct a new Splom object
Splom traces generate scatter plot matrix visualizations. Each
splom `dimensions` items correspond to a generated axis. Values
for each of those dimensions are set in `dimensions[i].values`.
Splom traces support all `scattergl` marker style attributes.
Specify `layout.grid` attributes and/... | 27,308 | en | 0.672511 |
import time
from bs4 import BeautifulSoup
import requests
import json
from datetime import datetime, timedelta
import psycopg2
import smtplib
import os
DATABASE = os.environ["DATABASE"]
USER = os.environ["USER"]
PASSWORD = os.environ["PASSWORD"]
HOST = os.environ["HOST"]
def send_email(message: str)... | vaccines.py | 3,474 | Infinite loop of every 10min requests to Vilnius vaccination center.
Collects count of vaccines and adds to PostgreSQL database.
Sends an email if Pfizer vaccine is available.
Sends an email to target email with given message.
Args:
message (str): message you're sending
Connect to DB Time | 295 | en | 0.718913 |
# 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/keyvault/azure-mgmt-keyvault/azure/mgmt/keyvault/v2016_10_01/aio/operations_async/__init__.py | 622 | 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 cause incorr... | 452 | en | 0.550672 |
# Lint as: python3
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | tensorflow_model_analysis/api/model_eval_lib.py | 45,383 | Class for results from multiple model analysis run.
CombineFn to combine dictionaries generated by different evaluators.
Performs Extractions and Evaluations in provided order.
PTransform for performing extraction, evaluation, and writing results.
Users who want to construct their own Beam pipelines instead of using t... | 15,395 | en | 0.744419 |
#coding:utf-8
#
# id: bugs.core_5275
# title: CORE-5275: Expression index may become inconsistent if CREATE INDEX was interrupted after b-tree creation but before commiting
# decription:
# This test (and CORE- ticket) has been created after wrong initial implementation of test for ... | tests/bugs/core_5275_test.py | 17,632 | coding:utf-8 id: bugs.core_5275 title: CORE-5275: Expression index may become inconsistent if CREATE INDEX was interrupted after b-tree creation but before commiting decription: This test (and CORE- ticket) has been created after wrong initial implementation of test for CORE-1746. ... | 14,141 | en | 0.516854 |
from odroid_go import GO
from .Block import Block
from .Snake import Snake
SNAKE_COLOR = GO.lcd.colors.GREEN
BACKGROUND_COLOR = GO.lcd.colors.BLACK
FOOD_COLOR = GO.lcd.colors.RED
BORDER_COLOR = GO.lcd.colors.WHITE
SCREEN_WIDTH = 320
SCREEN_HEIGHT = 240
BLOCK_SIZE = 10
#Where borders are drawn
INIT_X = 0
INIT_Y = 20
... | src/snake/Entities/Globals.py | 1,343 | Where borders are drawnInitial position of snake; relative to bordersInitial direction of snakeDirections1: Forward2: Backward3: Left4: Right | 141 | en | 0.81997 |
"""
Tests for Reactions
"""
from src.common import constants as cn
from src.common.simple_sbml import SimpleSBML
from src.common import simple_sbml
from src.common.function_definition import FunctionDefinition
from tests.common import helpers
import copy
import libsbml
import numpy as np
import unittest
IGNORE_TEST ... | tests/common/test_function_definition.py | 812 | Tests for Reactions
Tests | 27 | en | 0.892553 |
from typing import FrozenSet
from collections import Iterable
from math import log, ceil
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msa... | benchmarks/f3_wrong_hints/scaling_ltl_timed_transition_system/15-sender_receiver_10.py | 18,657 | invar delta >= 0 delta > 0 -> (r2s' = r2s & s2r' = s2r) (G F !s.stutter) -> G (s.wait_ack -> F s.send) send & c = 0 & msg_id = 0 invar: wait_ack -> c <= timeout delta > 0 | stutter -> l' = l & msg_id' = msg_id & timeout' = timeout & c' = c + delta & out_c' = out_c (send & send') -> (msg_id' = msg_id & timeout' = base_t... | 858 | en | 0.254738 |
'''
Deals with the actual detection of signals in multichannel audio files.
There are two problems that need to solved while detecting a signal of interest.
#. within-channel signal detection
#. across-channel correspondence matching
Within-channel signal detection
-------------------------------
This task in... | batracker/signal_detection/detection.py | 8,105 | Parameters
----------
multichannel : np.array
Msamples x Nchannels audio data
fs : float >0
detector_function : function, optional
The function used to detect the start and end of a signal.
Any custom detector function can be given, the compulsory inputs
are audio np.array, sample rate and the functio... | 4,524 | en | 0.747423 |
# coding: utf-8
"""
Run the tests.
$ pip install nose (optional)
$ cd swagger_client-python
$ nosetests -v
"""
import os
import sys
import time
import unittest
import swagger_client
from swagger_client.rest import ApiException
class ApiExceptionTests(unittest.TestCase):
def setUp(self):
self.api_clien... | samples/client/petstore/python/tests/test_api_exception.py | 2,745 | Run the tests.
$ pip install nose (optional)
$ cd swagger_client-python
$ nosetests -v
coding: utf-8 | 102 | en | 0.479007 |
# reimplementation of https://github.com/guillaumegenthial/tf_ner/blob/master/models/lstm_crf/main.py
import functools
import json
import logging
from pathlib import Path
import sys
import numpy as np
import tensorflow as tf
# tf.enable_eager_execution()
from tf_metrics import precision, recall, f1
DATADIR = "../../.... | src/model/lstm_crf/main.py | 10,628 | Enumerator to enumerate through words_file and associated tags_file one line at a time
:param words_file: file path of the words file (one sentence per line)
:param tags_file: file path of tags file (tags corresponding to words file)
:return enumerator that enumerates over the format (words, len(words)), tags one line... | 2,092 | en | 0.729055 |
# -*- coding: utf-8 -*-
"""Assignment Day :13
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1hCwbVUHmWUKYdN7xNNeZcze9aGEmlGKz
"""
# Q1.
#Remove the hardcoded part from the code with the help of configparser
import os
from configparser import Con... | assignment_day_13.py | 1,236 | Assignment Day :13
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1hCwbVUHmWUKYdN7xNNeZcze9aGEmlGKz
-*- coding: utf-8 -*- Q1.Remove the hardcoded part from the code with the help of configparserQ2The question has been asked in an interviewPlease writ... | 438 | en | 0.942958 |
# -*- coding: utf-8 -*-
"""
pygments.lexers.smalltalk
~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Smalltalk and related languages.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, include, bygroups, defa... | Python/Django/rest_framework/1_serialization/env/lib/python2.7/site-packages/pygments/lexers/smalltalk.py | 7,215 | For `Newspeak <http://newspeaklanguage.org/>` syntax.
.. versionadded:: 1.1
For `Smalltalk <http://www.smalltalk.org/>`_ syntax.
Contributed by Stefan Matthias Aust.
Rewritten by Nils Winter.
.. versionadded:: 0.10
pygments.lexers.smalltalk
~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Smalltalk and related languages.
:copy... | 711 | en | 0.772801 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import time
import numpy as np
import math
import os
# gene[f][c] f:function type, c:connection (nodeID)
class Individual(object):
def __init__(self, net_info, init):
self.net_info = net_info
self.gene = np.zeros((self.net_info.node_num + ... | cgp.py | 17,757 | !/usr/bin/env python -*- coding: utf-8 -*- gene[f][c] f:function type, c:connection (nodeID) In the case of starting only convolution generate initial individual randomly initial architecture i.e. input layer *do not connect with these ids building convolution net output layer intermediate node type gene connec... | 1,188 | en | 0.704489 |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
===========================
Many python developers think of registry keys as if they were python keys in a
dictionary which is not the case. The windows registry is broken down into the
following components:
-----
Hives
-----
This is the top level of the regis... | salt/states/reg.py | 12,225 | Load this state if the reg module exists
split the hive from the key
Ensure a registry value is removed. To remove a key use key_absent.
:param str name: A string value representing the full path of the key to
include the HIVE, Key, and all Subkeys. For example:
``HKEY_LOCAL_MACHINE\SOFTWARE\Salt``
Valid hive values... | 6,099 | en | 0.630555 |
import os
import click
import numpy as np
from tqdm import tqdm
from models.model_loader import load_model
from torchvision.transforms import Compose
from dataset.data_transform import Resize, Rotation, ElasticAndSine, ColorGradGausNoise, AddWidth, Normalize, ToGray, OnlyElastic, OnlySine, ColorGrad, ColorGausNoise
fro... | train.py | 35,432 | was e-3@click.option('--lr-decay', type=float, default=1e-4, help='Base learning rate') was 0.0001print(train_base_dir)print(sorted(lexicon.items(), key=operator.itemgetter(1)))else: train_data = TestDataset(transform=transform, abc=abc).set_mode("train") synth_eval_data = TestDataset(transform=transform, abc=ab... | 894 | en | 0.301815 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | src/image-gallery/azext_image_gallery/custom.py | 5,772 | -------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. ----------------------------------------------------------------------------... | 641 | en | 0.537005 |
from unittest.mock import MagicMock
from django.core.exceptions import ValidationError
from users.backends import DakaraModelBackend
from users.tests.base_test import UsersAPITestCase, config_email_disabled
class DakaraModelBackendTestCase(UsersAPITestCase):
"""Test the authentication backend."""
def setUp... | dakara_server/users/tests/test_backends.py | 3,093 | Test the authentication backend.
Test to authenticate an inactive user.
Test to authenticate when not validated by email.
Test to authenticate when not validated by email and emails disabled.
Test to authenticate when not validated by manager.
Test to authenticate.
Test to authenticate as superuser.
create a user wit... | 335 | en | 0.829266 |
#!/usr/bin/env python3
# Macaw
#
# Testing file open and string concatenation.
import random
import pkgutil
def main():
# This dictionary of words is for testing only and should *not* be considered secure.
# Courtesy of https://gist.github.com/deekayen/4148741
#f = open('dictionary.txt')
f = pkgutil... | macaw/macaw.py | 1,422 | !/usr/bin/env python3 Macaw Testing file open and string concatenation. This dictionary of words is for testing only and should *not* be considered secure. Courtesy of https://gist.github.com/deekayen/4148741f = open('dictionary.txt') grab a random word from the dictionary file.concat that word to the end of the passwo... | 323 | en | 0.79725 |
"""
Django settings for hotelrooms project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os... | hotelrooms/hotelrooms/settings.py | 4,024 | Django settings for hotelrooms project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
Build paths insi... | 1,166 | en | 0.653058 |
from math import ceil
import datetime
from altair import Chart # type: ignore
import pandas as pd # type: ignore
import numpy as np
from .parameters import Parameters
from .utils import add_date_column
from .presentation import DATE_FORMAT
def new_admissions_chart(
alt, projection_admits: pd.DataFrame, param... | src/penn_chime/charts.py | 5,321 | docstring
:param chart: Chart: The alt chart to be used in finding max points
:param suffix: str: The assumption is that the charts have similar column names.
The census chart adds " Census" to the column names.
Make sure to include a space or underscore as appropriate
:return: str: Return... | 629 | en | 0.69898 |
import shlex
import string
import sys
from contextlib import contextmanager
from typing import Any, Callable, Generic, List, Optional, Tuple, Type, TypeVar, cast
import pytest
import simple_parsing
from simple_parsing import ConflictResolution, DashVariant, ParsingError
from simple_parsing.utils import camel_case
fro... | test/testutils.py | 8,577 | Basic setup for a test.
Keyword Arguments:
arguments {Optional[str]} -- The arguments to pass to the parser (default: {""})
dest {Optional[str]} -- the attribute where the argument should be stored. (default: {None})
Returns:
{cls}} -- the class's type.
Replace the start with `prog`, since the test runn... | 575 | en | 0.626653 |
from __future__ import annotations
import copy
import logging
from collections import defaultdict
from pathlib import Path
from rasa.nlu.featurizers.featurizer import Featurizer
import numpy as np
import scipy.sparse
import tensorflow as tf
from typing import Any, Dict, List, Optional, Text, Tuple, Union, Type
from ... | rasa/nlu/classifiers/diet_classifier.py | 70,452 | A multi-task model for intent classification and entity extraction.
DIET is Dual Intent and Entity Transformer.
The architecture is based on a transformer which is shared for both tasks.
A sequence of entity labels is predicted through a Conditional Random Field (CRF)
tagging layer on top of the transformer output seq... | 11,273 | en | 0.855674 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Entry',
fields=[
('id', models.AutoField(verbos... | blog/migrations/0001_initial.py | 603 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Copyright 2020 The FedLearner 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... | fedlearner/trainer/sparse_estimator.py | 11,681 | Copyright 2020 The FedLearner 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 ... | 723 | en | 0.819866 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import math
from warnings import warn
try:
import numpy
except ImportError:
numpy = None
try:
from numpy.linalg import svd as singular_value_decomposition
except ImportError:... | util_common/nlp/Sumy/summarizers/lsa.py | 4,340 | Computes TF metrics for each sentence (column) in the given matrix.
You can read more about smoothing parameter at URL below:
http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html
Creates mapping key = word, value = row index
Creates matrix of shape |unique words|×|sentences| where cells
cont... | 611 | en | 0.706144 |
#!/usr/bin/env python
# Copyright (c) 2015 Freescale Semiconductor, Inc.
# Copyright 2016-2017 NXP
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import struct
from .codec import (MessageType, MessageInfo, Codec, CodecError)
class BasicCodec(Codec):
## Version of this codec.
BASIC_CODEC_VER... | sdk_k64f/middleware/multicore/erpc/erpc_python/erpc/basic_codec.py | 3,885 | !/usr/bin/env python Copyright (c) 2015 Freescale Semiconductor, Inc. Copyright 2016-2017 NXP All rights reserved. SPDX-License-Identifier: BSD-3-Clause Version of this codec. @return 4-tuple of msgType, service, request, sequence. @return Int of list length. @return Int of union discriminator. | 295 | en | 0.643646 |
class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
# self.email = f"{fname}.{lname}@sandy.com"
def explain(self):
return f"This employee is {self.fname} {self.lname}"
def email(self):
return f"{self.fname}.{self.lname} @parker.com... | 47 Setters_Property Decorators/main1.py | 472 | self.email = f"{fname}.{lname}@sandy.com"required call email() function to print | 80 | en | 0.628658 |
import os
import subprocess
import jinja2
import json
import openchemistry as oc
def run_calculation(geometry_file, output_file, params, scratch_dir):
# Read in the geometry from the geometry file
# This container expects the geometry file to be in .xyz format
with open(geometry_file) as f:
xyz_s... | docker/nwchem/src/run.py | 3,174 | Read in the geometry from the geometry file This container expects the geometry file to be in .xyz format remove the first two lines in the xyz file (i.e. number of atom and optional comment) Read the input parameters We update the multiplicity key when using scf. SCF accept names and not numbers. single point energy C... | 671 | en | 0.74266 |
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from ch08.deep_convnet import DeepConvNet
from dataset.mnist import load_mnist
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=False)
network = DeepConvNet()
network.loa... | ch08/half_float_network.py | 804 | coding: utf-8 親ディレクトリのファイルをインポートするための設定 高速化のため float16に型変換 | 58 | ja | 0.999924 |
# Generated by Django 2.1.7 on 2019-03-16 10:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='is_donor',
),
]
| src/accounts/migrations/0002_remove_user_is_donor.py | 318 | Generated by Django 2.1.7 on 2019-03-16 10:46 | 45 | en | 0.523374 |
"""
A validator for a frontend failure model. The model contains all
the failing web frontends and their status, as well as the virtual
machines they run on.
"""
from vuluptuous import Schema
schema = Schema({
'web_frontends_failures'
})
| frontend-failure-model/frontend_failure.py | 239 | A validator for a frontend failure model. The model contains all
the failing web frontends and their status, as well as the virtual
machines they run on. | 153 | en | 0.953625 |
"""
Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str
class ProcessAPITestCase(TestBase... | lldb/test/API/python_api/process/TestProcessAPI.py | 18,344 | Test access 'my_int' using Python SBProcess.GetByteOrder() and other APIs.
Test Python SBProcess.AllocateMemory() and SBProcess.DeallocateMemory() APIs.
Test SBProcess.GetNumSupportedHardwareWatchpoints() API with a process.
Test SBProcess::GetProcessInfo() API with a locally launched process.
Test Python SBProcess.Rea... | 3,877 | en | 0.844804 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from obspy.core.stream import Stream
def plot_gll(x, y, z):
""" Plots values on 2D unstructured GLL mesh
"""
r = (max(x) - min(x))/(max(y) - min(y))
rx = r/np.sqrt(1 + r**2)
ry = 1/np.sqrt(1 + r**2)
f ... | seisflows/tools/graphics.py | 4,919 | Extracts trace data from an obspy stream and returns a 2D array.
Parameters
----------
stream: Obspy stream object
Stream storing trace data
Returns
-------
output: ndarray, ndim=2
Returns an (nt*nr) array. nt and nr are the number of sample points
and number of traces respectively. Assumes trace lengths ... | 1,544 | en | 0.570663 |
# Generated by Django 3.0.6 on 2020-05-24 13:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('grid', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Image',
fiel... | grid/migrations/0002_image.py | 1,009 | Generated by Django 3.0.6 on 2020-05-24 13:43 | 45 | en | 0.683315 |
a = []
# append element at the end.
a.append(2)
a.append(3)
print(a)
# insert at a specific location.
a.insert(0, 5)
a.insert(10, 5)
print(a)
# when specified a position not in list, it inserts at the end.
a.insert(100, 6)
print(a)
# Deleting elements from a list.
a.remove(5) # removes the first occurence of value pa... | SRC/December-Batch/02_class/01_list.py | 978 | append element at the end. insert at a specific location. when specified a position not in list, it inserts at the end. Deleting elements from a list. removes the first occurence of value passed access the last element Printing a list the len is not inclusive the len is not inclusive Reverse printing a list the len is ... | 390 | en | 0.858729 |
import os
import sys
import yaml
import argparse
from kubernetes import client, config
import urllib3
from jinja2 import FileSystemLoader, Environment
urllib3.disable_warnings()
KERNEL_POD_TEMPLATE_PATH = '/kernel-pod.yaml.j2'
def generate_kernel_pod_yaml(keywords):
"""Return the kubernetes pod spec as a yaml ... | tools/kernelspecs/kernels/R_kubernetes/scripts/launch_kubernetes.py | 5,072 | Return the kubernetes pod spec as a yaml string.
- load jinja2 template from this file directory.
- substitute template variables with keywords items.
jinja2 template substitutes template variables with None though keywords doesn't contain corresponding item. Therfore, no need to check if any are left unsubstituted.... | 1,337 | en | 0.800432 |
# -*- 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 or... | google/cloud/datacatalog_v1beta1/types/table_spec.py | 3,858 | Spec for a group of BigQuery tables with name pattern
``[prefix]YYYYMMDD``. Context:
https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding
Attributes:
dataset (str):
Output only. The Data Catalog resource name of the dataset
entry the current table belongs to, for e... | 2,462 | en | 0.633527 |
"""
Django settings for workstation project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from dote... | workstation-backend/workstation/settings.py | 3,502 | Django settings for workstation project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
Build paths ins... | 1,086 | en | 0.654808 |
"""
Django settings for BlogProject project.
Generated by 'django-admin startproject' using Django 1.11.20.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
impo... | BlogProject/settings.py | 3,558 | Django settings for BlogProject project.
Generated by 'django-admin startproject' using Django 1.11.20.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
Build paths... | 1,040 | en | 0.598534 |
import numpy as np
import time
import matplotlib.pyplot as plt
from MuellerBrownPotential import MuellerBrownPotential
from LogExpOfHarmonicWellsPotential import LogExpOfHarmonicWellsPotential
from MonteCarloSimulator import MonteCarloSimulator
from MetadynamicsBias import MetadynamicsBias
T = 1.0
NumMCmoves = 10000
... | Particle-On-Potential-MC-sampling/Run_MuellerBrownPotential-WithMetaD.py | 1,142 | potential = LogExpOfHarmonicWellsPotential() | 44 | en | 0.399146 |
"""
Test command line commands.
"""
from pathlib import Path
from subprocess import PIPE, Popen
__author__ = "Sergey Vartanov"
__email__ = "me@enzet.ru"
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from map_machine.ui.cli import COMMAND_LINES
LOG: bytes = (
b"INFO Constructing way... | tests/test_command_line.py | 4,358 | Run command that should fail and check error message.
Run command that should fail and check error message.
Test `element` command.
Test `icons` command.
Test `mapcss` command.
Test `render` command.
Test `render` command.
Test `tile` command.
Test `render` command with wrong arguments.
Test command line commands.
4 ... | 529 | en | 0.759631 |
from colab_ssh.utils.packages.installer import create_deb_installer
from colab_ssh.utils.ui.render_html import render_template
from subprocess import Popen, PIPE
import shlex
from colab_ssh._command import run_command, run_with_pipe
import os
import time
from colab_ssh.get_tunnel_config import get_argo_tunnel_config
fr... | colab_ssh/launch_ssh_cloudflared.py | 3,215 | Kill any cloudflared process if running Download cloudflared Install the openssh server Set the password Configure the openSSH server Prepare the cloudflared command Initial sleep time Create tunnel and retry if failed Increase the sleep time and try again | 256 | en | 0.713216 |
import json
from girder.constants import AccessType
from girder_client import HttpError
import pytest
from .conftest import getClient, getTestFolder, localDataRoot, users, wait_for_jobs
@pytest.mark.integration
@pytest.mark.parametrize("user", users.values())
@pytest.mark.run(order=3)
def test_reset_integration_env... | server/tests/integration/test_dataset_upload.py | 3,169 | Validate the fileset Confirm that the new dataset looks like it should. | 71 | en | 0.852261 |
import Celula
class Labirinto:
def __init__(self, num_rows, num_columns, order_to_check):
# Indica a ordem que vai os vizinhos vao ser checados
self.order_to_check = order_to_check
# Numero de linhas no grid
self.num_rows = num_rows
# Numero de colunas no grid
s... | Trabalho 02/Resolucao/code/backtracking/Labirinto.py | 4,294 | Indica a ordem que vai os vizinhos vao ser checados Numero de linhas no grid Numero de colunas no grid Preenche o grid Printar o grid Adiciona a celula cell em [pos_y][pos_x] Jeito rapido de resolver IndexError porque nao quero gastar muito tempo nesse codigo Verificar se existe uma celula em cima Verificar se existe u... | 1,033 | pt | 0.97481 |
import json
import logging
import os
from typing import Optional, List
from checkov.common.checks_infra.registry import get_graph_checks_registry
from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes
from checkov.common.output.record import Record
from checkov.common.output.... | checkov/terraform/plan_runner.py | 7,317 | Entity can exist only once per dir, for file as well | 52 | en | 0.961798 |
import os
import logging
import json
from typing import Union, Dict, List
from documentstore_migracao.utils.isis2json import isis2json
logger = logging.getLogger(__name__)
class OutputContainer:
"""Classe que mimetiza a escrita de arquivos para a escrita em uma estrutura
de lista. Cada linha em um arquivo r... | documentstore_migracao/utils/extract_isis.py | 2,168 | Classe que mimetiza a escrita de arquivos para a escrita em uma estrutura
de lista. Cada linha em um arquivo representa uma entrada na lista.
Invoca o utilitário `isis2json` com os parâmetros adaptados para a
leitura de arquivos MST de acordo com as definições padrões utilizadas
pelo __main__ da ferramenta `isis2json`.... | 593 | pt | 0.981687 |
#/usr/bin/env python
from paraview.simple import *
import sys
wavelet1 = Wavelet()
wavelet2 = Wavelet()
pythonCalculator1 = PythonCalculator(Input=wavelet2)
pythonCalculator1.ArrayName = 'RTData'
pythonCalculator1.Expression = 'RTData+200'
pythonCalculator1.CopyArrays = 0
# this one should be ignored in the output s... | Applications/ParaView/Testing/Python/AppendAttributes.py | 2,080 | /usr/bin/env python this one should be ignored in the output since it has a different amount of points and cells than the first one should have RTData and RTData_input_1 now try with the can.ex2 exodus file for multiblock testing | 229 | en | 0.924523 |
# 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_alicloud/bastionhost/host_group_account_user_group_attachment.py | 17,901 | The set of arguments for constructing a HostGroupAccountUserGroupAttachment resource.
:param pulumi.Input[Sequence[pulumi.Input[str]]] host_account_names: A list names of the host account.
:param pulumi.Input[str] host_group_id: The ID of the host group.
:param pulumi.Input[str] instance_id: The ID of the Bastionhost i... | 7,458 | en | 0.563514 |
# cdiazbas@iac.es
import numpy as np
# Return the angles in the plane of the sky given angles with respect
# to the vertical for observations on the limb (in degrees!)
def absolute_to_sky(thetaB, chiB):
thetaB = np.deg2rad(thetaB)
chiB = np.deg2rad(chiB)
t1 = np.sin(thetaB) * np.sin(chiB)
t2 = -np.co... | pyRoutines/angle_transformation.py | 3,278 | cdiazbas@iac.es Return the angles in the plane of the sky given angles with respect to the vertical for observations on the limb (in degrees!) Test for the quadrant Return the angles in the vertical system given angles in the plane of the sky for observations on the limb (in degrees!) Test for the quadrant Return the a... | 611 | en | 0.850765 |
# encoding: utf-8
import os
import os.path
from pkg_resources import parse_version
# Avoid problem releasing to pypi from vagrant
if os.environ.get('USER', '') == 'vagrant':
del os.link
try:
from setuptools import (setup, find_packages,
__version__ as setuptools_version)
except I... | setup.py | 15,454 | encoding: utf-8 Avoid problem releasing to pypi from vagrant Check setuptools version FIXME: Remove deprecated resource previews below. You should use the versions as *_view instead. End of deprecated previews namespace_packages=['ckanext', 'ckanext.stats'], setup.py test command needs a TestSuite so does not work with... | 423 | en | 0.637159 |
from __future__ import print_function
import random
import logging
import argparse
import grpc
import object_detection_pb2
import object_detection_pb2_grpc
BLOCK_SIZE = 40000
class ImageDataBlockRequestIterable(object):
def __init__(self, img_data):
self.data = img_data
self.pos = 0
def ... | darknet_model_client.py | 2,238 | pylint: disable=no-memberprint('{}, {}'.format(err.code().name, err.code().value())) pylint: disable=no-member python darknet_model_client.py -a 127.0.0.1:7713 -f ../darknet/model-zoo/platen-switch/test/IMG_9256.JPG | 215 | de | 0.153509 |
# coding=utf-8
# Copyright 2021 The OneFlow 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 require... | libai/data/datasets/bert_dataset.py | 14,501 | Dataset containing sentence pairs for BERT training.
Each index corresponds to a randomly generated sentence pair.
Args:
tokenizer: Tokenizer to use.
data_prefix: Path to the training dataset.
indexed_dataset: Indexed dataset to use.
max_seq_length: Maximum length of the sequence. All values are padded... | 3,547 | en | 0.82636 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Red Hat, 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 applica... | managesf/tests/test_resources_storyboard.py | 9,413 | -*- coding: utf-8 -*- Copyright (c) 2017 Red Hat, 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 i... | 1,176 | en | 0.933051 |
import os.path
import time
from moler.config import load_config
from moler.device.device import DeviceFactory
from moler.util.moler_test import MolerTest
def outage_callback(device_name, ping_times):
MolerTest.info("Network outage on {}".format(device_name))
ping_times["lost_connection_time"] = time.time()
... | trainings/workshop1/step13/network_outage.py | 3,474 | ping operable AFTER any net loss TEST GOAL: network outage should not exceed 3 seconds test setup ensure network is up before running test run event observing "network down/up" run test test teardown | 199 | en | 0.835388 |
# -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20181028052650.1: * @file leowapp.py
#@@first
'''
This file is deprecated/obsolete. It may be removed soon.
leoflexx.py implements LeoWapp using flexx.
'''
#@+<< imports >>
#@+node:ekr.20181028052650.3: ** << imports >>
import leo.core.leoGlobals as g
import leo.c... | leo/plugins/leowapp.py | 3,592 | Handle an missing attribute.
Do the standard xml escapes, and replace newlines and tabs.
Return True if the plugin has loaded successfully.
Send a message to the framework.
The main loop for the browser gui.
This file is deprecated/obsolete. It may be removed soon.
leoflexx.py implements LeoWapp using flexx.
-*- cod... | 1,533 | en | 0.4208 |
# Generated by Django 2.1.5 on 2019-02-08 20:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='post',
name='image',
field=m... | blog/migrations/0002_auto_20190209_0235.py | 405 | Generated by Django 2.1.5 on 2019-02-08 20:35 | 45 | en | 0.495211 |
# Natural Language Toolkit - Range
# Represents a range of numbers, not an immutable object and can be modified by include
# Capable of performing operations on ranges
#
# Author: Sumukh Ghodke <sumukh dot ghodke at gmail dot com>
#
# URL: <http://nltk.sf.net>
# This software is distributed under GPL, for license inf... | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk_contrib/classifier/numrange.py | 2,683 | any number within this range should be greater than or equal to self.lower and
less than (or less than equal to depending on whether it includes the max) self.upper
Natural Language Toolkit - Range Represents a range of numbers, not an immutable object and can be modified by include Capable of performing operation... | 496 | en | 0.877341 |
"""
Django settings for locallibrary project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pa... | locallibrary/settings.py | 4,564 | Django settings for locallibrary project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
needed by code... | 1,811 | en | 0.646573 |
from bokeh.plotting import figure, show
# prepare some data
x = [1, 2, 3, 4, 5]
y = [4, 5, 5, 7, 2]
# create a plot
p = figure(
title="Background colors example",
sizing_mode="stretch_width",
max_width=500,
height=250,
)
# add a renderer
p.line(x, y, line_color="green", line_width=2)
# change the fi... | sphinx/source/docs/first_steps/examples/first_steps_4_background.py | 473 | prepare some data create a plot add a renderer change the fill colors show the results | 86 | en | 0.513101 |
import sys
class Solution:
# Write your code here
def __init__(self):
self.stack = []
self.queue = []
def popCharacter(self):
return self.stack.pop()
def pushCharacter(self, char):
self.stack.append(char)
def dequeueCharacter(self):
char = self.queue[0]
... | Day 18/Queue and stacks.py | 1,097 | Write your code here read the string sCreate the Solution class object push/enqueue all the characters of string s to stackfinally print whether string s is palindrome or not. | 175 | en | 0.703395 |
###############################################################################
##
## Copyright (C) 2013-2014 Tavendo GmbH
##
## 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
##
## h... | ThirdParty/AutobahnPython/autobahn/wamp/message.py | 86,459 | A WAMP ``ABORT`` message.
Format: ``[ABORT, Details|dict, Reason|uri]``
A WAMP ``AUTHENTICATE`` message.
Format: ``[AUTHENTICATE, Signature|string, Extra|dict]``
A WAMP ``CALL`` message.
Formats:
* ``[CALL, Request|id, Options|dict, Procedure|uri]``
* ``[CALL, Request|id, Options|dict, Procedure|uri, Arguments|list... | 23,587 | en | 0.565591 |
# parse list of objects
import csv
file = "basic_objects.txt"
objects = []
with open(file) as f:
for line in f:
if line[0:2] == '//' or line[0:2] == None: # skip empties, comments
pass
else:
obj = line.rstrip() # strip Newli... | py/parse_sort_objects.py | 1,020 | parse list of objects skip empties, comments strip Newlines Capitalize every word test for dupes Write out txt list with open("cleaned_basic_objects.txt", 'wb') as csvfile: writer = csv.writer(csvfile) writer.writerows(n.split(',') for n in nice_objects) idk why you need the split | 293 | en | 0.768273 |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | bokeh/client/states.py | 4,666 | The ``ClientConnection`` connected to a Bokeh server, and has
received an ACK from it.
The ``ClientConnection`` connected to a Bokeh server, but has not yet
received an ACK from it.
The ``ClientConnection`` was connected to a Bokeh server, but is
now disconnected.
The ``ClientConnection`` is not yet connected.
Th... | 2,479 | en | 0.566543 |
import mxnet as mx
import proposal
import proposal_target
from rcnn.config import config
import focal_loss
eps = 2e-5
use_global_stats = True
workspace = 512
res_deps = {'50': (3, 4, 6, 3), '101': (3, 4, 23, 3), '152': (3, 8, 36, 3), '200': (3, 24, 36, 3)}
units = res_deps['101']
filter_list = [256, 512, 1024, 2048]
... | rcnn/symbol/symbol_resnet_modify.py | 13,629 | res1 res2 res3 res4 shared convolutional layers RPN layers prepare rpn data classification bounding box regression ROI proposal ROI proposal target Fast R-CNN res5 classificationcls_prob = mx.symbol.SoftmaxOutput(name='cls_prob', data=cls_score, label=label, normalization='batch') reshape output shared convolutional la... | 424 | en | 0.519322 |
# -*- coding: utf-8 -*-
"""Subspace Outlier Detection (SOD)
"""
# Author: Yahya Almardeny <almardeny@gmail.com>
# License: BSD 2 clause
import numpy as np
import numba as nb
from sklearn.neighbors import NearestNeighbors
from sklearn.utils import check_array
from ..utils.utility import check_parameter
from .base impo... | pyod/models/sod.py | 7,068 | Subspace outlier detection (SOD) schema aims to detect outlier in
varying subspaces of a high dimensional feature space. For each data
object, SOD explores the axis-parallel subspace spanned by the data
object's neighbors and determines how much the object deviates from the
neighbors in this subspace.
See :cite:`krieg... | 3,585 | en | 0.747481 |
# 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/.
import pytest
from unittestzero import Assert
from pages.dashboard import DashboardPage
class TestProductFilter(objec... | smoketests/tests/dashboard/test_product_filter.py | 2,397 | Tests product filtering in dashboard
1. Verify that at least one product exists
2. Verify that filtering by product returns results
3. Verify that versions show up when you choose a product
4. Verify that the state of the filters are correct after being applied
5. Verify product and version values in the URL
NB: We d... | 685 | en | 0.925968 |
import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import hashlib
import csv
from product_spiders.item... | portfolio/Python/scrapy/seapets/thepetexpress.py | 2,025 | categories pagination products | 30 | en | 0.398588 |
# coding: utf-8
"""
Ory Kratos
Welcome to the ORY Kratos HTTP API documentation! # noqa: E501
The version of the OpenAPI document: latest
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import ory_kratos_client
from ory_krat... | clients/kratos/python/test/test_request_method_config.py | 2,806 | RequestMethodConfig unit test stubs
Test RequestMethodConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included
Test RequestMethodConfig
Ory Kratos
Welcome to the ORY Kratos HTTP API documentation! # noqa: E501
The version of the OpenA... | 501 | en | 0.592003 |
# -*- coding: utf-8 -*-
"""
mslib.mscolab._tests.test_utils
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tests for mscolab/utils
This file is part of mss.
:copyright: Copyright 2019 Shivashis Padhi
:copyright: Copyright 2019-2020 by the mss team, see AUTHORS.
Licensed under the Apache License, Ver... | mslib/mscolab/_tests/test_utils.py | 1,843 | mslib.mscolab._tests.test_utils
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tests for mscolab/utils
This file is part of mss.
:copyright: Copyright 2019 Shivashis Padhi
:copyright: Copyright 2019-2020 by the mss team, see AUTHORS.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file excep... | 771 | en | 0.812315 |
import os
import numpy as np
import tensorflow as tf
from collections import deque
def sample(logits):
noise = tf.random_uniform(tf.shape(logits))
return tf.argmax(logits - tf.log(-tf.log(noise)), 1)
def cat_entropy(logits):
a0 = logits - tf.reduce_max(logits, 1, keepdims=True)
ea0 = tf.exp(a0)
z... | baselines/a2c/utils.py | 9,361 | lasagne ortho init for tf assumes NHWC pick the one with the correct shape fixed off by one bug rolling buffer for episode lengths rolling buffer for episode rewards on the first params dump, no episodes are finished For ACER flatten input use flattened indices | 261 | en | 0.880684 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | kubernetes/test/test_v2beta1_horizontal_pod_autoscaler.py | 1,075 | V2beta1HorizontalPodAutoscaler unit test stubs
Test V2beta1HorizontalPodAutoscaler
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 FIXME: con... | 478 | en | 0.376048 |
# Generated by Django 3.0.8 on 2021-07-07 22:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('keyword_relation', '0010_auto_20210322_2049'),
]
operations = [
migrations.CreateModel(
name='Keyword_Grouping',
fie... | keyword_relation/migrations/0011_keyword_grouping.py | 596 | Generated by Django 3.0.8 on 2021-07-07 22:33 | 45 | en | 0.73796 |
import tensorflow as tf
class FrozenBatchNorm2D(tf.keras.layers.Layer):
def __init__(self, eps=1e-5, **kwargs):
super().__init__(**kwargs)
self.eps = eps
def build(self, input_shape):
self.weight = self.add_weight(name='weight', shape=[input_shape[-1]],
... | detr_tensorflow/models/custom_layers.py | 2,646 | Use this custom layer instead of tf.keras.layers.Dense
to allow loading converted PyTorch Dense weights
that have shape (output_dim, input_dim) | 143 | en | 0.501608 |
import ClientSide2 #custom package
import numpy as np
import argparse
import json
import os
import ClassifierFunctions2 as cf
import random
import logging
from matplotlib import pyplot as plt
from builtins import input
from Notation import SpaceGroupsDict as spgs
SpGr = spgs.spacegroups()
from itertools import co... | DiffractionClassifierCombinatorial2.0.py | 16,156 | powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
custom package Initialize essential global variablesURL = "" you'll need me to send you the link list of three, one per level This will be implemented as rollout broadens print(guesses)peak_locs,user_info,URL,fam print(failed_combos) ... | 2,019 | en | 0.439183 |
"""The tests the History component."""
# pylint: disable=protected-access,invalid-name
from datetime import timedelta
import json
from unittest.mock import patch, sentinel
import pytest
from pytest import approx
from homeassistant.components import history, recorder
from homeassistant.components.recorder.history impo... | tests/components/history/test_init.py | 36,563 | Check if significant states are retrieved.
Record some test states.
We inject a bunch of state updates from media player, zone and
thermostat.
Set the state.
Set the state.
Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state ... | 3,704 | en | 0.918417 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | aliyun-python-sdk-cs/aliyunsdkcs/request/v20151215/PauseClusterUpgradeRequest.py | 1,502 | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file... | 754 | en | 0.883564 |
#MenuTitle: Generate lowercase from uppercase
"""
Generate lowercase a-z from uppercase A-Z
TODO (M Foley) Generate all lowercase glyphs, not just a-z
"""
font = Glyphs.font
glyphs = list('abcdefghijklmnopqrstuvwxyz')
masters = font.masters
for glyph_name in glyphs:
glyph = GSGlyph(glyph_name)
glyph.updateGl... | Glyph-Builders/lowercase_from_upper.py | 567 | Generate lowercase a-z from uppercase A-Z
TODO (M Foley) Generate all lowercase glyphs, not just a-z
MenuTitle: Generate lowercase from uppercase | 147 | en | 0.214155 |
# to run:
# pip install unittest2
# unit2 discover
#
# to debug:
# pip install nose
# nosetests --pdb
import StringIO
import sys
import pdfquery
import unittest2
from pdfquery.cache import FileCache
class TestPDFQuery(unittest2.TestCase):
"""
Various tests based on the IRS_1040A sample doc.
"""
... | tests/tests.py | 6,649 | Ensure that annotations such as links are getting added to the PDFs
properly, as discussed in issue #28.
Various tests based on the IRS_1040A sample doc.
Test the extract() function.
Test the :contains and :in_bbox selectors.
Test that converted XML hasn't changed from saved version.
Test that converted XML hasn't chan... | 666 | en | 0.922295 |
# Copyright 2016 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | nova/tests/functional/db/test_console_auth_token.py | 2,236 | Copyright 2016 Hewlett Packard Enterprise Development Company LP 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... | 614 | en | 0.856728 |
import argparse
import datetime
import json
import os
import time
from os import path
import numpy as np
import torch
from absl import flags
from torch import optim
from pprint import pprint
import wandb
from src.alive_sieve import AliveSieve, SievePlayback
from src.nets import AgentModel
from src.rewards_lib import ... | src/ecn.py | 21,563 | testing option will:
- use argmax, ie disable stochastic draws
- not run optimizers
- not save model
turning testing on means, we disable stochasticity: always pick the argmax
returns a / b, unless b is zero, in which case returns 0
this is primarily for usage in cases where b might be systemtically zero, eg because co... | 602 | en | 0.834104 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
!!! This generally needs to be run right after the close of applications for a framework, and passed to product
!!! managers & CCS.
Generate a CSV with per-lot draft statistics for each supplier who registered interest in the framework,
whether or not they made a compl... | scripts/framework-applications/export-framework-applications-at-close.py | 2,270 | !!! This generally needs to be run right after the close of applications for a framework, and passed to product
!!! managers & CCS.
Generate a CSV with per-lot draft statistics for each supplier who registered interest in the framework,
whether or not they made a complete application in the end.
Fields included:
* Su... | 952 | en | 0.759126 |
from docxtpl import DocxTemplate
import csv
import json
import random
#случайный авто
with open('Car_info.txt') as file:
car_rand = []
reader = csv.reader(file)
for row in file:
car_rand.append(row)
report_car = car_rand[random.randint(0, len(car_rand)-1)]
car_info = report_car.split()
#О авто
def g... | 7.py | 1,369 | случайный автоО автоcsv файлjson файл | 37 | ru | 0.907523 |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
from datadog_api_client.v2.model_uti... | src/datadog_api_client/v2/model/security_filter_exclusion_filter.py | 6,839 | 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... | 3,786 | en | 0.800289 |
# -*- coding:utf-8 -*-
"""
"""
import pandas as pd
from pandas.util import hash_pandas_object
from hypernets.tabular.datasets.dsutils import load_bank
from . import if_cuml_ready, is_cuml_installed
if is_cuml_installed:
import cudf
from hypernets.tabular.cuml_ex import CumlToolBox
dd_selector = CumlTool... | hypernets/tests/tabular/tb_cuml/drift_detection_test.py | 2,954 | -*- coding:utf-8 -*- = train_test_split(df, train_size=0.7, random_state=9527) | 79 | en | 0.709475 |
"""Abstract class for image transports.
Defines generic functions.
"""
# Copyright (c) 2018 Erling Andersen, Haukeland University Hospital, Bergen, Norway
from abc import ABCMeta, abstractmethod # , abstractproperty
# import imagedata.transports
class NoOtherInstance(Exception):
pass
class AbstractTransport... | src/imagedata/transports/abstracttransport.py | 2,964 | Abstract base class definition for imagedata transport plugins.
Plugins must be a subclass of AbstractPlugin and
must define the attributes set in __init__() and
the following methods:
open() method
isfile() method
walk() method
Plugin authors
Multi-line string naming the author(s) of the plugin.
Close the transport
... | 1,326 | en | 0.655018 |
# coding: utf-8
"""
IncQuery Server
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: 0.12.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class TWCRep... | iqs_client/models/twc_repository_info_response.py | 4,351 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Returns true if both objects are equal
TWCRepositoryInfoResponse - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Gets the last_updated of this TW... | 1,369 | en | 0.582697 |
"""This is a set of tools built up over time for working with Gaussian and
QChem input and output."""
########################################################################
# #
# ... | gautools/__init__.py | 1,715 | This is a set of tools built up over time for working with Gaussian and
QChem input and output.
This script was written by Thomas Heavey in 2017. theav... | 1,388 | en | 0.892806 |
# -*- coding: utf-8 -*-
from datetime import date, time
import pytest
from django.contrib.admin import site as admin_site
from resources.admin.period_inline import PeriodModelForm, prefix_weekday
from resources.models import Period, Resource
from resources.models.unit import Unit
from resources.tests.utils import ass... | resources/tests/test_admin_period_inline.py | 2,052 | -*- coding: utf-8 -*- Make every day open at 06, set closed on wednesdays Weekdays _got_ closed, yeah? Sorry for accessing a private member :( should have a weekday field | 170 | en | 0.968467 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.