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 |
|---|---|---|---|---|---|---|
from __future__ import print_function, division
import logging
import numpy as np
from . import operators
from . import utils
from . import algorithms
def delta_data(A, S, Y, W=1):
return W*(A.dot(S) - Y)
def grad_likelihood_A(A, S, Y, W=1):
D = delta_data(A, S, Y, W=W)
return D.dot(S.T)
def grad_likelih... | proxmin/nmf.py | 6,974 | Helper class to compute the Lipschitz constants of grad f.
The __call__ function compute the spectral norms of A or S, which
determine the Lipschitz constant of the respective update steps.
If a weight matrix is used, the stepsize will be upper bounded by
assuming the maximum value of the weights. In the case of vary... | 2,907 | en | 0.791016 |
import json
import logging
import math
import os
import random
import warnings
from dataclasses import asdict
from multiprocessing import Pool, cpu_count
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from tensorboardX import SummaryWriter
from torch.nn.utils.rnn import pad_sequence
from ... | simpletransformers/seq2seq/seq2seq_model.py | 46,925 | Initializes a Seq2SeqModel.
Args:
encoder_type (optional): The type of model to use as the encoder.
encoder_name (optional): The exact architecture and trained weights to use. This may be a Hugging Face Transformers compatible pre-trained model, a community model, or the path to a directory containing model fi... | 6,662 | en | 0.662834 |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTest(TestCase):
def test_create_user_with_email_successful(self):
"""이메일로 유저 생성을 성공하는 테스트"""
email = 'test@testemail.com'
password = 'testpassword'
user = get_user_model().objects.create_use... | shoppingmall/core/tests/test_models.py | 1,352 | Superuser를 생성하는 테스트
이메일로 유저 생성을 성공하는 테스트
이메일이 표준 형식으로 들어오는 테스트
이메일이 입력되지 않았을 때 에러가 발생하는 테스트 | 91 | ko | 1.00007 |
# Generated by Django 2.1.2 on 2019-02-05 08:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0038_merge_20190203_1423'),
('core', '0039_auto_20190205_0609'),
]
operations = [
]
| src/core/migrations/0040_merge_20190205_0807.py | 268 | Generated by Django 2.1.2 on 2019-02-05 08:07 | 45 | en | 0.579368 |
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""Entry point for both build and try bots.
This script is invoked from XXX, usually without arguments
to package an SDK. It autom... | native_client_sdk/src/build_tools/build_sdk.py | 35,213 | !/usr/bin/env python Copyright (c) 2012 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. pylint: disable=W0621 std python includes local includes Add SDK make tools scripts to the python path. Replace a few placeholders in READM... | 2,961 | en | 0.825541 |
# Copyright (c) 2016, 2020, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# ... | backend/env/Lib/site-packages/mysqlx/authentication.py | 5,431 | Base class for implementing the authentication plugins.
Class implementing the MySQL Native Password authentication plugin.
Class implementing the MySQL Plain authentication plugin.
Class implementing the SHA256_MEMORY authentication plugin.
Hashing for MySQL 4.1 authentication.
Args:
data (str): The authenticatio... | 2,847 | en | 0.778393 |
from os.path import realpath
def main():
inpString = open(f'{realpath(__file__)[:-2]}txt').read()
inpString += '0' * (3 - len(inpString) % 3) # Padding to make it divisible by 3
inp = list(inpString)
for i in range(len(inp)):
if inp[i] not in '0123456789abcdef':
inp[i] = ... | 01/01.py | 551 | Padding to make it divisible by 3 Print first 2 char of every 1/3rd part of input | 81 | en | 0.859381 |
# This file is part of postcipes
# (c) Timofey Mukha
# The code is released under the MIT Licence.
# See LICENCE.txt and the Legal section in the README for more information
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .postcipe import Postci... | postcipes/bfs.py | 4,955 | This file is part of postcipes (c) Timofey Mukha The code is released under the MIT Licence. See LICENCE.txt and the Legal section in the README for more information | 165 | en | 0.879404 |
from django.contrib import admin
from .models import Post, Reply
# Register your models here.
admin.site.register(Post)
admin.site.register(Reply)
| showcase/post/admin.py | 149 | Register your models here. | 26 | en | 0.957485 |
# Listing_19-1.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Trying out sounds in Pygame
import pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode([640,480... | FatherSon/HelloWorld2_source_code/Listing_19-1.py | 692 | Listing_19-1.py Copyright Warren & Carter Sande, 2013 Released under MIT license http://www.opensource.org/licenses/mit-license.php Version $version ---------------------------- Trying out sounds in Pygame Wait a second for the mixer to finish initializing Create the Sound object Play the sound | 298 | en | 0.594575 |
"""
With these settings, tests run faster.
"""
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="4UWuZDCfH... | config/settings/test.py | 1,422 | With these settings, tests run faster.
noqa GENERAL ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/secret-key https://docs.djangoproject.com/en/dev/ref/settings/test-runner PASSWORDS ----------------------------------------------------... | 777 | en | 0.371128 |
import copy
from functools import wraps
import numpy as np
import wandb
import torchvision
import torch
import torch.nn.functional as F
from kornia import enhance, filters
from torchvision.transforms import RandomApply, RandomChoice
from atariari.methods.utils import EarlyStopping
from torch import nn
from torch.u... | byol_pytorch/byol_pytorch.py | 11,096 | loss fn augmentation utils class RandomApply(nn.Module): def __init__(self, fn, p): super().__init__() self.fn = fn self.p = p def forward(self, x): if random.random() > self.p: return x return self.fn(x) exponential moving average MLP class for projector and ... | 1,585 | en | 0.464673 |
# SPDX-License-Identifier: MIT
#!/usr/bin/env python3
import os
import sys
from ply import yacc
from ply.lex import TOKEN
from .slexer import SLexer
from ..lib import dbg
from .symbol import (
BinaryOperatorSymbol, ConstraintSymbol, FieldSymbol, ArraySymbol,
CallSymbol, IDSymbol, ConcreteIntSymbol, StringLitera... | analyzer/apisan/parse/sparser.py | 5,986 | argument_list :
| expression
| argument_list COMMA expression
binary_expression : cast_expression
binary_expression : binary_expression TIMES binary_expression
| binary_expression DIVIDE binary_expression
| binary_expression MOD binary_expression
| binary_expression PLUS binary_expression
| binary_expression MINU... | 1,986 | en | 0.528269 |
""" StreamSort Projects Extension -- Constants
Copyright (c) 2021 IdmFoundInHim, under MIT License
"""
SINGLE_MAX_MS = 15 * 60 * 1000
SINGLE_MAX_TRACKS = 4
| projects/constants.py | 158 | StreamSort Projects Extension -- Constants
Copyright (c) 2021 IdmFoundInHim, under MIT License | 96 | en | 0.329785 |
# -*- coding: utf-8 -*-
""" XIO plugin for the minicbf format of images (DECTRIS-PILATUS).
"""
__version__ = "0.2.1"
__author__ = "Pierre Legrand (pierre.legrand@synchrotron-soleil.fr)"
__date__ = "23-09-2012"
__copyright__ = "Copyright (c) 2009-2012 Pierre Legrand"
__license__ = "New BSD, http://www.opensource.org/l... | yamtbx/dataproc/XIO/plugins/minicbf_interpreter.py | 5,584 | Dummy class, container for standard Dict and Function.
from str return seconds
from str return timestr + msec
Intepret the ascii structure of the minicbf image header.
Calculate EdgeResolution
XIO plugin for the minicbf format of images (DECTRIS-PILATUS).
-*- coding: utf-8 -*- The adsc Header Translator Dictionary. P... | 1,241 | en | 0.595659 |
# -*- coding: utf-8 -
#
# This file is part of gaffer. See the NOTICE for more information.
import os
import sys
from setuptools import setup, find_packages, Extension
py_version = sys.version_info[:2]
if py_version < (2, 6):
raise RuntimeError('On Python 2, Gaffer requires Python 2.6 or better')
CLASSIFIERS ... | setup.py | 2,125 | -*- coding: utf-8 - This file is part of gaffer. See the NOTICE for more information. read long description | 107 | en | 0.855484 |
#!/usr/bin/env python
# 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 "Licen... | demos/gce_demo.py | 26,411 | !/usr/bin/env python 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 m... | 5,630 | en | 0.840526 |
from django.shortcuts import render
from django.http import JsonResponse
from django.core.files.storage import FileSystemStorage
import requests
# Create your views here.
def cnn(request):
return render(request, 'CNN/cnn.html')
def change(request):
##########################################################... | CNN/views.py | 1,043 | Create your views here.defaults to MEDIA_ROOT Here we know the file is in file name = file_name + randomNumber | 113 | en | 0.79925 |
"""
Compatibility tools for differences between Python 2 and 3
"""
import functools
import itertools
import sys
import urllib
PY3 = (sys.version_info[0] >= 3)
PY3_2 = sys.version_info[:2] == (3, 2)
if PY3:
import builtins
from collections import namedtuple
from io import StringIO, BytesIO
import inspe... | statsmodels/compat/python.py | 6,588 | Simple workaroung for getargspec deprecation that returns
an ArgSpec-like object
replacement for six's iteritems for Python2/3 compat
uses 'iteritems' if available and otherwise uses 'items'.
Passes kwargs to method.
Compatibility tools for differences between Python 2 and 3
added JP, not in numpy version have to exp... | 720 | en | 0.674038 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# License: MIT. See LICENSE
# import frappe
from frappe.model.document import Document
class WebPageBlock(Document):
pass
| frappe/website/doctype/web_page_block/web_page_block.py | 209 | -*- coding: utf-8 -*- Copyright (c) 2020, Frappe Technologies and contributors License: MIT. See LICENSE import frappe | 118 | en | 0.567409 |
from builtins import range
from builtins import object
import numpy as np
from past.builtins import xrange
class KNearestNeighbor(object):
""" a kNN classifier with L2 distance """
def __init__(self):
pass
def train(self, X, y):
"""
Train the classifier. For k-nearest neighbors t... | assignments/2021/assignment1/cs231n/classifiers/k_nearest_neighbor.py | 8,815 | a kNN classifier with L2 distance
Compute the distance between each test point in X and each training point
in self.X_train using no explicit loops.
Input / Output: Same as compute_distances_two_loops
Compute the distance between each test point in X and each training point
in self.X_train using a single loop over th... | 4,797 | en | 0.812165 |
# Copyright 2016 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 applicab... | research/cognitive_mapping_and_planning/datasets/factory.py | 3,880 | Wrapper for selecting the navigation environment that we want to train and
test on.
Copyright 2016 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 ht... | 745 | en | 0.843272 |
import pandas as pd
import numpy as np
def gloriosafuncao(df):
df = pd.DataFrame([df])
numerico = [
11, "email", 1, 2, 3, 7,
8, 9, 12, 10, 13, 14,
15, 16, 17, 18, 19, 20, 21, 4, 5, 6
]
df.columns = numerico
labels = [
'email',
'PPI',
'ProgramasSo... | data-clean/clean.py | 6,947 | 'Beneficiario', 'Pescador/agricultor familiar', 'PescAgriF', 'Beneficiario', 'PescAgriF', | 89 | es | 0.248033 |
# -*- coding: utf-8 -*-
# Copyright 2020-2022 CERN
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | lib/rucio/tests/conftest.py | 12,679 | Fixture which overrides the different internal caches with in-memory ones for the duration
of a particular test.
This override works only in tests which use core function calls directly, not in the ones
working via API.
The fixture acts by by mock.patch the REGION object in the provided list of modules to mock.
Detec... | 3,086 | en | 0.787211 |
# -*- coding: utf-8 -*-
"""
Copyright © 2019-present Lenovo
This file is licensed under both the BSD-3 license for individual/non-commercial use and
EPL-1.0 license for commercial use. Full text of both licenses can be found in
COPYING.BSD and COPYING.EPL files.
"""
import time
from copy import deepcopy
from fnmatch... | antilles-core/openHPC_web_project/tests/user/mock_libuser.py | 13,314 | if set USERPASSWORD of group GROUPPASSWORD same as it
if not any value set, key should not exists
Copyright © 2019-present Lenovo
This file is licensed under both the BSD-3 license for individual/non-commercial use and
EPL-1.0 license for commercial use. Full text of both licenses can be found in
COPYING.BSD and COPYI... | 868 | en | 0.619667 |
# Generated by Django 1.11.24 on 2019-10-16 22:48
from typing import Any, Set, Union
import ujson
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.db import migrations
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from django.db... | zerver/migrations/0209_user_profile_no_empty_password.py | 11,210 | With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable password" (i.e. no password at all). This was a
serious security issue for organizations with both password and
Go... | 5,122 | en | 0.954521 |
from flask import g
import logging
from datetime import datetime
import config
def get_logger(name):
# type: (str) -> logging.Logger
logging.basicConfig()
logger = logging.getLogger(name)
logger.setLevel(config.GLOBAL_LOGGING_LEVEL)
ch = logging.StreamHandler()
ch.setLevel(config.GLOBAL_LOGGING_LEVEL)
fo... | app_util.py | 792 | type: (str) -> logging.Logger logger.addHandler(ch) | 52 | en | 0.287958 |
# coding: utf-8
"""
TheTVDB API v2
API v3 targets v2 functionality with a few minor additions. The API is accessible via https://api.thetvdb.com and provides the following REST endpoints in JSON format. How to use this API documentation ---------------- You may browse the API routes without authentication... | tvdb_api/models/movie.py | 10,825 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
Movie - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the artworks of this Movie. # noqa: E501
:return: The artworks ... | 4,867 | en | 0.730315 |
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
class CartPoleEnv(gym.Env):
"""
Description:
A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to prevent it fr... | configurable_control_gym/envs/cartpole.py | 8,820 | Description:
A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to prevent it from falling over by increasing and reducing the cart's velocity.
Source:
This environment corresponds to the version of the cart-pole problem des... | 1,789 | en | 0.908914 |
# Copyright (c) 2015 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | ykman/__init__.py | 1,543 | Copyright (c) 2015 Yubico AB All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the follow... | 1,318 | en | 0.883634 |
#
# Spec2Vec
#
# Copyright 2019 Netherlands eScience Center
#
# 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 applicabl... | matchms/old/ms_similarity_classical.py | 21,310 | Calculates cosine similarity matrix.
Be careful! Binning is here done by creating one-hot vectors.
It is hence really actual "bining" and different from the tolerance-based
approach used for the cosine_matrix or molnet_matrix!
Also: tol here is about tol/2 when compared to cosine_matrix or molnet_matrix...
Calculate ... | 6,653 | en | 0.801504 |
from leapp.models import Model, fields
from leapp.topics import BootPrepTopic, SystemInfoTopic
from leapp.utils.deprecation import deprecated
class DracutModule(Model):
"""
Specify a dracut module that should be included into the initramfs
The specified dracut module has to be compatible with the target ... | repos/system_upgrade/common/models/initramfs.py | 4,478 | Specify a dracut module that should be included into the initramfs
The specified dracut module has to be compatible with the target system.
See the description of UpgradeInitramfsTasks and TargetInitramfsTasks
for more information about the role of initramfs in the in-place upgrade
process.
List of files (cannonical ... | 1,984 | en | 0.912068 |
# -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.colorimetry.luminance` module.
"""
import numpy as np
import unittest
from colour.colorimetry import (
luminance_Newhall1943, intermediate_luminance_function_CIE1976,
luminance_CIE1976, luminance_ASTMD1535, luminance_Fairchild2010,
lu... | colour/colorimetry/tests/test_luminance.py | 20,521 | Defines :func:`colour.colorimetry.luminance.intermediate_luminance_function_CIE1976` definition unit tests methods.
Defines :func:`colour.colorimetry.luminance.luminance` definition unit
tests methods.
Defines :func:`colour.colorimetry.luminance.luminance_ASTMD1535`
definition unit tests methods.
Defines :func:`colour.... | 3,730 | en | 0.576442 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
""" setup.py for resilient-circuits Python module """
import io
from os import path
from setuptools import find_packages, setup
this_directory = path.abspath(path.dirname(__file__))
with io.open(path.join(this_... | resilient-circuits/setup.py | 2,059 | setup.py for resilient-circuits Python module
!/usr/bin/env python -*- coding: utf-8 -*- (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. Runtime Dependencies PyPI metadata | 182 | en | 0.435333 |
import pyglet
class Resources:
# --- Player Parameters ---
player_animation_started = False
player_images = []
player_animation_time = 1. / 9.
player_animation_index = 0
# --- Obstacle Parameters ---
obstacle_images = []
# --- Player Methods ---
# loads the images neede... | src/dinosaur/game/resources.py | 1,883 | --- Player Parameters --- --- Obstacle Parameters --- --- Player Methods --- loads the images needed for the player animation if they haven't been loaded already starts the player's running animation by scheduling recurring updates to the player's image index updates the player's image index returns the current image f... | 382 | en | 0.921788 |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... | queue_services/business-events-listener/src/business_events_listener/worker.py | 6,269 | The unique worker functionality for this service is contained here.
The entry-point is the **cb_nr_subscription_handler**
The design and flow leverage a few constraints that are placed upon it
by NATS Streaming and using AWAIT on the default loop.
- NATS streaming queues require one message to be processed at a time.... | 1,716 | en | 0.883344 |
##############################################################################
# Copyright 2019 Parker Berberian and Others #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# yo... | laas/tests/test_action_get_task_list.py | 2,499 | Copyright 2019 Parker Berberian and Others 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... | 942 | en | 0.865261 |
from datetime import date
import pytest
from dateutil.parser import parse as dt_parse
from freezegun import freeze_time
from app.models.alert_date import AlertDate
def test_AlertDate_properties():
sample_datetime = dt_parse('2021-03-02T10:30:00Z')
alerts_date = AlertDate(sample_datetime)
assert alerts_d... | tests/app/models/test_alert_date.py | 2,635 | 12 hour clock GMT BST | 21 | en | 0.359164 |
# Copyright 2018 Google Inc. 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 a... | dm/templates/external_load_balancer/external_load_balancer.py | 9,153 | Entry point for the deployment resources.
Creates the backend service.
Creates all backend services to be used by the load balancer.
Creates the forwarding rule.
Finds what network protocol to use.
Creates reference to a property of a given resource.
Creates a target proxy resource.
Creates a UrlMap resource.
C... | 1,132 | en | 0.826715 |
#python exceptions let you deal with
#unexpected results
try:
print(a) #this will throw an exception since a is not found
except:
print("a is not defined!")
#there are specific errors in python
try:
print(a) #this will throw a NameError
except NameError:
print("a is still not defined")
except:
print("Somethin... | exceptions.py | 403 | python exceptions let you deal withunexpected resultsthis will throw an exception since a is not foundthere are specific errors in pythonthis will throw a NameErrorthis will break our programsince a is not defined | 213 | en | 0.879358 |
"""
.. autoclass:: ppci.arch.arch.Architecture
:members:
.. autoclass:: ppci.arch.arch_info.ArchInfo
:members:
.. autoclass:: ppci.arch.arch.Frame
:members:
.. autoclass:: ppci.arch.isa.Isa
:members:
.. autoclass:: ppci.arch.registers.Register
:members: is_colored
.. autoclass:: ppci.arch.e... | ppci/arch/__init__.py | 1,755 | Try to return an architecture instance.
Args:
arch: can be a string in the form of arch:option1:option2
.. doctest::
>>> from ppci.api import get_arch
>>> arch = get_arch('msp430')
>>> arch
msp430-arch
>>> type(arch)
<class 'ppci.arch.msp430.arch.Msp430Arch'>
Try to get the architecture f... | 786 | en | 0.495587 |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
... | samples/openapi3/client/petstore/python-experimental/test/test_composed_bool.py | 839 | ComposedBool unit test stubs
Test ComposedBool
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: " \ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.te... | 444 | en | 0.798526 |
from warnings import warn
from functools import partial
from tqdm import tqdm
import torch
import numpy as np
from torch.optim import Adam
from torch.nn import MSELoss
from odl.contrib.torch import OperatorModule
from dival.reconstructors import IterativeReconstructor
from dival.reconstructors.networks.unet import U... | dival/reconstructors/dip_ct_reconstructor.py | 6,654 | CT reconstructor applying DIP with TV regularization (see [2]_).
The DIP was introduced in [1]_.
References
----------
.. [1] V. Lempitsky, A. Vedaldi, and D. Ulyanov, 2018, "Deep Image Prior".
IEEE/CVF Conference on Computer Vision and Pattern Recognition.
https://doi.org/10.1109/CVPR.2018.00984
.. [2] ... | 1,672 | en | 0.782034 |
"""
PAIPASS Oauth2 backend
"""
import re
from .oauth import BaseOAuth2
from ..utils import handle_http_errors, url_add_parameters
from ..exceptions import AuthCanceled, AuthUnknownError
class PaipassOAuth2(BaseOAuth2):
"""Facebook OAuth2 authentication backend"""
name = "paipass"
ID_KEY = "email"
... | social_core/backends/paipass.py | 2,684 | Facebook OAuth2 authentication backend
Finish the auth process once the access_token was retrieved
Build redirect with redirect_state parameter.
Return user details from Facebook account
Loads user data from service
PAIPASS Oauth2 backend | 238 | en | 0.777786 |
"""ConnManagerMQTT containing script"""
import _thread
import time
import random
import logging
from .uconn_mqtt import UConnMQTT
from . import exceptions
class ConnManagerMQTT(object):
"""
UconnMQTT wrapper that guarantee delivery to addressee
"""
_SENDER = 'sender'
_DESTINATION = 'destination'
... | utilities/connmanagermqtt.py | 4,343 | UconnMQTT wrapper that guarantee delivery to addressee
Initialization of ConnManager
Message receiving callback
:param sender: Message sender
:param message: The message
Check if message was delivered and republish if not
:param id: Message ID
Disconnection from server
Publish message
:param sender: Message sender
:... | 611 | en | 0.618187 |
from typing import Tuple
import torch as th
import torch.nn as nn
from torchvision import transforms
from autoencoding_rl.latent_extractors.autoencoder.SimpleEncoder import SimpleEncoder
from autoencoding_rl.latent_extractors.autoencoder.SimpleDecoder import SimpleDecoder
from autoencoding_rl.utils import Transition... | src/autoencoding_rl/latent_extractors/dyn_autoencoder/DynAutoencoder.py | 9,340 | Compute 'static' features encodingGives a (batch_size, static_encoding_size) outputCompute 'dynamic' features encodingGives a (batch_size, dyn_encoding_size) outputstate_d_1_batch now has size (batch_size, dyn_encoding_size)reward_d_1_batch now has size (batch_size, 1) (still 2-dimensional)Will now use 'static' feature... | 1,065 | en | 0.752529 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 10 18:18:26 2021
@author: Paolo Cozzi <paolo.cozzi@ibba.cnr.it>
"""
import click
import logging
import datetime
from pathlib import Path
from mongoengine.errors import DoesNotExist
from src import __version__
from src.data.common import WORKING_... | src/data/update_db_status.py | 1,380 | Update SMARTER database statuses
Created on Wed Nov 10 18:18:26 2021
@author: Paolo Cozzi <paolo.cozzi@ibba.cnr.it>
!/usr/bin/env python3 -*- coding: utf-8 -*- update stuff connect to database | 194 | en | 0.534542 |
# encoding: utf-8
"""
The *pathspec* package provides pattern matching for file paths. So far
this only includes Git's wildmatch pattern matching (the style used for
".gitignore" files).
The following classes are imported and made available from the root of
the `pathspec` package:
- :class:`pathspec.pathspec.PathSpec... | venv/Lib/site-packages/pathspec/__init__.py | 1,085 | The *pathspec* package provides pattern matching for file paths. So far
this only includes Git's wildmatch pattern matching (the style used for
".gitignore" files).
The following classes are imported and made available from the root of
the `pathspec` package:
- :class:`pathspec.pathspec.PathSpec`
- :class:`pathspec.... | 710 | en | 0.595565 |
#!/usr/bin/python3
# *****************************************************************************
#
# 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 ... | infrastructure-provisioning/src/general/scripts/os/common_clean_instance.py | 8,118 | !/usr/bin/python3 ***************************************************************************** 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 t... | 1,104 | en | 0.763016 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 17:18:43 2020
@author: admangli
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
dataset = pd.read_csv('Ads_CTR_Optimisation.csv').values
#%%
slot_machines = 10
#%% Random ad selection reward
import rand... | Machine Learning/Sklearn Implementations/Reinforcement Learning/Upper_Confidence_Bound.py | 2,201 | Created on Fri Mar 27 17:18:43 2020
@author: admangli
!/usr/bin/env python3 -*- coding: utf-8 -*-%%%% Random ad selection reward%% To get an idea of underlying distributino Generate initial seed, selecting each machine at least once randomly Calculate Ri and Delta for each ad for the current round Pick the ad with ma... | 497 | en | 0.854125 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base import Loss
class AdaCos(Loss):
"""PyTorch implementation of AdaCos. See Ref[1] for paper
This implementation is different from the most open-source implementations in following ways:
1) expects raw logits of size ... | pytorch_tools/losses/angular.py | 2,914 | PyTorch implementation of AdaCos. See Ref[1] for paper
This implementation is different from the most open-source implementations in following ways:
1) expects raw logits of size (bs x num_classes) not (bs, embedding_size)
2) despite AdaCos being dynamic, still add an optional margin parameter
3) calculate running ave... | 925 | en | 0.709046 |
"""
IGN Instituto Geográfico Nacional Sismología Feed.
Fetches GeoRSS feed from IGN Instituto Geográfico Nacional Sismología.
"""
from datetime import datetime
from typing import Optional
import dateparser as dateparser
from georss_client import FeedEntry, GeoRssFeed
from georss_client.consts import CUSTOM_ATTRIBUTE
... | georss_ign_sismologia_client/__init__.py | 4,639 | IGN Sismología feed.
IGN Sismología feed entry.
Feed Manager for IGN Sismología feed.
Initialize the IGN Sismología Feed Manager.
Initialise this service.
Initialise this service.
Return string representation of this feed.
Filter the provided entries.
Generate a new entry.
Return the short id of this entry.
Return the ... | 729 | en | 0.68694 |
''' convenience functions for ANOVA type analysis with OLS
Note: statistical results of ANOVA are not checked, OLS is
checked but not whether the reported results are the ones used
in ANOVA
includes form2design for creating dummy variables
TODO:
* ...
*
'''
import numpy as np
#from scipy import stats
import sta... | statsmodels/sandbox/regression/try_ols_anova.py | 9,151 | from scipy import statsbrute force, assumes x is 2dreplace with encoding if possibleincludes singularity with additive factors Result stringsthe second leaves the constant in, not with NIST regressionbut something fishy with res.ess negative in examples ?not checked if these are all the right onesdict doesn't work with... | 1,333 | en | 0.589562 |
# Copyright 2020 Konstruktor, Inc. 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 la... | tethys/bin/cli.py | 994 | Tethys apps manager
The tethys CLI for managing your environment.
Copyright 2020 Konstruktor, Inc. 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/lic... | 643 | en | 0.852221 |
"""
This code was taken from https://github.com/ActiveState/appdirs and modified
to suite our purposes.
"""
import os
import sys
from pip._vendor import six
def user_cache_dir(appname):
r"""
Return full path to the user-specific cache dir for this application.
"appname" is the name of application.
... | pip/appdirs.py | 4,328 | This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
Return full path to the user-specific cache dir for this application.
"appname" is the name of application.
Typical user cache directories are:
Mac OS X: ~/Library/Caches... | 1,527 | en | 0.728566 |
# https://github.com/theeko74/pdfc
# modified by brio50 on 2022/01/23, working with gs version 9.54.0
"""
Simple python wrapper script to use ghoscript function to compress PDF files.
Compression levels:
0: default
1: prepress
2: printer
3: ebook
4: screen
Dependency: Ghostscript.
On MacOSX insta... | gs_compress.py | 6,123 | Function to compress PDF via Ghostscript command line interface
Simple python wrapper script to use ghoscript function to compress PDF files.
Compression levels:
0: default
1: prepress
2: printer
3: ebook
4: screen
Dependency: Ghostscript.
On MacOSX install via command line `brew install ghostscri... | 954 | en | 0.727137 |
# -*- 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/recommendationengine/v1beta1/recommendationengine-v1beta1-py/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py | 45,048 | Service for ingesting end user actions on the customer
website.
Metaclass for the UserEventService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
Releases underlying transport's resources.
.. warning::
ONLY use ... | 23,188 | en | 0.752753 |
# -*- coding: utf-8 -*-
import os
import re
from math import radians, degrees
import numpy as np
import pandas as pd
import cv2
from pdftabextract import imgproc
from pdftabextract.geom import pt
from pdftabextract.common import read_xml, parse_pages, save_page_grids
from pdftabextract.textboxes import rotate_textbo... | examples/eg1/eg1.py | 14,963 | -*- coding: utf-8 -*-%% Some constantsDATAPATH = 'data/'DATAPATH = 'ip/'OUTPUTPATH = 'generated_output/'OUTPUTPATH = 'op/'INPUT_XML = 'output.xml'INPUT_XML = 'output.xml' minimum height of a row in pixels, measured in the scanned pages very important. the minimum width of a column in pixels, measured in the scanned pag... | 4,393 | en | 0.845568 |
# coding=utf-8
import sys
import argparse
import os
from tensorflow.python.platform import gfile
import numpy as np
import tensorflow as tf
from tensorflow.python.layers.core import Dense
from utils.data_manager import load_data, load_data_one
from collections import defaultdict
from argparse import ArgumentParser
fro... | main.py | 11,385 | coding=utf-8arg_parser.add_argument('--tran_data', choices=['wikisql', 'spider', 'overnight'], default='overnight', help='data to transfer') Model configuration default=20452, Embedding sizesHidden sizes Training training details decoding/validation/testing [print(n.name) for n in tf.get_default_graph().as_graph_def()... | 534 | en | 0.362491 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils import timezone
class Migration(migrations.Migration):
dependencies = [
('nationalparks', '0009_auto_20150831_1721'),
]
operations = [
migrations.AddField(
... | ekip/nationalparks/migrations/0010_auto_20150902_1902.py | 888 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Copyright 2015 Internap.
#
# 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... | fake_switches/command_processing/base_command_processor.py | 4,660 | :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase
Copyright 2015 Internap. Licensed unde... | 828 | en | 0.759456 |
from __future__ import division
import sys
class Inf(float):
__name__ = __name__
__file__ = __file__
@staticmethod
def div(p, q):
"""
``p / q`` returning the correct infinity instead of
raising ZeroDivisionError.
"""
from math import copysign
if q !=... | inf.py | 757 | ``p / q`` returning the correct infinity instead of
raising ZeroDivisionError.
Normal case, no infinities. Doesn't return, raises an Exception. q is +0.0, return inf with same sign as p. q is -0.0, return inf with flipped sign. | 229 | en | 0.875042 |
import os
import numpy as np
from shapely.geometry import box, Polygon
import geopandas as gpd
from ..utils.core import _check_gdf_load, _check_crs
from ..utils.tile import save_empty_geojson
from ..utils.geo import gdf_get_projection_unit, split_multi_geometries
from ..utils.geo import reproject_geometry
from tqdm imp... | 3-SatShipAI/solaris/tile/vector_tile.py | 14,194 | An object to tile geospatial vector data into smaller pieces.
Arguments
---------
Attributes
----------
Clip GDF to a provided polygon.
Clips objects within `gdf` to the region defined by
`poly_to_cut`. Also adds several columns to the output::
`origarea`
The original area of the polygons (only used if... | 7,035 | en | 0.583641 |
import os
import argparse
import gym
from gym import envs
import numpy as np
from skimage import transform
from stable_baselines.common.atari_wrappers import WarpFrame
from stable_baselines.common.vec_env import VecVideoRecorder, VecFrameStack, VecNormalize
from .utils import ALGOS, create_test_env, get_saved_hyper... | utils/record_video.py | 4,306 | -----------------------------------------import dVRL_simulator----------------------------------------- Sanity checksenv = RGBobs(env)obs = cv2.cvtColor(obs, cv2.COLOR_RGB2GRAY) ADDED 2obs = cv2.resize(obs, (84,84), interpolation=cv2.INTER_AREA) ADDED 2obs_dummy = env.reset() ADDED 1obs = transform.resize(obs_dummy, (8... | 609 | en | 0.48827 |
from __future__ import absolute_import
from __future__ import unicode_literals
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
from builtins import next
from builtins import chr
from builtins import str
from builtins import range
from builtins import object
import copy
import os
import gevent
fro... | src/config/common/cfgm_common/vnc_cassandra.py | 73,932 | Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. end _get_resource_class end get_db_info TODO(sahid): To satisfy test-framework which has its specific py3 support for thrift we can have the above condition, when that will be fixed we could uncomment the code.if six.PY3: raise VncError( "selected... | 7,442 | en | 0.738152 |
import django
import six
from django.http import HttpResponseRedirect
if django.VERSION[0] < 2:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
from django.db import transaction
from django.utils import timezone
import logging
from processlib.assignment import inherit
from ... | processlib/activity.py | 14,466 | An async activity that renders a view while the async task is running.
The view could be AsyncActivityView with a custom template_name
An activity that simple serves as a marker for a certain state being reached, e.g.
if the activity before it was conditional.
ensure that we have a single referenced process object HA... | 508 | en | 0.915931 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import sys
def update_allure_feature_name(results_dir: str, prefix: str):
"""Make Allure JSON results unique by pre-pending a prefix to: name, historyId & uuid.
Use it when not all of the test results show up in the Allure report.
This ... | update_results.py | 1,324 | Make Allure JSON results unique by pre-pending a prefix to: name, historyId & uuid.
Use it when not all of the test results show up in the Allure report.
This is because tests from different workers can actually have the same: historyId & uuid values.
You can use e.g. browser name as the prefix.
!/usr/bin/env python... | 343 | en | 0.839487 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('forms', '0016_auto_20150330_1413'),
]
operations = [
migrations.AlterField(
model_name='radiosheet',
... | forms/migrations/0017_auto_20150331_1815.py | 1,610 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | sdk/python/pulumi_azure_native/datafactory/private_endpoint_connection.py | 9,605 | The set of arguments for constructing a PrivateEndpointConnection resource.
:param pulumi.Input[str] factory_name: The factory name.
:param pulumi.Input[str] resource_group_name: The resource group name.
:param pulumi.Input[str] private_endpoint_connection_name: The private endpoint connection name.
:param pulumi.Input... | 1,939 | en | 0.614426 |
#!/usr/bin/env python
# coding: utf-8
# # WORKFLOW PROCEDURE
# In[ ]:
# import utilities
from ds_utils import *
# to plot results
get_ipython().run_line_magic('matplotlib', 'inline')
# ## How to use this code:
#
# ### Step 1
#
# From a list of train and test datasets run the baseline_generator function and ch... | workflow_procedure_example.py | 6,285 | len of list_estimators and list_params should be the same. For any
estimator you need a list of parameters to optimize. Eg
list_estimators = [RandomForestClassifier(),
LogisticRegression()]
list_params = [{'n_estimators': [500,1000],
'max_features': [8,10],
'max_depth' : [4,6,8],
'criterion' :['gini... | 3,931 | en | 0.874581 |
# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
# pylint:disable=protected-access
import json
import re
import urllib.parse
from collections import namedtuple
from pathlib import Path
from random import randint
from typing import Callable, List
from uuid import u... | services/director-v2/tests/unit/test_modules_director_v0.py | 7,725 | set a minimal configuration for testing the director connection only
pylint:disable=unused-variable pylint:disable=unused-argument pylint:disable=redefined-outer-name pylint:disable=protected-access lists services TODO: here we see the return value is currently not validated TODO: here we see the return value is curr... | 404 | en | 0.693469 |
#!/usr/bin/env python3
# Copyright (c) 2015-2018 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.blocktools import get_masternode_payment, create_coinbase, create_block
from test_framewo... | qa/rpc-tests/llmq-is-cl-conflicts.py | 13,224 | !/usr/bin/env python3 Copyright (c) 2015-2018 The Dash Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.disable_mocktime() Start up network handling in another thread mine single block, wait for chainlock create three raw... | 1,660 | en | 0.913163 |
#!/usr/bin/env python
#
# @file test_signals.py
#
# @author Matt Gigli <mjgigli@gmail.com>
#
# @section LICENSE
#
# The MIT License (MIT)
# Copyright (c) 2016 Matt Gigli
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"... | test/test_signals.py | 5,941 | !/usr/bin/env python @file test_signals.py @author Matt Gigli <mjgigli@gmail.com> @section LICENSE The MIT License (MIT) Copyright (c) 2016 Matt Gigli 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 Softwar... | 2,081 | en | 0.924985 |
"""Various functions that interact with Slack, e.g. posting messages."""
import asyncio
import logging
import socket
from pathlib import Path
from typing import Union, Optional
from slack_sdk.errors import SlackApiError
from lsw_slackbot.plots import plot_resource_use
from lsw_slackbot.resources import current_memory... | lsw_slackbot/slack.py | 4,849 | Various functions that interact with Slack, e.g. posting messages.
Handle various different errors, *some* of which are non-critical... Handle various different errors, *some* of which are non-critical... Todo: it would be really cool if hello_world also printed the latest commit message. This could be done by runn... | 756 | en | 0.877996 |
from contextlib import contextmanager
import platform
import shlex
from subprocess import PIPE, Popen
from shutil import which
class ShellCommandResult(tuple):
"""
The result of a :func:`coalib.misc.run_shell_command` call.
It is based on a ``(stdout, stderr)`` string tuple like it is returned
form `... | venv/lib/python3.5/site-packages/coalib/misc/Shell.py | 5,916 | The result of a :func:`coalib.misc.run_shell_command` call.
It is based on a ``(stdout, stderr)`` string tuple like it is returned
form ``subprocess.Popen.communicate`` and was originally returned from
:func:`coalib.misc.run_shell_command`. So it is backwards-compatible.
It additionally stores the return ``.code``:
... | 3,889 | en | 0.768537 |
#!/usr/bin/env python
import numpy as np
def initialize_hyper_parameters(layer_acts, learning_rate):
"""
Initialize parameters for different levels of the network
Arguments:
layer_acts -- python array (list) containing the activation functions of each layer in the network
learning_rate -- float ... | utils/init_parameters.py | 3,319 | Initialize parameters for different levels of the network
Arguments:
layer_acts -- python array (list) containing the activation functions of each layer in the network
learning_rate -- float value used as constant for gradient descent
Returns:
hyper_parameters -- python dictionary containing hyper_parameters (can be ... | 825 | en | 0.551498 |
"""
Code for particle tracking, designed for ROMS output. This new version
makes extensive use of nearest-neighbor KDTree algorithms for interpolation.
This results is significantly (36x) faster runtimes compared with old version.
PERFORMANCE: about 3 minutes per day for a 3D cas6 experiment with 10k particles.
NOTE... | tracker/tracker/user_tracker.py | 9,682 | Code for particle tracking, designed for ROMS output. This new version
makes extensive use of nearest-neighbor KDTree algorithms for interpolation.
This results is significantly (36x) faster runtimes compared with old version.
PERFORMANCE: about 3 minutes per day for a 3D cas6 experiment with 10k particles.
NOTE: Yo... | 4,390 | en | 0.845306 |
"""
Custom Decorators
"""
# Django
from django.shortcuts import redirect, reverse
from django.http import JsonResponse
from django.utils.translation import gettext as _
from django.http import Http404
# local Django
from app.modules.util.helpers import Helpers
from app.modules.core.response import Response
from app.m... | app/modules/core/decorators.py | 3,339 | Custom Decorators
Django local Django | 39 | en | 0.156442 |
from datetime import datetime, timedelta
from django.test import TestCase
from mock import patch
from corehq.apps.domain.models import Domain
from corehq.apps.hqcase.utils import update_case
from corehq.apps.sms.mixin import PhoneNumberInUseException
from corehq.apps.sms.models import (
PhoneNumber,
SQLMobil... | corehq/apps/sms/tests/test_phone_numbers.py | 34,381 | A test to make sure that the cache clearing is working as expected.
This test gets run twice using different values for refresh_each_time.
This makes sure that the mechanism used for clearing the cache works
whether you're updating a document you just saved or getting a document
fresh from the database and updating it.... | 688 | en | 0.85646 |
from hash_map_base_class import *
class ProbeHashMap(HashMapBase):
"""Hash map implemented with linear probing for collision resolution."""
_AVAIL = object() # sentinal marks locations of previous deletions
def _is_available(self,j):
"""Return True if the index j is available in the table."""
... | CHAPTER 10 (maps, hash tables and skip lists)/probe_hash_map_class.py | 2,186 | Hash map implemented with linear probing for collision resolution.
Search for key k in bucket at index j.
Return (success, index) tuple, described as follows:
If match was found, success is True and index denotes its location.
If no match found, success is False and index denotes first available slot.
Return True if t... | 607 | en | 0.912212 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('filer', '0009_auto_20171220_1635'),
]
operations = [
migrations.AlterField(
model_name='image',
name... | filer/migrations/0010_auto_20180414_2058.py | 519 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
"""Tests for solver module
"""
# from mathgrid import solver
from mathgrid import solver
def test_calculator_01():
assert solver.calculator('=((1+3)*2)/(6-4)') == 4
assert solver.calculator('((1+3)*2)/(6-4)') == '((1+3)*2)/(6-4)'
assert solver.calculator('=hola') == 'hola'
| tests/test_solver.py | 289 | Tests for solver module
from mathgrid import solver | 53 | en | 0.744333 |
"""
Tests for various datasette helper functions.
"""
from datasette.app import Datasette
from datasette import utils
from datasette.utils.asgi import Request
from datasette.utils.sqlite import sqlite3
import json
import os
import pathlib
import pytest
import tempfile
from unittest.mock import patch
@pytest.mark.para... | tests/test_utils.py | 20,731 | Tests for various datasette helper functions.
Test order is preserved Run the test again but this time use the path= argument Default usage of this should use symlink It should be a hard link Copy instead if os.link raises OSError (normally due to different device) Default usage of this should use symlink It should b... | 741 | en | 0.763793 |
import pgzero
import pgzrun
import random
from pgzero.actor import Actor
__all__ = ["pgzrun", "pgzero"]
from pgzero.clock import clock
from pgzero.keyboard import keyboard
from pgzero.loaders import sounds
clouds = [Actor('cloud1', (200, 200)),
Actor('cloud2', (400, 300)),
Actor('cloud3', (600, ... | dino/main.py | 6,669 | 0 - game not started 1 - game just stared 2 - finished frame that is currently running player movement speed and direction 0 - jump is available 1 - jump is forbidden cactus movement speed 0 - game running 1 - game blocked change difficulty level, increase game and clouds speed reset global variables change difficulty ... | 818 | en | 0.92168 |
"""
A pure python (slow) implementation of rijndael with a decent interface
To include -
from rijndael import rijndael
To do a key setup -
r = rijndael(key, block_size = 16)
key must be a string of length 16, 24, or 32
blocksize must be 16, 24, or 32. Default is 16
To use -
ciphertext = r.encrypt(plaintext)
plai... | benchmarks/crypto.py | 11,029 | A pure python (slow) implementation of rijndael with a decent interface
To include -
from rijndael import rijndael
To do a key setup -
r = rijndael(key, block_size = 16)
key must be a string of length 16, 24, or 32
blocksize must be 16, 24, or 32. Default is 16
To use -
ciphertext = r.encrypt(plaintext)
plaintex... | 1,386 | en | 0.776632 |
# (c) 2019, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
''' unit tests for Ansible module: na_ontap_rest_cli'''
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import pytest
from ansible.module_utils impo... | venv/lib/python3.6/site-packages/ansible_collections/netapp/ontap/tests/unit/plugins/modules/test_na_ontap_rest_cli.py | 6,968 | Exception class to be raised by module.exit_json and caught by the test case
Exception class to be raised by module.fail_json and caught by the test case
Unit tests for na_ontap_job_schedule
function to patch over exit_json; package return data into an exception
function to patch over fail_json; package return data in... | 873 | en | 0.760083 |
# Copyright 2016 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/contrib/learn/python/learn/basic_session_run_hooks.py | 14,433 | Saves checkpoints every N steps or seconds.
Prints given tensors every N iteration.
The tensors will be printed to the log, with `INFO` severity.
NaN Loss monitor.
Monitors loss and stops training if loss is NaN.
Can either fail with exception or just stop training.
Steps per second monitor.
Monitor to request stop a... | 3,544 | en | 0.78129 |
import unittest
from my_lambdata.assignment1 import WrangledFrame
class TestWrangledFrame(unittest.TestCase):
def test_add_state_names(self):
wf = WrangledFrame({"abbrev": ["CA", "CO", "CT", "DC", "TX"]})
breakpoint()
wf.add_state_names()
# ensure there is a "name" column
... | tests/wrangled_test.py | 623 | ensure there is a "name" column ensure the values of WF are specific classes/values (string, "California") | 106 | en | 0.653227 |
# -*- coding:utf-8 -*-
"""
博客系统。
"""
import pymysql
pymysql.install_as_MySQLdb()
| end/nebulablogs/__init__.py | 95 | 博客系统。
-*- coding:utf-8 -*- | 28 | zh | 0.797089 |
# -*- coding: utf-8 -*-
import pytest
import tempfile
from jsonschema import ValidationError
from rasa.nlu import training_data
from rasa.nlu.convert import convert_training_data
from rasa.nlu.extractors.mitie_entity_extractor import MitieEntityExtractor
from rasa.nlu.tokenizers.whitespace_tokenizer import Whitespace... | tests/nlu/base/test_training_data.py | 17,950 | -*- coding: utf-8 -*- The order changes based on different computers hence the grouping converting the converted file back to original file format and performing the same tests If the above assert fails - this can be used to dump to the file and diff using git with io.open(gold_standard_file) as f: f.write(td.as_js... | 333 | en | 0.88665 |
# 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 ... | sdk/keyvault/azure-keyvault/azure/keyvault/v7_3_preview/models/sas_definition_create_parameters.py | 2,461 | The SAS definition create parameters.
All required parameters must be populated in order to send to Azure.
:param template_uri: Required. The SAS definition token template signed
with an arbitrary key. Tokens created according to the SAS definition
will have the same properties as the template.
:type template_uri:... | 1,343 | en | 0.548296 |
# 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/.
from iris.test_case import *
class Test(BaseTest):
def __init__(self, app):
BaseTest.__init__(self, app)... | iris/tests/experiments/private_browsing_mode.py | 954 | 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/. check if incognito mode works check basic_url in incognito mode | 256 | en | 0.875146 |
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
app = Flask(__name__)
# LINE BOT info
line_bot_api = LineBotApi('QCynFfsDk7My1YN72sVQyvk6ArYkD2TUQW/pUxUQqllnGFNcqjZ8tKC+qMcVa2u4Lg1W... | Final_Project/hx711py/lineBotTest.py | 1,229 | LINE BOT info Message event | 27 | en | 0.130694 |
#!/usr/bin/env python3
# still in development
#
import asyncio
import websockets
import json
import requests
eventsAPIPath = '/api/v1/events'
localServerIP = '0.0.0.0'
localServerAPIPort = '8000'
localServerWSPort = '8000'
localServerPath = '/sealog-server'
localToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI... | misc/sealog_repeater_receive.py | 2,257 | !/usr/bin/env python3 still in development end of repeat | 56 | en | 0.672453 |
"""
https://leetcode.com/problems/powerful-integers/
Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0.
Return a list of all powerful integers that have value less than or equal to bound.
You may return the answer in any order. In your answer,... | easy/970-Powerful Integers.py | 1,135 | https://leetcode.com/problems/powerful-integers/
Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0.
Return a list of all powerful integers that have value less than or equal to bound.
You may return the answer in any order. In your answer, eac... | 714 | en | 0.834791 |
class RenderNodeAction(Enum,IComparable,IFormattable,IConvertible):
"""
Enumerated actions for processing a render node during custom export.
enum RenderNodeAction,values: Proceed (0),Skip (1)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
... | stubs.min/Autodesk/Revit/DB/__init___parts/RenderNodeAction.py | 968 | Enumerated actions for processing a render node during custom export.
enum RenderNodeAction,values: Proceed (0),Skip (1)
x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y
__format__(formattable: IFormattable,format: str) -> str
x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__i... | 451 | en | 0.429152 |
import numpy as np
import torch
from dataclasses import dataclass
from typing import List
from jiant.tasks.core import (
BaseExample,
BaseTokenizedExample,
BaseDataRow,
BatchMixin,
GlueMixin,
Task,
TaskTypes,
)
from jiant.tasks.lib.templates.shared import double_sentence_featurize, labels_t... | jiant/tasks/lib/wnli.py | 2,829 | NOTE: get_glue_preds() is dependent on this guid format. | 56 | en | 0.472587 |
# Copyright 2015 Google Inc. 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 ... | modules/balancer/balancer.py | 23,311 | Base error class.
DAO for external tasks.
Raised when an op that needs an entity is run with a missing entity.
DTO for external tasks.
Raised when an op attempts an invalid transition on a task.
Storage for external tasks.
Base class for wire operation payloads.
Interface for the pool of machines that do background wor... | 5,500 | en | 0.885711 |
"""
CLI tests
"""
from tso.tsocli import __main__ as tsocli
import pytest
from unittest.mock import patch, MagicMock, mock_open
mock_configurqation = "{}"
class TestCli:
def test_cli_should_exit_with_no_args(self):
with pytest.raises(SystemExit) as pytest_wrapped_e:
tsocli.main([])
... | src/tso/tsocli/tests/test_cli.py | 2,032 | CLI tests
Both Exceptions should be the same The exceptions should be a System Exit | 85 | en | 0.83666 |
#
# 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... | tests/providers/microsoft/azure/transfers/test_local_to_wasb.py | 2,571 | 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... | 752 | en | 0.883564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.