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 |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
:mod:`plots` -- Tests data plots
================================
.. module:: plots
:platform: Unix, Windows
:synopsis: Tests of the raster plots and processed data plots.
.. moduleauthor:: Andre Rocha <rocha.matcomp@gmail.com>
"""
import matplotlib.pyplot as plt
from matplotlib.te... | tests/test_plots.py | 1,439 | Test the rasters plot as multiples subplots.
:mod:`plots` -- Tests data plots
================================
.. module:: plots
:platform: Unix, Windows
:synopsis: Tests of the raster plots and processed data plots.
.. moduleauthor:: Andre Rocha <rocha.matcomp@gmail.com>
-*- coding: utf-8 -*- | 305 | en | 0.465421 |
"""
A python script to run a parameter sweep
"""
# Python tools
import numpy as np
import yaml
import os
# WISDEM tools
from wisdem.aeroelasticse import runFAST_pywrapper, CaseGen_General
from wisdem.aeroelasticse.Util import FileTools
# ROSCO tools
from ROSCO_toolbox import controller as ROSCO_controller
from ROSCO_to... | runBatch/run_FlapGainSweep_BAR.py | 6,479 | A python script to run a parameter sweep
Python tools WISDEM tools ROSCO tools FLAGS Controller tuning yaml Generate case inputs for control related stuff values = [[0.7], [2.73]] use np.around to avoid precision issues Some path specifics/ FAST input file (ext=.fst) FAST input file (ext=.fst) Wind Time Turbine Defin... | 872 | en | 0.511581 |
import requests
import time
from bs4 import BeautifulSoup
class crawl:
"""Keep track of time between scrape requests.
args:
wait: time between requests
retry_max: number of times to retry
"""
def __init__(self, wait, retry_max):
self.wait = wait
self.retry_max = retry_... | manual_crawler.py | 1,549 | Keep track of time between scrape requests.
args:
wait: time between requests
retry_max: number of times to retry
can let user scrape faster the first time. sleep for successively longer times | 202 | en | 0.945938 |
# Copyright 2019 Uber Technologies, 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 applica... | horovod/spark/keras/tensorflow.py | 4,565 | Handles custom object lookup.
Arguments:
obj: object, dict, or list.
Returns:
The same structure, where occurrences
of a custom object name have been replaced
with the custom object.
Copyright 2019 Uber Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (t... | 924 | en | 0.820926 |
# -----------------------------------------------------------------------------
# Copyright (c) 2021 Trevor P. Martin. All rights reserved.
# Distributed under the MIT License.
# -----------------------------------------------------------------------------
from Data import encode_data
# from utils import cross_validati... | sub_models.py | 23,095 | Parameters
----------
dataset: a string {nn269, ce, hs3d} indicating which dataset to use
splice_site_type: a string {acceptor, donor} indicating which splice
site to train on
model_architecture: a string {cnn, dnn, rnn} indicating which model
architecture to use for training
save_model: boolean, whether to sav... | 10,776 | en | 0.442838 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import enum
from builtins import _test_sink, _test_source
from typing import Annotated, Any, Dict, List
class Test1_C:
x: int = 0
... | source/interprocedural_analyses/taint/test/integration/via_type_of.py | 3,229 | Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. always-via-type:int always-via-type:str always-via-type:typing.Annotated[str] via-type:int, via-type:str, via-type:typing.Annotated[str] always-via-t... | 718 | en | 0.334962 |
import os
import anyconfig
PARSABLES = {
'pickle':['p','pickle'],
'toml':['toml'],
'xml':['xml'],
'yaml':['yml','yaml'],
'json':['json'],
'ini':['ini'],
'properties':['props','properties'],
'shellvars':['env']}
class Source(object):
def __init__(self, uri, root_path=None, cont... | flange/source.py | 2,072 | if the file had a known extension but didn't parse, raise an exception. The danger is that it be parsed incorrectly as properties file which seems to match everything print type(e) 'exception parsing {}\t{}'.format(ext, e) print type(e) 'exception parsing as ', p, ' ', e | 272 | en | 0.921938 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'picscope.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| picscope/urls.py | 299 | Examples: url(r'^$', 'picscope.views.home', name='home'), url(r'^blog/', include('blog.urls')), | 95 | en | 0.359796 |
"""Data Helpers
Data helpers leverage the abstraction layer of ArchivesSnake to provide
additional functionality for retrieving, inferring and concatenating data
elements. They can also extend (or invert) relationships between different
objects.
"""
from datetime import datetime
import re
from rapidfuzz import fuzz
f... | rac_aspace/data_helpers.py | 8,346 | Finds the closest value matching a key.
Starts with an archival object, and iterates up through its ancestors
until it finds a match for a key that is not empty or null.
:param JSONModelObject archival_object: an ArchivesSpace archival_object.
:param str key: the key to match against.
:returns: The value of the key,... | 3,058 | en | 0.722661 |
# Copyright (c) 2009-2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functiona... | gem5/src/dev/arm/RealView.py | 40,675 | ARM CoreTile Express A15x2 Daughterboard Configuration Controller
This subsystem describes a subset of the devices that sit behind the
daughterboard configuration controller on a CoreTile Express A15x2. See
ARM DUI 0604E for details.
ARM V2M-P1 Motherboard Configuration Controller
This subsystem describes a subs... | 9,225 | en | 0.85409 |
#!/usr/bin/env python
# File: plot_icd_vs_colorgrad.py
# Created on: Tue 08 May 2012 11:03:26 AM CDT
# Last Change: Sun 21 Oct 2012 02:43:33 PM CDT
# Purpose of script: <+INSERT+>
# Author: Steven Boada
import pylab as pyl
from mk_galaxy_struc import mk_galaxy_struc
galaxies = mk_galaxy_struc()
f1 = pyl.figure(1,fig... | sandbox/legacy_plot_code/plot_icd_vs_colorgrad_vs_sersic.py | 1,979 | !/usr/bin/env python File: plot_icd_vs_colorgrad.py Created on: Tue 08 May 2012 11:03:26 AM CDT Last Change: Sun 21 Oct 2012 02:43:33 PM CDT Purpose of script: <+INSERT+> Author: Steven Boadapyl.scatter(galaxy.ICD_IH,galaxy.Color_grad,s=50,edgecolor='w')f1s1.vlines(0.04,-3.,1,lw=2,zorder=0)f1s1.hlines(0.0,-0.1,0.25,lw=... | 698 | en | 0.43007 |
# -*- coding: utf-8 -*-
"""
babel.messages.mofile
~~~~~~~~~~~~~~~~~~~~~
Writing of files in the ``gettext`` MO (machine object) format.
:copyright: (c) 2013 by the Babel Team.
:license: BSD, see LICENSE for more details.
"""
import array
import struct
from babel.messages.catalog import Catalog, ... | desktop/core/ext-py/Babel-2.5.1/babel/messages/mofile.py | 7,294 | Read a binary MO file from the given file-like object and return a
corresponding `Catalog` object.
:param fileobj: the file-like object to read the MO file from
:note: The implementation of this function is heavily based on the
``GNUTranslations._parse`` method of the ``gettext`` module in the
standard ... | 2,635 | en | 0.60942 |
import sys
import logging
import urlparse
import urllib
import redis
from flask import Flask, current_app
from flask_sslify import SSLify
from werkzeug.contrib.fixers import ProxyFix
from werkzeug.routing import BaseConverter
from statsd import StatsClient
from flask_mail import Mail
from flask_limiter import Limiter
... | redash/__init__.py | 4,345 | Make noisy libraries less noisy Redis passwords might be quoted with special characters This is ay workaround for when we enable multi-org and some files are being called by the index rule: for path in settings.STATIC_ASSETS_PATHS: full_path = safe_join(path, value) if os.path.isfile(full_path): raise V... | 435 | en | 0.867426 |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 5
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class SnapshotScheduleExtended(o... | isi_sdk_8_1_0/isi_sdk_8_1_0/models/snapshot_schedule_extended.py | 9,661 | 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
SnapshotScheduleExtended - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the alias of this SnapshotScheduleExtended. # ... | 4,273 | en | 0.646334 |
from decimal import Decimal as D
from django.utils.translation import ugettext_lazy as _
from oscar.core.loading import get_class, get_classes, get_model
from oscar.templatetags.currency_filters import currency
Benefit = get_model('offer', 'Benefit')
BasketDiscount, SHIPPING_DISCOUNT, ZERO_DISCOUNT = get_classes('of... | src/oscar/apps/offer/benefits.py | 11,852 | An offer benefit that gives an absolute discount
An offer benefit that gives the items in the condition for a
fixed price. This is useful for "bundle" offers.
Note that we ignore the benefit range here and only give a fixed price
for the products in the condition range. The condition cannot be a value
condition.
We... | 1,251 | en | 0.926654 |
import os
import shutil
import tempfile
import time
class TemporaryDirectory():
def __init__(self, remove: bool=True, prefix: str='tmp'):
self._remove = remove
self._prefix = prefix
def __enter__(self) -> str:
if 'KACHERY_STORAGE_DIR' in os.environ:
storage_dir = os.getenv... | kachery/_temporarydirectory.py | 1,732 | maybe somebody else created this directory pragma: no cover | 59 | en | 0.926715 |
# --------------------------------------------------------
# Deformable Convolutional Networks
# Copyright (c) 2017 Microsoft
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Modified by Haozhi Qi, from py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn)
# ----------------------------------... | lib/dataset/pascal_voc.py | 19,551 | -------------------------------------------------------- Deformable Convolutional Networks Copyright (c) 2017 Microsoft Licensed under The Apache-2.0 License [see LICENSE for details] Modified by Haozhi Qi, from py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn) ----------------------------------------------... | 832 | en | 0.624463 |
from typing import List
from yandex_market_language import models, exceptions
from yandex_market_language.models import fields
from yandex_market_language.models.abstract import XMLElement, XMLSubElement
from yandex_market_language.exceptions import ValidationError
class Shop(
fields.EnableAutoDiscountField,
... | yandex_market_language/models/shop.py | 8,099 | Shop model.
Docs:
https://yandex.ru/support/partnermarket/elements/shop.html
Add simple elements Add currencies Add categories Add delivery options Add pickup options Add enable_auto_discounts Add offers Add gifts Add promos | 227 | en | 0.244726 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-10-02 09:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hkm', '0025_userprofile_printer_presets'),
]
operations = [
migrations.AddF... | hkm/migrations/0026_hkm_museum_printer_credentials.py | 749 | -*- coding: utf-8 -*- Generated by Django 1.10.2 on 2017-10-02 09:43 | 68 | en | 0.729437 |
# =============================================================================
# IMPORTS
# =============================================================================
import torch
from espaloma.nn.readout.base_readout import BaseReadout
# ===========================================================================... | espaloma/nn/readout/node_typing.py | 812 | Simple typing on homograph.
============================================================================= IMPORTS ============================================================================= ============================================================================= MODULE CLASSES =================================... | 364 | en | 0.325539 |
from __future__ import print_function, division
import json
import torch
from torch.utils.data import Dataset
import numpy as np
import os
import sys
import collections
import torch.utils.data as data
import shutil
from PIL import Image
from torchvision.datasets.utils import download_url, check_integrity
class ADE20KD... | datasets/ade.py | 2,476 | assert(seg.ndim == 2) | 21 | pt | 0.335081 |
# coding: utf-8
#
# Copyright 2018 Moriyoshi Koizumi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... | dummydf/sql/dataframe.py | 8,652 | coding: utf-8 Copyright 2018 Moriyoshi Koizumi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di... | 1,376 | en | 0.88211 |
from kivy.uix.screenmanager import Screen
# Declara o Menu do Jogo
class TelaMenu(Screen):
pass
# Declara a Tela do Pong
class TelaJogo(Screen):
pass
# Declara a Tela do Vencedor 3
class TelaVencedor1(Screen):
pass
# Declara a Tela do Vencedor 2
class TelaVencedor2(Screen):
pass
| Jogo_pong/telas/Telas.py | 304 | Declara o Menu do Jogo Declara a Tela do Pong Declara a Tela do Vencedor 3 Declara a Tela do Vencedor 2 | 103 | pt | 0.834372 |
""" Get a list of Packages in CI, Deployed, or all Images """
from __future__ import print_function
from pc_lib import pc_api, pc_utility
# --Configuration-- #
parser = pc_utility.get_arg_parser()
parser.add_argument(
'--mode',
type=str,
choices=['ci', 'deployed', 'all'],
default='all',
help='(Op... | pcs_images_packages_read.py | 7,545 | Get a list of Packages in CI, Deployed, or all Images
--Configuration-- --Helpers-- --Initialize-- --Main-- Monitor > Vulnerabilities/Compliance > Images > Deployed TODO: Verify instances array length. Monitor > Vulnerabilities/Compliance > Images > CI | 259 | en | 0.476926 |
from abc import ABC
from types import NoneType
import logictest
import http_connector
from log import log
class TestHttp(logictest.SuiteRunner, ABC):
def __init__(self, kind, pattern):
super().__init__(kind, pattern)
self._http = None
def get_connection(self):
if self._http is None:... | tests/logictest/http_runner.py | 3,057 | include data, timestamp, dict, list ... bool to string in python will be True/False | 83 | en | 0.766479 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 18:05
from __future__ import unicode_literals
import common.blocks.columns
import common.blocks.tabs
from django.db import migrations, models
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailembeds.blocks
import... | common/migrations/0018_auto_20161014_1805.py | 4,371 | -*- coding: utf-8 -*- Generated by Django 1.10.2 on 2016-10-14 18:05 | 68 | en | 0.663651 |
# Copyright 2013 IBM Corp
# 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 appl... | yardstick/dispatcher/http.py | 3,702 | Dispatcher class for posting data into a http target.
Copyright 2013 IBM Corp 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/licens... | 788 | en | 0.877676 |
#created by Angus Clark on 8/01/2017
# toDo incoperate the saving program into this_dir
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '130.56.253.43'
print host # remove when done debugging
port = 5201 # edit when port for comm is decided
s.bind((host,port))
f = open('temp.json','wb')
s... | ServerScript/recievejson(legacy).py | 459 | created by Angus Clark on 8/01/2017 toDo incoperate the saving program into this_dir remove when done debugging edit when port for comm is decided | 146 | en | 0.866454 |
# Generated by Django 2.2.1 on 2019-05-21 10:29
from django.db import migrations, models
import uni_ticket.models
class Migration(migrations.Migration):
dependencies = [
('uni_ticket', '0030_auto_20190520_1532'),
]
operations = [
migrations.AlterField(
model_name='ticketcate... | uni_ticket/migrations/0031_auto_20190521_1229.py | 1,518 | Generated by Django 2.2.1 on 2019-05-21 10:29 | 45 | en | 0.472784 |
from typing import List, Literal, Union, Callable, Tuple
from dataclasses import dataclass, replace
from .config_types import (
TWInterface,
TWSettingStorage, TWSettingBool, TWSetting,
WrapType, Fields, AnkiModel, LabelText, WhichField, Tags, Falsifiable,
)
ScriptKeys = Literal[
'enabled',
'name'... | src/lib/interface.py | 1,477 | name for the type of the interface result is used for storing, list of values that are readonly,, list of values or stored in `storage` field, | 142 | en | 0.734461 |
import pymysql.cursors
import ldap
def get_domain_name():
"""
Returns the domain name of the current configuration from a config file
Returns
-------
string
the domain name
"""
with open("/var/www/logic_webapp/webapp_config") as file:
line = file.readline()
dom... | webapp/external_access.py | 1,895 | Creates an LDAP connection object with a given hostname
Parameters
----------
host : hostname with the LDAP database in the form of (ldap://host)
Returns
-------
LDAP connection object
Creates the connection to the database (MySQL) so it can be queried
Parameters
----------
host : string
hostname on which is loc... | 855 | en | 0.738918 |
"""Form definitions, allow easy validation of input and rendering of forms
"""
# future imports
from __future__ import absolute_import
# local imports
from app.forms.pages.base import PageForm
class AboutPageForm(PageForm):
pass
| src-server/app/forms/pages/about.py | 237 | Form definitions, allow easy validation of input and rendering of forms
future imports local imports | 102 | en | 0.622062 |
from typing import Union, Iterator, Tuple
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Tuple[int, int, int]]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"... | spacy/lang/en/syntax_iterators.py | 1,570 | Detect base noun phrases from a dependency parse. Works on both Doc and Span.
Ensure works on both Doc and Span. Prevent nested chunks from being produced If the head is an NP, and we're coordinated to it, we're an NP | 219 | en | 0.927047 |
"""Permissions for the client app"""
from rest_framework import permissions
class ClientPermissions(permissions.BasePermission):
"""Handles authorization of requests to the client app."""
def has_permission(self, request, view):
if view.action == 'create' \
and request.user.has_perm('c... | client/permissions.py | 652 | Handles authorization of requests to the client app.
Permissions for the client app | 83 | en | 0.853848 |
import os
import discord
import youtube_dl as ytdl
class MusicPlayer:
'''
This module is responsible for connecting and disconnecting the bot from a voice channel, downloading songs from
youtube and add them in the queue . Basic music functions like pause, resume, stop and play, in order to give
... | modules/youtube_music.py | 6,597 | This module is responsible for connecting and disconnecting the bot from a voice channel, downloading songs from
youtube and add them in the queue . Basic music functions like pause, resume, stop and play, in order to give
users a simple music bot based on the new api of discord.
Because the songs will be downloaded, i... | 798 | en | 0.911044 |
from typing import Any, Dict, Iterable, Optional, Tuple
from datastore.shared.util import DeletedModelsBehaviour
from ....models.checker import Checker, CheckException
from ....models.models import Organization
from ....shared.exceptions import ActionException
from ....shared.filters import FilterOperator
from ....sh... | openslides_backend/action/actions/organization/initial_import.py | 3,439 | Action to import an initial-data.json in an empty datastore.
Should be callable from the management service.
Simplified entrypoint to perform the action.
check datavalidation | 176 | en | 0.769299 |
# 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-ecs/aliyunsdkecs/request/v20140526/ModifyLaunchTemplateDefaultVersionRequest.py | 2,732 | 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 |
"""
@brief test log(time=20s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG, run_cmd
from pyquickhelper.pycode import get_temp_folder, fix_tkinter_issues_virtualenv, skipif_appveyor, skipif_travis
from pyquickhelper.pycode import add_missing_development_version
class TestPyDa... | _unittests/ut_talk_examples/test_pydata2016_animation.py | 4,352 | @brief test log(time=20s)
update a distribution based on new data. To get the list of available writers Set up plot parameters This vertical line represents the theoretical value, to which the plotted distribution should converge. This way the plot can continuously run and we just keep watching new realizations ... | 419 | en | 0.901916 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Scaleway IP management module
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: scaleway_ip
short_descriptio... | venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/modules/cloud/scaleway/scaleway_ip.py | 7,148 | !/usr/bin/python -*- coding: utf-8 -*- Scaleway IP management module GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) IP is assigned to a server IP is unassigned to a server IP is migrated between 2 different servers Create IP | 268 | en | 0.81556 |
"""
# Interaction Tracker
# @license http://www.apache.org/licenses/LICENSE-2.0
# Author @ Jamil Hussain, Zaki
"""
from django.conf import settings
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
from django.core.validators import RegexValidator
from django.db import models
from dj... | InteractionTracker/accounts/models.py | 4,685 | Creates and saves a superuser with the given email, date of
birth and password.
Creates and saves a User with the given email, date of
birth and password.
Does the user have permissions to view the app `app_label`?
Does the user have a specific permission?
# Interaction Tracker
# @license http://www.apache.org/licenses... | 689 | en | 0.908022 |
from __future__ import unicode_literals
import os
import inspect
from webob import Request, Response
from parse import parse
from jinja2 import FileSystemLoader, Environment
from requests import session as RequestsSession
from wsgiadapter import WSGIAdapter as RequestWSGIAdapter
class API:
"""
this is just ... | diy/api.py | 4,968 | this is just for examples
to get reponse Hello World in web browser
this is just for examples
to get reponse Hello World in web browser
class for implemented alternative
route using class-based handlers
class based views such as Django
already implemented
based on mozilla documentation
mount it to session object
any re... | 371 | en | 0.868682 |
# 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 ... | azure-mgmt-network/azure/mgmt/network/v2018_10_01/models/connection_monitor_query_result.py | 1,373 | List of connection states snaphots.
:param source_status: Status of connection monitor source. Possible values
include: 'Uknown', 'Active', 'Inactive'
:type source_status: str or
~azure.mgmt.network.v2018_10_01.models.ConnectionMonitorSourceStatus
:param states: Information about connection states.
:type states:
li... | 841 | en | 0.555938 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | python/paddle/fluid/tests/unittests/ipu/op_test_ipu.py | 3,437 | Restore random seeds
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required b... | 702 | en | 0.817034 |
# Copyright 2021 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | unit_tests/events/plugins/test_zaza_events_plugins_conncheck.py | 40,611 | Unit tests for zaza.events.plugins.conncheck.py.
Copyright 2021 Canonical Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by appl... | 766 | en | 0.828614 |
import argparse
import numpy as np
from sklearn.metrics import accuracy_score, jaccard_score, balanced_accuracy_score
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import dataloader
import track
from classifiers import ObservationsConditionsClassifier
from classifiers import ClassifierComp... | train.py | 7,289 | save prediction Transition step Calculate information and sort indices by information | 85 | en | 0.732314 |
#!/usr/bin/env python3
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the pruning code.
WARNING:
This test uses 4GB of disk space.
This test takes 30 mins or more (up ... | test/functional/feature_pruning.py | 21,581 | Test the pruning code.
WARNING:
This test uses 4GB of disk space.
This test takes 30 mins or more (up to 2 hours)
!/usr/bin/env python3 Copyright (c) 2014-2020 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.ph... | 7,196 | en | 0.862031 |
import time
from Classes.Packets.PiranhaMessage import PiranhaMessage
class OwnHomeDataMessage(PiranhaMessage):
def __init__(self, messageData):
super().__init__(messageData)
self.messageVersion = 0
def encode(self, fields, player):
ownedBrawlersCount = len(player.OwnedBrawlers)
... | Classes/Packets/Server/Home/OwnHomeDataMessage.py | 15,158 | Trophies Highest Trophies Experience Thumbnail Namecolor Selected Skins Randomizer Skin Selected Current Random Skin Unlocked Skin Purchase Option New Item State Offer 1 Offer 2 Token Doubler Enabled Token Doubler New Tag State Event Tickets New Tag State Coin Packs New Tag State Change Name Cost Timer For the Next Nam... | 3,237 | en | 0.511895 |
from sympy.logic.boolalg import to_cnf, eliminate_implications, distribute_and_over_or, \
compile_rule, conjuncts, disjuncts, to_int_repr, fuzzy_not, Boolean, is_cnf
from sympy import symbols, And, Or, Xor, Not, Nand, Nor, Implies, Equivalent, ITE
from sympy.utilities.pytest import raises, XFAIL
def test_overloadi... | py3k-sympy/sympy/logic/tests/test_boolalg.py | 8,602 | Test for associativity of And
Test that mixing symbols with boolean values
works as expected
Test for commutivity of And and Or
Test that |, & are overloaded as expected
test methodsarg is not a sequence | 205 | en | 0.970191 |
import argparse
from pathlib import Path
import tempfile
from typing import List
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
from target_extraction.data_types import TargetTextCollection
from target_extraction.tokenizers import spacy_tokenizer
def parse_path(path_st... | tdsa_augmentation/data_creation/shrink_glove_to_targets.py | 3,129 | :param glove_fp: File path to the glove file that is to be shrinked
:param filter_words: List of words to filter/shrink the glove file/vectors
by
:param save_fp:
python tdsa_augmentation/data_creation/shrink_glove_to_targets.py ./data/original_restaurant_sentiment/train.json ./resources/word_embe... | 353 | en | 0.766923 |
import platform
import random
import shutil
import subprocess
import textwrap
from pathlib import Path, PurePath
import pytest
from cibuildwheel.docker_container import DockerContainer
from cibuildwheel.environment import EnvironmentAssignment
# for these tests we use manylinux2014 images, because they're available ... | unit_test/docker_container_test.py | 6,677 | for these tests we use manylinux2014 images, because they're available on multi architectures and include python3.8 max environment variable size is 128kB check the length of d note: the below embedded snippets are in python2 check that we can pass though arbitrary binary data without erroring check that we can capture... | 574 | en | 0.814767 |
import numpy as np
from envs.babyai.oracle.teacher import Teacher
class LandmarkCorrection(Teacher):
def empty_feedback(self):
"""
Return a tensor corresponding to no feedback.
"""
return np.array([-1, -1])
def random_feedback(self):
"""
Return a tensor corresp... | envs/babyai/oracle/landmark_correction.py | 2,221 | Return the expert action from the previous timestep.
Return a tensor corresponding to no feedback.
Returns true when we should give feedback.
Currently returns true when the agent's past action did not match the oracle's action.
Return a tensor corresponding to no feedback.
TODO: Unhardocde this Hardcoded 1 time-step... | 756 | en | 0.880958 |
from inits import *
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
# global unique layer ID dictionary for layer name assignment
_LAYER_UIDS = {}
def get_layer_uid(layer_name=''):
"""Helper function, assigns unique layer IDs."""
if layer_name not in _LAYER_UIDS:
_LAYER_UIDS[layer_n... | layers.py | 8,106 | Dense layer.
Graph convolution layer.
Base layer class. Defines basic API for all layer objects.
Implementation inspired by keras (http://keras.io).
# Properties
name: String, defines the variable scope of the layer.
logging: Boolean, switches Tensorflow histogram logging on/off
# Methods
_call(inputs): D... | 1,128 | en | 0.407244 |
import numpy
import mysql.connector
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn import tree
##--------------------------Catch Data from data base--------------------------------
cnx = mysql.connector.connect(user = [type your user] , password = ... | PredictPrice.py | 2,108 | --------------------------Catch Data from data base-------------------------------- TestData Add newApartments to input of table Encode Neighborhood integer encode binary encode Start training and testing Encode New Apartment | 225 | en | 0.628545 |
# Given a statement, find the parse tree that led to it.
from tree_parser import *
import pickle #pickle.dump(database.proof_datas, open(output_file,'wb'))
from copy import deepcopy
from tree import *
#output_file = 'tree_parse_data'
# class InitialStringSearcher:
# def __init__(self):
# self.nodes = ... | statement_to_tree.py | 10,900 | Given a statement, find the parse tree that led to it.pickle.dump(database.proof_datas, open(output_file,'wb'))output_file = 'tree_parse_data' class InitialStringSearcher: def __init__(self): self.nodes = {} self.return_value = None def add(self,string,value): return self.add() def a... | 2,941 | en | 0.584816 |
"""
const $ = new Env("京东饭粒");
京东饭粒任务
活动入口:https://u.jd.com/ytWx4w0
每天60豆小毛,爱要不要
cron:
46 9 * * * jd_fanli.py
"""
import os
import time
import re
import requests
import random
proxies = {"http": None, "https": None}
def randomstr(num):
randomstr = ""
for i in range(num):
randomstr = randomstr + ra... | jd_fanli.py | 3,715 | const $ = new Env("京东饭粒");
京东饭粒任务
活动入口:https://u.jd.com/ytWx4w0
每天60豆小毛,爱要不要
cron:
46 9 * * * jd_fanli.py
print(r.text) print(r.text) tt=int(time.time()*1000) print(data) | 173 | zh | 0.315014 |
"""
test all other .agg behavior
"""
from collections import OrderedDict
import datetime as dt
from functools import partial
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
PeriodIndex,
Series,
date_range,
period_range,
)
from pandas... | pandas/tests/groupby/aggregate/test_other.py | 18,632 | test all other .agg behavior
GH 6337 http://stackoverflow.com/questions/21706030/pandas-groupby-agg-function-column-dtype-error different api for agg when passed custom function with mixed frame GH 3579 GH 12821 test for `first` function test for `last` function count similar to GH12821 xref 11444 see gh-11199 GH 905... | 730 | en | 0.588589 |
#!/usr/bin/python
# encoding: utf-8
'''
codegen_checker.codegen -- shortdesc
codegen_checker.codegen is a description
It defines classes_and_methods
@author: user_name
@copyright: 2013 organization_name. All rights reserved.
@license: license
@contact: user_email
@deffield updated: U... | tools/codegen/codegen_checker.py | 6,290 | !/usr/bin/python encoding: utf-8 Local imports Prepare a whitespace remover Read the file in a line at a time IGNORE:C0111 Setup argument parser Process arguments Get the directories in canonical form Find all the model files Get the basename Try to find the existing header file in the usual place. Try to find the exis... | 837 | en | 0.763348 |
# asot: Localhost tunneling
# Copyright 2021, Luna and asot contributors
# SPDX-License-Identifier: BSD-3-Clause
from .main import main
if __name__ == "__main__":
main()
| server/asot/manage/__main__.py | 176 | asot: Localhost tunneling Copyright 2021, Luna and asot contributors SPDX-License-Identifier: BSD-3-Clause | 106 | en | 0.425146 |
from datetime import datetime
import numpy as np
import exetera.core.session as sess
from exetera.core import dataframe
ADATA = '/home/jd21/data/processed_May17_processed.hdf5'
VDATA = '/home/jd21/data/vacc.0603.h5'
DSTDATA = '/home/jd21/data/full_merge.h5'
def asmt_merge_vacc():
"""
Merge assessment df wi... | scripts/asmt_merge_vacc_exetera.py | 4,181 | Merge assessment df with vaccine dataframe, filter out subject has a healthy assessments before vaccine date
Merge tests to previous merged (assessments, vaccine), filter out subjects has test records within 10days after vaccine
open related datasetsfilter vaccine typejoin asmt with vaccine using patient_id, write to... | 748 | en | 0.908865 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Public Title.
Doc str for module users
.. moduleauthor:: Max Wu <http://maxwu.me>
.. References::
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
.. Test Samples in doctest format
>>> None
"""
from setupt... | setup.py | 2,987 | Public Title.
Doc str for module users
.. moduleauthor:: Max Wu <http://maxwu.me>
.. References::
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
.. Test Samples in doctest format
>>> None
!/usr/bin/env python -*- coding: utf-8 -*- Get the long descrip... | 1,443 | en | 0.758441 |
from clvm_tools import binutils
from chinilla.types.blockchain_format.program import Program, INFINITE_COST
from chinilla.types.announcement import Announcement
from chinilla.types.blockchain_format.sized_bytes import bytes32
from chinilla.util.condition_tools import parse_sexp_to_conditions
from chinilla.wallet.puzzl... | tests/wallet/test_singleton.py | 5,008 | (SINGLETON_STRUCT INNER_PUZZLE lineage_proof my_amount inner_solution) SINGLETON_STRUCT = (MOD_HASH . (LAUNCHER_ID . LAUNCHER_PUZZLE_HASH)) create a singleton. This should call driver code. create a fake coin id for the `p2_singleton` create a `p2_singleton` puzzle. This should call driver code. | 296 | en | 0.613554 |
from __future__ import annotations
import numpy as np
import tcod
import g
import game.constants
import game.engine
import game.game_map
import game.render_functions
from game.tiles import tile_graphics
def render_map(console: tcod.Console, gamemap: game.game_map.GameMap) -> None:
# The default graphics are of ... | game/rendering.py | 2,735 | The default graphics are of tiles that are visible. Apply effects to create a darkened map of tile graphics. Skip entities that are not in the FOV. Skip entities that are not in the FOV. | 186 | en | 0.919954 |
import os
import platform
from datetime import datetime
# TODO test counter
# def test_count():
# return 0
# f"Count: {test_count()}\n"\
def serve_info():
return f"Stats\n" \
f"UTC: {datetime.utcnow().isoformat()}\n" \
f"\nMachine\n" \
f"Architecture: {platform.machine()}\n" \... | utils/logger.py | 965 | TODO test counter def test_count(): return 0 f"Count: {test_count()}\n"\ | 75 | en | 0.314237 |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/spbnetworkrange_525415b0593fd4072368412490b137fa.py | 16,145 | The SPB Network Range.
The SpbNetworkRange class encapsulates a list of spbNetworkRange resources that are managed by the user.
A list of resources can be retrieved from the server using the SpbNetworkRange.find() method.
The list can be managed by using the SpbNetworkRange.add() and SpbNetworkRange.remove() methods.
R... | 9,732 | en | 0.773691 |
import time, datetime
from app import db
class ServerInfo(db.Model):
__tablename__ = 'servers'
__table_args__ = (db.PrimaryKeyConstraint('ip', 'port', name='_ip_port_pk'),)
ip = db.Column(db.String(128), nullable=False)
port = db.Column(db.Integer, nullable=False)
... | app/modules/serverinfo/models.py | 1,930 | du_unix = time.mktime(self.date_updated.timetuple()) now_unix = time.mktime(datetime.datetime.now().timetuple()) | 112 | en | 0.167643 |
'''
TRIES
Trie support search, insert, and deletion in O(L) time where L is length of the key
why Trie?
* With Trie, we can insert and find strings in O(L) time where L represent the length of a single word. This is obviously faster than BST.
This is also faster than Hashing because of the ways it is im... | CTCI/Data Structures/Trees/tries.py | 1,157 | TRIES
Trie support search, insert, and deletion in O(L) time where L is length of the key
why Trie?
* With Trie, we can insert and find strings in O(L) time where L represent the length of a single word. This is obviously faster than BST.
This is also faster than Hashing because of the ways it is impleme... | 1,015 | en | 0.864697 |
import argparse
import multiprocessing
import random
import shutil
from datetime import datetime
from functools import partial
from pathlib import Path
import chainer
import chainer.functions as F
import chainer.links as L
import cupy
import numpy as np
from chainer import iterators, optimizers, serializers
from chain... | train_cifar.py | 6,582 | Write parameters text | 21 | ml | 0.064151 |
import lvgl as lv
import styles
def lv_arc(screen):
# Create the arc object on lv screen, ie a lv.scr() object
arc = lv.arc(screen)
# Set arc size
arc.set_size(150, 150)
# Set arc background style color blue
arc.add_style(arc.PART.BG, styles.gstyle_bg1)
# Set arc indicator (i.e. line) st... | widgets/lv_arc/lv_arc.py | 1,534 | Create the arc object on lv screen, ie a lv.scr() object Set arc size Set arc background style color blue Set arc indicator (i.e. line) style to color red Setup Angles, from docs: Zero degree is at the middle right (3 o'clock) of the object and the degrees are increasing in a clockwise direction. The angles should be... | 952 | en | 0.620366 |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import calendar
import codecs
import datetime
import io
import os.path
import re
import subprocess
import sys
from pycoinzpub.convention import tx_fee, satoshi_to_mbtc
from pycoinzpub.encoding import hash160
from pycoinzpub.key import Key
fr... | pycoin/cmds/tx.py | 27,963 | !/usr/bin/env python address_re = re.compile(r"[1-9a-kmnp-zA-KMNP-Z]{27-31}") decode look for WIFs if len(keys) == 1 and key.hierarchical_wallet() is None: we have exactly 1 WIF. Let's look for an address potential_addresses = address_re.findall(line) hex transaction id hex transaction data spendable TODO: check ... | 829 | en | 0.825056 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WebPersonal.settings")
application = get_wsgi_application()
#application = DjangoWhiteNoise(application) | WebPersonal/WebPersonal/wsgi.py | 215 | application = DjangoWhiteNoise(application) | 43 | en | 0.747037 |
from bottle import route, Route, request, default_app, view, HTTPError, response
from redis import StrictRedis
from redis.utils import pipeline
import json
import uwsgi
import os
import logging
import requests
from config import get_config
from worker import get_cache_key, get_wait_key, get_queue_key
from worker im... | web/app.py | 3,898 | Init the application and add routes
pos == 1 implies this url is next up pos <= 0 implies this url was removed from queue and is being processed | 147 | en | 0.982162 |
"""
Some common functions for interfacing with the
NodeMeister REST API.
"""
import requests
import anyjson
import re
import logging
MISSING_ITEM = '-'
DIFF_MARKER = ">"
try:
logger.debug("importing nodemeisterlib")
except NameError:
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] %(mes... | contrib/cli_scripts/nodemeisterlib.py | 32,476 | add a class to a group in NodeMeister
:param nm_host: NodeMeister hostname or IP
:type nm_host: string
:param gid: numeric ID of the group to add param to
:type gid: int
:param classname: class name
:type classname: string
:param classparams: class parameters, default None
:type classparams: string or None
:param dry_... | 12,455 | en | 0.56303 |
from __future__ import absolute_import
from datetime import datetime
from django.utils import timezone
from sentry.api.serializers import Serializer, register
from sentry.models import Event, EventError
@register(Event)
class EventSerializer(Serializer):
_reserved_keys = frozenset(['sentry.interfaces.User', 'sd... | src/sentry/api/serializers/models/event.py | 4,733 | XXX(dcramer): These are called entries for future-proofing we treat user as a special contextual item data might not be returned for e.g. a public HTTP repr Sentry at one point attempted to record invalid types here. Remove after June 2 2016 TODO(dcramer): move release serialization here See GH-3248 | 300 | en | 0.887235 |
import os
import sys
from envyaml import EnvYAML
# Adding the repository root to the sys path so exports work properly
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..", "..")))
from examples.common.processes import GUIProcess, ImageCapture, YoloImageProcessor # noqa: E402
from rembrain_robot_framew... | examples/local/main.py | 973 | Adding the repository root to the sys path so exports work properly noqa: E402 noqa: E402 | 89 | en | 0.496783 |
# Purpose: API utilities
#
# Notes: API credentials must be enabled on Veracode account and placed in ~/.veracode/credentials like
#
# [default]
# veracode_api_key_id = <YOUR_API_KEY_ID>
# veracode_api_key_secret = <YOUR_API_KEY_SECRET>
#
# and file permission set appropriate... | veracode_api_py/api.py | 19,318 | Purpose: API utilities Notes: API credentials must be enabled on Veracode account and placed in ~/.veracode/credentials like [default] veracode_api_key_id = <YOUR_API_KEY_ID> veracode_api_key_secret = <YOUR_API_KEY_SECRET> and file permission set appropriately (chmod 600)xml ... | 525 | en | 0.553879 |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2021 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... | testscripts/RDKB/component/WAN_MANAGER/TS_WANMANAGER_DSLWANoE_FixedMode_ActLink_P_1-1_WAN_Pri-Sec.py | 16,882 | If not stated otherwise in this file or this component's Licenses.txt file the following copyright and licenses apply: Copyright 2021 RDK Management 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... | 1,606 | en | 0.80357 |
from django.shortcuts import render,redirect
from .models import Image,Location,Category
# Create your views here.
def intro(request):
images = Image.objects.all()
return render(request, 'intro.html',{'images':images})
def search_results(request):
if 'image' in request.GET and request.GET["image"]:
... | snaps/views.py | 545 | Create your views here. | 23 | en | 0.928092 |
"""Assorted utilities shared between parts of apitools."""
import collections
import httplib
import os
import types
import urllib2
from apitools.base.py import exceptions
__all__ = [
'DetectGae',
'DetectGce',
]
def DetectGae():
"""Determine whether or not we're running on GAE.
This is based on:
ht... | .install/.backup/lib/apitools/base/py/util.py | 1,707 | Determine whether or not we're running on GAE.
This is based on:
https://developers.google.com/appengine/docs/python/#The_Environment
Returns:
True iff we're running on GAE.
Determine whether or not we're running on GCE.
This is based on:
https://developers.google.com/compute/docs/instances#dmi
Returns:
Tru... | 453 | en | 0.852391 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
r"""
Batch acquisition functions using the reparameterization trick in combination
with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and
[Wilson2017reparam]_
.. [Rezende2014reparam]
D. J. Rezende, S. Mohamed,... | botorch/acquisition/monte_carlo.py | 16,071 | Abstract base class for Monte-Carlo based batch acquisition functions.
MC-based batch Expected Improvement.
This computes qEI by
(1) sampling the joint posterior over q points
(2) evaluating the improvement over the current best for each sample
(3) maximizing over q
(4) averaging over the samples
`qEI(X) = E(max(max ... | 8,878 | en | 0.754776 |
from .fhirbase import fhirbase
class Annotation(fhirbase):
"""
A text note which also contains information about who made the
statement and when.
Args:
authorReference: The individual responsible for making the annotation.
authorString: The individual responsible for making the anno... | cardea/fhir/Annotation.py | 1,134 | A text note which also contains information about who made the
statement and when.
Args:
authorReference: The individual responsible for making the annotation.
authorString: The individual responsible for making the annotation.
time: Indicates when this particular annotation was made.
text: The text ... | 440 | en | 0.859821 |
import abc
import json
import logging
import os
from typing import Any, Tuple, Union
import numpy as np
import tifffile
import tiledb
import zarr
from slaid.commons import Mask, BasicSlide
from slaid.commons.base import Polygon
from slaid.commons.ecvl import BasicSlide as EcvlSlide
logger = logging.getLogger(__file_... | slaid/renderers.py | 4,462 | from https://github.com/hmallen/numpyencoder | 44 | en | 0.682819 |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | tools/infer/utility.py | 16,245 | Visualize the results of OCR detection and recognition
args:
image(Image|array): RGB image
boxes(list): boxes with shape(N, 4, 2)
txts(list): the texts
scores(list): txxs corresponding scores
drop_score(float): only scores greater than drop_threshold will be visualized
font_path: the path of fon... | 1,854 | en | 0.73026 |
from django.db import models
import string, random, datetime
from profiles.models import UserProfile, Location, Surcharges, User
from decimal import *
from menu.models import Product, Entree, Pizza, PizzaTopping, Side
from localflavor.us.models import PhoneNumberField, USStateField, USZipCodeField
#modify this to che... | src/orders/models.py | 5,189 | modify this to check against prior conf orders.delivery charge needs to be separate from lines | 94 | en | 0.905803 |
import json
import os
from golem.core import utils
from golem.test_runner import test_runner
from golem.report.execution_report import create_execution_directory
from golem.report.execution_report import create_execution_dir_single_test
from golem.report import test_report
from golem.report.test_report import get_tes... | tests/report/test_report_test.py | 6,386 | inexistent test set inexistent test | 35 | fr | 0.191815 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
class Stage5(torch.nn.Module):
def __init__(self):
super(Stage5, self).__init__()
self.layer1 = torch.nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
self._initialize_weights()
... | runtime/image_classification/models/vgg16/gpus=16_straight/stage5.py | 1,049 | Copyright (c) Microsoft Corporation. Licensed under the MIT license. | 68 | en | 0.51155 |
import twl
wolf = twl.Wolf()
def split(wolf, end=7):
return [wolf.len(n)() for n in range(2, end+1)]
def spell(ltrs, wild=0):
return split(wolf.wild(ltrs, wild), len(ltrs)+wild)
def _munge(func, fix, ltrs, wild=0):
return split(func(fix).wild(fix+ltrs, wild), len(fix+ltrs)+wild)
def starts(fix, ltr... | use.py | 669 | print(wolf.len(2).words) print(wolf.wild('aa')()) | 49 | fr | 0.114239 |
"""Notification."""
from models.metric_notification_data import MetricNotificationData
class Notification:
"""Handle notification contents and status."""
def __init__(self, report, metrics, destination_uuid, destination):
"""Initialise the Notification with the required info."""
self.report_... | components/notifier/src/models/notification.py | 996 | Handle notification contents and status.
Check if the notification itself is the same, regardless of its metric content.
Initialise the Notification with the required info.
Merge new metrics into this notification.
Notification. | 228 | en | 0.81605 |
import RPi.GPIO as GPIO
import hx711
import matplotlib.pyplot as plt
# Read initial calibration and tare weight data then display the plot.
def main():
GPIO.setmode(GPIO.BCM)
hx = hx711.HX711(dout_pin=5, pd_sck_pin=6)
zero_the_scale(hx)
calibrate_scale(hx)
(tare_weight, total_weight) = get_tare_an... | pie_pie_chart.py | 3,046 | Read initial calibration and tare weight data then display the plot. Set scale position to zero. The scale should be empty when this is run. Calibrate the scale with prompts to the user. Prompt user and get readings for the tare weight and full pie. Continually read data from the sensor, update the pie chart, and displ... | 372 | en | 0.778552 |
import math
from enforce_typing import enforce_types
from engine import SimStrategyBase
from util.constants import S_PER_HOUR
@enforce_types
class SimStrategy(SimStrategyBase.SimStrategyBase):
def __init__(self, no_researchers=2):
#===initialize self.time_step, max_ticks====
super().__init__()
... | assets/netlists/opsci_profit_sharing/SimStrategy.py | 1,815 | ===initialize self.time_step, max_ticks=======set base-class values we want for this netlist====typical runs: 10 years, 20 years, 150 years===new attributes specific to this netlist=== OCEAN 40% of grant funding will go towards "doing work" & publishing meaning that TICKS_BETWEEN_PROPOSALS should be used this would be ... | 639 | en | 0.717006 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... | sdk/python/pulumi_azure_nextgen/network/get_express_route_gateway.py | 6,839 | ExpressRoute gateway resource.
Configuration for auto scaling.
A unique read-only string that changes whenever the resource is updated.
List of ExpressRoute connections to the ExpressRoute gateway.
ExpressRoute gateway resource.
API Version: 2020-08-01.
:param str express_route_gateway_name: The name of the ExpressRo... | 806 | en | 0.801792 |
"""
Support for Xiaomi Gateways.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/xiaomi_aqara/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.discovery import SERVICE_XIAOMI_GW
from homeassista... | homeassistant/components/xiaomi_aqara.py | 10,991 | Representation a base Xiaomi device.
Initialize the Xiaomi device.
Extend a voluptuous schema with a gateway validator.
Set state to UNAVAILABLE.
Update some configuration defaults.
Service to add a new sub-device within the next 30 seconds.
Return True if entity is available.
Return the state attributes.
Convert sid t... | 1,151 | en | 0.861725 |
# coding: utf-8
#
# Copyright 2020 The Oppia 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 requi... | scripts/linters/test_files/invalid_python_three.py | 1,156 | This is a fake docstring for valid syntax purposes.
This doesn't do anything.
Args:
name: str. Means nothing.
Yields:
tuple(str, str). The argument passed in but twice in a tuple.
Python file with invalid syntax, used by scripts/linters/
python_linter_test.py. This file doesnot import from __future__.
codin... | 906 | en | 0.863752 |
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as ip
from scipy.ndimage import gaussian_filter1d
from utils.helpers import find_index, peakdet, replace_nan
from params import fall_params
def calc_fall_flush_timings_durations(flow_matrix, summer_timings):
max_zero_allowed_per_year = fal... | utils/calc_fall_flush.py | 12,683 | Left side sharp
Smaller filter to find fall flush peak Larger filter to find wet season peak smaller is more peak Maximum duration from start to end, for fall flush peak Return to wet season flow must be certain percentage of that year's max flow Size of flush peak, from rising limb to top of peak, has great enough c... | 1,250 | en | 0.790456 |
"""projeto URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | projeto/urls.py | 843 | projeto URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | 633 | en | 0.677606 |
# -*- coding: utf-8 -*-
import logging
from ocp_resources.constants import PROTOCOL_ERROR_EXCEPTION_DICT
from ocp_resources.resource import TIMEOUT, Resource
from ocp_resources.utils import TimeoutSampler
LOGGER = logging.getLogger(__name__)
class CDIConfig(Resource):
"""
CDIConfig object.
"""
ap... | ocp_resources/cdi_config.py | 1,622 | CDIConfig object.
Wait until upload proxy url is changed
Args:
timeout (int): Time to wait for CDI Config.
Returns:
bool: True if url is equal to uploadProxyURL.
-*- coding: utf-8 -*- | 195 | en | 0.801278 |
"""Database schemas, examples, and tools"""
import copy
from warnings import warn
from cerberus import Validator
from .sorters import POSITION_LEVELS
SORTED_POSITION = sorted(POSITION_LEVELS.keys(), key=POSITION_LEVELS.get)
ACTIVITIES_TYPE = ["teaching", "research"]
AGENCIES = ["nsf", "doe"]
APPOINTMENTS_TYPE = ["g... | regolith/schemas.py | 165,807 | Don't validate descriptions
The rule's arguments are validated against this schema:
{'type': 'string'}
Test if value is in list
The rule's arguments are validated against this schema:
{'type': 'list'}
Validate a record for a given db
Parameters
----------
coll : str
The name of the db in question
record : dict
... | 1,016 | en | 0.777122 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from handlers.Home_Core import Home_Core
class ITM_Core(Home_Core):
def __init__(self, request, response, itm_db):
super(ITM_Core, self).__init__(request, response)
self.itmDB = itm_db
self.db = itm_db.db
| server_src/modules/handlers/ITM_Core.py | 260 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
from typing import Dict, List, TypeVar, Generic
import warnings
import torch
import numpy
from allennlp.common import Registrable
from allennlp.data.tokenizers.token import Token
from allennlp.data.vocabulary import Vocabulary
TokenType = TypeVar("TokenType", int, List[int], numpy.ndarray)
class TokenIndexer(Gener... | allennlp/data/token_indexers/token_indexer.py | 6,591 | A ``TokenIndexer`` determines how string tokens get represented as arrays of indices in a model.
This class both converts strings into numerical values, with the help of a
:class:`~allennlp.data.vocabulary.Vocabulary`, and it produces actual arrays.
Tokens can be represented as single IDs (e.g., the word "cat" gets re... | 3,491 | en | 0.784837 |
from __future__ import print_function
import os
import datetime
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import Query, scoped... | examples/smartquery.py | 12,355 | setup we also use ReprMixin which is optional to smart query relationship, it should be explicitly set, not to be a backref below relationship will just return query (without executing) this query can be customized see http://docs.sqlalchemy.org/en/latest/orm/collections.htmldynamic-relationship we will use this relat... | 4,165 | en | 0.83528 |
#! /usr/bin/env python
import rospy
from std_msgs.msg import Int32
def cb(message):
rospy.loginfo(message.data*2)
print (rospy.loginfo)
if message.data%2 == 0:
print ('0')
elif message.data%2 != 0 :
print('1')
if __name__ == '__main__':
rospy.init_node('twice')
sub = rospy... | mypkg/scripts/twice.py | 372 | ! /usr/bin/env python | 21 | fr | 0.299742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.