content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
import json
from typing import List, Dict
from icecream import ic
from compiler_idioms.idiom.instruction_sequence import InstructionSequence
from compiler_idioms.idiom.utils.magic import compute_magic_numbers_if_not_exists
from compiler_idioms.instruction import from_anonymized_pattern, Instruction
from compiler_idio... | compiler_idioms/idiom/implementations/remainder_signed_todo.py | 2,676 | TEST_PATTERN_PATH = TEST_DIR / "mods-pointer.json" with TEST_PATTERN_PATH.open('r') as f: seq = json.load(f) print(seq) sequences = [from_anonymized_pattern(seq['pattern'])] | 177 | en | 0.519745 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2015, IBM Corp.
# All rights reserved.
#
# Distributed under the terms of the BSD Simplified License.
#
# The full license is in the LICENSE file, distributed with this software.
... | ibmdbpy/tests/test_frame.py | 14,822 | Test module for IdaDataFrameObjects
!/usr/bin/env python -*- coding: utf-8 -*------------------------------------------------------------------------------ Copyright (c) 2015, IBM Corp. All rights reserved. Distributed under the terms of the BSD Simplified License. The full license is in the LICENSE file, distributed ... | 930 | en | 0.788551 |
#!/usr/bin/env python
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import datetime
import json
import logging
import os
import re
import StringIO
import sys
import tempfile
import threading
i... | tools/swarming_client/tests/swarming_test.py | 59,694 | !/usr/bin/env python Copyright 2013 The LUCI Authors. All rights reserved. Use of this source code is governed under the Apache License, Version 2.0 that can be found in the LICENSE file. net_utils adjusts sys.path. As seen in services/swarming/handlers_api.py. Silence pylint 'Access to a protected member _Event of a c... | 1,412 | en | 0.819362 |
#!/usr/bin/env python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
"""
Script to generate gperf tables of kernel object metadata
User mode threads making system calls reference kernel objects by memory
address, as the kernel/driver APIs in Zephyr are the same for both user
and supe... | scripts/gen_kobject_list.py | 32,054 | Script to generate gperf tables of kernel object metadata
User mode threads making system calls reference kernel objects by memory
address, as the kernel/driver APIs in Zephyr are the same for both user
and supervisor contexts. It is necessary for the kernel to be able to
validate accesses to kernel objects to make th... | 6,177 | en | 0.893746 |
# Copyright 2019 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... | models/official/unet3d/unet_main.py | 4,994 | Runs Mask RCNN model on distribution strategy defined by the user.
Training script for UNet-3D.
Copyright 2019 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 Lice... | 766 | en | 0.836053 |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import numpy... | models/transformer.py | 105,956 | Transformer decoder consisting of *args.decoder_layers* layers. Each layer
is a :class:`TransformerDecoderLayer`.
Args:
args (argparse.Namespace): parsed command-line arguments
dictionary (~fairseq.data.Dictionary): decoding dictionary
embed_tokens (torch.nn.Embedding): output embedding
no_encoder_attn... | 14,504 | en | 0.640538 |
# Copyright 2017 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 ag... | saliency/guided_backprop.py | 2,982 | A SaliencyMask class that computes saliency masks with GuidedBackProp.
This implementation copies the TensorFlow graph to a new graph with the ReLU
gradient overwritten as in the paper:
https://arxiv.org/abs/1412.6806
Thanks to Chris Olah for generously sharing his implementation of the ReLU
backprop.
Returns a Guide... | 1,155 | en | 0.846006 |
import jax.numpy as jnp
import jax.random as random
import numpyro
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS
from typing import Any, Dict, Optional
class PlayerModel(object):
"""
numpyro implementation of the AIrsenal player model.
"""
def __init__(self):
self... | airsenal/framework/player_model.py | 3,356 | numpyro implementation of the AIrsenal player model.
one sample from the prior per player now it's all about how to broadcast in the right dimensions..... | 156 | en | 0.927601 |
# -*- coding: utf-8 -*-
""" OneLogin_Saml2_Settings class
Copyright (c) 2010-2018 OneLogin, Inc.
MIT License
Setting class of OneLogin's Python Toolkit.
"""
from time import time
import re
from os.path import dirname, exists, join, sep
from app.utils.onelogin.saml2 import compat
from app.utils.onelogin.saml2.const... | app/utils/onelogin/saml2/settings.py | 28,985 | Handles the settings of the Python toolkits.
Add default values if the settings info is not complete
Initializes the settings:
- Sets the paths of the different folders
- Loads settings info from settings file or array/object provided
:param settings: SAML Toolkit Settings
:type settings: dict
:param custom_base_path... | 4,201 | en | 0.57819 |
from emonitor.utils import Module
from emonitor.extensions import babel
from .content_frontend import getFrontendContent, getFrontendData
class LocationsModule(Module):
info = dict(area=['frontend'], name='locations', path='locations', icon='fa-code-fork', version='0.1')
def __repr__(self):
return "l... | emonitor/modules/locations/__init__.py | 816 | add template path translations | 30 | en | 0.109087 |
import functools
import os
import random
import matplotlib.pyplot as plt
import networkx as nx
def make_graph(path):
G = nx.DiGraph()
with open(path, 'r') as f:
lines = f.readlines()
# random.seed(0)
sample_nums = int(len(lines) * 0.00006)
lines = random.sample(lines, sample_... | homework_3/main.py | 8,559 | random.seed(0) 节点的度中心性 节点的接近中心性 节点的核数 节点的pagerank值 节点的hub值和authority值 节点的介数中心性 | 78 | zh | 0.944627 |
from nlu import *
from nlu.pipe_components import SparkNLUComponent
from sparknlp.annotator import *
class Lemmatizer(SparkNLUComponent):
def __init__(self,component_name='lemma', language='en', component_type='lemmatizer', get_default=False,model = None, sparknlp_reference=''):
component_name = 'lemmatiz... | nlu/components/lemmatizer.py | 808 | component_name = utils.lower_case(component_name) TODO | 54 | en | 0.146894 |
#!/usr/bin/env python
"""
Solution to Project Euler Problem
http://projecteuler.net/
by Apalala <apalala@gmail.com>
(cc) Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once. For example, 2143 is ... | projecteuler/euler041_pandigital_prime.py | 1,030 | Solution to Project Euler Problem
http://projecteuler.net/
by Apalala <apalala@gmail.com>
(cc) Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital
and i... | 414 | en | 0.678706 |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Zyxel.ZyNOS.get_inventory
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ------------------------------------------------------... | sa/profiles/Zyxel/ZyNOS/get_inventory.py | 5,303 | -*- coding: utf-8 -*- --------------------------------------------------------------------- Zyxel.ZyNOS.get_inventory --------------------------------------------------------------------- Copyright (C) 2007-2019 The NOC Project See LICENSE for details --------------------------------------------------------------------... | 348 | en | 0.202854 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by ExopyHqcLegacy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ------... | tests/tasks/tasks/instr/test_apply_mag_field_task.py | 3,891 | Test ApplyMagFieldView widget outisde of a LoopTask.
Test ApplyMagFieldView widget inside of a LoopTask.
Simply test that everything is ok if field can be evaluated.
Check handling a wrong field.
Simple test when everything is right.
Tests for the ApplyMagFieldTask
-*- coding... | 783 | en | 0.689893 |
#!/usr/bin/env python
# $Id$
#
# Author: Thilee Subramaniam
#
# Copyright 2012 Quantcast Corp.
#
# 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
... | benchmarks/mstress/mstress_plan.py | 6,319 | !/usr/bin/env python $Id$ Author: Thilee Subramaniam Copyright 2012 Quantcast Corp. 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... | 787 | en | 0.806624 |
"""
Support for Syslog-based networking devices.
For now, support is limited to hostapd and dnsmasq.
Example syslog lines:
<30>Dec 31 13:03:21 router hostapd: wlan1: STA a4:77:33:e3:17:7c WPA: group key handshake completed (RSN)
<29>Dec 31 13:05:15 router hostapd: wlan0: AP-STA-CONNECTED 64:20:0c:37:52:82
... | syslog.py | 6,702 | Based on RFC 3164 + RFC 5424 and real-world logs
Parses lines created by hostapd and dnsmasq DHCP
Support for Syslog-based networking devices.
For now, support is limited to hostapd and dnsmasq.
Example syslog lines:
<30>Dec 31 13:03:21 router hostapd: wlan1: STA a4:77:33:e3:17:7c WPA: group key handshake complet... | 1,428 | en | 0.665849 |
import xlrd
import os
import sys
import copy
import json
import codecs
from collections import OrderedDict
# Constant Values
PARENT_NAME_ROW = 0
PARENT_NAME_COL = 0
COLUMN_NAMES_ROW = 1
DATA_STARTING_ROW = 2
ROOT_NAME = '*root'
ID_COLUMN_NAME = 'id'
PARENT_COLUMN_NAME = '*parent'
IGNORE_WILDCARD = '_'
REQUIRE_VERSION ... | third-party/language/generator.py | 7,024 | Constant Values Class xlrd is giving number as float xlrd is giving boolean as integeradd metadata row count Script | 115 | en | 0.878621 |
import torch.nn as nn
import torch.nn.functional as F
import torch
from mmcv.cnn import ConvModule
from mmcv.runner import force_fp32
from mmdet.models.builder import HEADS, build_loss
from mmdet.models.losses import accuracy
from .bbox_head import BBoxHead
from mmdet.core import multi_apply, multiclass_nms
from mmd... | mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py | 29,968 | More general bbox head, with shared conv and fc layers and two optional
separated branches.
.. code-block:: none
/-> cls convs -> cls fcs -> cls
shared convs -> shared fcs
\-> reg convs -> reg fcs -> reg
... | 4,838 | en | 0.79401 |
#! /usr/bin/env python3
""" example module: extra.good.best.tau """
def FunT():
return "Tau"
if __name__ == "__main__":
print("I prefer to be a module") | Curso de Cisco/Actividades/py/packages/extra/good/best/tau.py | 157 | example module: extra.good.best.tau
! /usr/bin/env python3 | 60 | fr | 0.143213 |
#!/usr/bin/env python3
import os
import requests
os.system("clear")
print("""
██ ██ █████ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ █ ██ ███████ ██ ██ ██ ██ ███
██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██
███ ███ ██ ██ ███████ ███████... | wallux.py | 3,930 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
from decisionengine.framework.modules.Publisher import Publisher
def test_publisher_structure():
"""
The module.publisher itself is a bit of a skeleton...
"""
params = {"1": 1, "2": 2, "channel_name": "t... | src/decisionengine/framework/modules/tests/test_Publisher.py | 702 | The module.publisher itself is a bit of a skeleton...
SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC SPDX-License-Identifier: Apache-2.0 | 149 | en | 0.461543 |
# Copyright 2019 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... | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | 7,451 | Return dataset online-generating data.
Creates dataset from (tf)records files for training/evaluation.
Creates NCF training/evaluation dataset.
Args:
params: Dictionary containing parameters for train/evaluation data.
producer: Instance of BaseDataConstructor that generates data online. Must
not be None when p... | 2,715 | en | 0.775864 |
# coding=utf-8
"""
A utility module for working with playbooks in the `origin-ci-tool` repository.
"""
from __future__ import absolute_import, division, print_function
from os.path import abspath, dirname, exists, join
from click import ClickException
def playbook_path(playbook_name):
"""
Get the path to th... | oct/util/playbook.py | 1,068 | Get the path to the named playbook. To allow for
as much brevity as possible in the given playbook
name, we will attempt to search under:
- oct/playbooks
- openshift-ansible/playbooks
:param playbook_name: the name of the playbook
:type playbook_name: str
:return: the path to the playbook
:rtype: str
:raises Cli... | 453 | en | 0.888934 |
# pylint: disable=redefined-outer-name
import pytest
from dagster.core.code_pointer import ModuleCodePointer
from dagster.core.definitions.reconstructable import ReconstructableRepository
from dagster.core.host_representation.grpc_server_registry import ProcessGrpcServerRegistry
from dagster.core.host_representation.h... | python_modules/dagster/dagster_tests/daemon_tests/test_queued_run_coordinator_daemon.py | 10,620 | verifies that only one repository location is created when two queued runs from the same
location are dequeued in the same iteration
pylint: disable=redefined-outer-name pylint: disable=unused-argument fill run store with ongoing runs get a selection of all in progress statuses add more queued runs than should be lau... | 325 | en | 0.862584 |
# -*- coding: utf-8 -*-
import tensorflow as tf
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import argparse
from aquaman_net import AquamanNet
from utils import IMAGE_SIZE
EPOCHS = 1000
BATCH_SIZE = 4
def preproc(image_bytes):
image_jpg = tf.image.d... | ml/train_net.py | 7,246 | -*- coding: utf-8 -*- Loss, training and eval operations are not needed during inference. IT IS VERY IMPORTANT TO RETRIEVE THE REGULARIZATION LOSSES This summary is automatically caught by the Estimator APIoptimizer = tf.train.GradientDescentOptimizer(learning_rate) You DO must get this collection in order to perform u... | 430 | en | 0.850411 |
#!/usr/bin/env python
"""
Test Service
"""
from ..debugging import bacpypes_debugging, ModuleLogger
# some debugging
_debug = 0
_log = ModuleLogger(globals())
def some_function(*args):
if _debug: some_function._debug("f %r", args)
return args[0] + 1
bacpypes_debugging(some_function) | py25/bacpypes/service/test.py | 297 | Test Service
!/usr/bin/env python some debugging | 49 | en | 0.485963 |
# Copyright 2021 The Couler Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | couler/core/step_update_utils.py | 8,628 | A task in DAG of Argo YAML contains name, related template and parameters.
Here we insert a single task into the global tasks.
A step in Argo YAML contains name, related template and parameters.
Here we insert a single step into the global steps.
Copyright 2021 The Couler Authors. All rights reserved. Licensed under ... | 954 | en | 0.808777 |
""" Pymode utils. """
import os.path
import sys
import threading
import warnings
from contextlib import contextmanager
import vim # noqa
from ._compat import StringIO, PY2
DEBUG = int(vim.eval('g:pymode_debug'))
warnings.filterwarnings('ignore')
@contextmanager
def silence_stderr():
""" Redirect stderr. """
... | bundle/python-mode/pymode/utils.py | 840 | Function description.
Redirect stderr.
Pymode utils.
noqa | 62 | en | 0.2436 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import glob
import os.path
import sys
DIR = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(DIR))
SRC_DIR = os.path.join(REPO, "src")
def check_header_files(component):
component_dir = os.path... | planner/FAST-DOWNWARD/misc/style/check-include-guard-convention.py | 1,391 | ! /usr/bin/env python -*- coding: utf-8 -*- | 43 | en | 0.437079 |
# Copyright (C) 2017-2019 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# 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 th... | vizier/api/client/cli/command.py | 2,899 | Abstract class for interpreter commands.
If the given tokens sequence matches the given command execute it
and return True. Otherwise, return False.
Parameters
----------
tokens: list(string)
List of tokens in the command line
Returns
-------
bool
Print a simple help statement for the command.
Output the given ro... | 1,590 | en | 0.698755 |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.water_heaters_and_thermal_storage import WaterHeaterMixed
log = logging.getLogger(__name__)
class TestWaterHeaterMixed(unittest.TestCase):
def setUp(self):
self.fd,... | tests/test_waterheatermixed.py | 12,246 | alpha real object-list real real alpha real real real real alpha real object-list real alpha real real alpha real alpha object-list object-list node real real real real real object-list object-list node node real node node real real real real alpha object-list | 260 | en | 0.628405 |
# coding=UTF-8
import os
import re
import sys
class BaseStringScript:
# State
STATE_SEARCHING='STATE_SEARCHING'
STATE_IN_STR='STATE_IN_STR'
STATE_IN_PLUR='STATE_IN_PLUR'
# Tag types
TYPE_STR='TYPE_STR'
TYPE_PLUR='TYPE_PLUR'
# String tag start/end
START_STR = '<string'
END_STR = '</string'
# ... | scripts/translations/base_string_script.py | 2,423 | Process and write a file of string resources.
:param file_name: path to the file to process.
:return: None.
Process a single string tag.
:param line: an array of lines making a single string tag.
:param type: the tag type, such as TYPE_STR or TYPE_PLUR
:return: an array of lines representing the processed tag.
Overwr... | 700 | en | 0.760265 |
"""Certbot client."""
# version number like 1.2.3a0, must have at least 2 parts, like 1.2
__version__ = '1.14.0.dev0'
| certbot/certbot/__init__.py | 118 | Certbot client.
version number like 1.2.3a0, must have at least 2 parts, like 1.2 | 83 | en | 0.908786 |
"""Config flow to configure the Netgear integration."""
from __future__ import annotations
import logging
from typing import cast
from urllib.parse import urlparse
from pynetgear import DEFAULT_HOST, DEFAULT_PORT, DEFAULT_USER
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.compo... | homeassistant/components/netgear/config_flow.py | 6,913 | Handle a config flow.
Options for the component.
Init object.
Initialize the netgear config flow.
Get the options flow.
Config flow to configure the Netgear integration.
Open connection and check authentication Check if already configured | 240 | en | 0.649914 |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... | tests/riscv/vector/vector_simple_add_force.py | 5,044 | Copyright (C) [2020] Futurewei Technologies, Inc. FORCE-RISCV is 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 THIS SOFTWARE IS PROVIDED ON AN "AS IS"... | 1,593 | en | 0.780195 |
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget
class JogWidget(QWidget):
def __init__(self, parent, callback):
super(JogWidget, self).__init__(parent)
self.parent = parent
self.callback = callback
self.wx_current = 0
self.wy_current = 0
... | classes/jogwidget.py | 1,623 | Safe Feed
self.callback("F111")print("G1 X{:0.2f} Y{:0.2f} F400".format(x_goto, y_goto)) | 89 | en | 0.351914 |
from collections import namedtuple
import logging
import random
from Items import ItemFactory
#This file sets the item pools for various modes. Timed modes and triforce hunt are enforced first, and then extra items are specified per mode to fill in the remaining space.
#Some basic items that various modes requ... | ItemList.py | 8,572 | This file sets the item pools for various modes. Timed modes and triforce hunt are enforced first, and then extra items are specified per mode to fill in the remaining space.Some basic items that various modes require are placed here, including pendants and crystals. Medallion requirements for the two relevant entrance... | 611 | en | 0.874537 |
# Generated by Django 3.1 on 2020-08-08 11:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('socialpages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='tags',
fields=[
('id', m... | socialpages/migrations/0002_auto_20200808_1457.py | 628 | Generated by Django 3.1 on 2020-08-08 11:57 | 43 | en | 0.754867 |
from pathlib import Path
from datetime import datetime
import fire
import torch
import torch.nn as nn
import torch.optim as optim
import ignite
import ignite.distributed as idist
from ignite.engine import Events, Engine, create_supervised_evaluator
from ignite.metrics import Accuracy, Loss
from ignite.handlers impor... | examples/contrib/cifar10/main.py | 12,783 | Main entry to train an model on CIFAR10 dataset.
Args:
seed (int): random state seed to set. Default, 543.
data_path (str): input dataset path. Default, "/tmp/cifar10".
output_path (str): output path. Default, "/tmp/output-cifar10".
model (str): model name (from torchvision) to setup model to train. De... | 3,187 | en | 0.675313 |
"""
Required device info for the PIC16F1768 devices
"""
from pymcuprog.deviceinfo.eraseflags import ChiperaseEffect
DEVICE_INFO = {
'name': 'pic16f1768',
'architecture': 'PIC16',
# Will erase Flash, User ID and Config words
'default_bulk_erase_address_word': 0x8000,
# Flash
'flash_address_word... | pymcuprog/deviceinfo/devices/pic16f1768.py | 1,208 | Required device info for the PIC16F1768 devices
Will erase Flash, User ID and Config words Flash 4KW User ID Config words | 123 | en | 0.67818 |
__copyright__ = """
Copyright (C) 2020 University of Illinois Board of Trustees
"""
__license__ = """
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 limitat... | test/test_init.py | 7,993 | Simple test to check that Lump initializer
creates the expected solution field.
Test of Gaussian pulse generator.
If it looks, walks, and quacks like a duck, then ...
Simple test to check that Shock1D initializer
creates the expected solution field.
Simple test to check that Uniform initializer
creates the expected sol... | 595 | en | 0.762692 |
import pickle
import fcntl
import os
import struct
from collections import defaultdict
from functools import partial
from asyncio import new_event_loop
from io import BytesIO
from .utils import opposite_dict
MESSAGE_LENGTH_FMT = 'I'
def set_nonblocking(fd):
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
... | madbg/communication.py | 3,095 | remove all writers that im the last to write to, remove all that write to me, if nothing left stop loop TODO: is this needed? for dest_fd, buffer in self.buffers.items(): while buffer: buffer = buffer[os.write(dest_fd, buffer):] | 240 | en | 0.638626 |
"""
Host management app
"""
from django.urls import path
from .views import *
app_name = 'sys_inspect'
urlpatterns = [
# 设备列表
path('device/list', InspectDevInfoViews.as_view(), name='inspect_devices_list'),
# 添加设备
path('device/add', AddDevView.as_view(), name='inspect_devices_add'),
# 删除设备
... | apps/sys_inspect/urls.py | 830 | Host management app
设备列表 添加设备 删除设备 编辑设备 任务列表 添加任务 删除任务 | 56 | zh | 0.992736 |
# -*- coding: utf-8 -*-
import itertools
import logging
import numpy as np
from collections import OrderedDict
from collections.abc import Mapping
from typing import Dict, List, Optional, Tuple, Union
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor, nn
from detectron2.layers import S... | detectron2/modeling/mmdet_wrapper.py | 10,813 | Wrapper of mmdetection backbones to use in detectron2.
mmdet backbones produce list/tuple of tensors, while detectron2 backbones
produce a dict of tensors. This class wraps the given backbone to produce
output in detectron2's convention, so it can be used in place of detectron2
backbones.
Wrapper of a mmdetection dete... | 2,464 | en | 0.782482 |
"""
@Author: Rossi
Created At: 2021-02-21
"""
import json
import time
from mako.template import Template
from Broca.faq_engine.index import ESIndex, VectorIndex
from Broca.message import BotMessage
class FAQAgent:
def __init__(self, agent_name, es_index, vector_index, threshold, topk, prompt_threshold,
... | Broca/faq_engine/agent.py | 2,897 | Respond to the user message by retriving documents from the knowledge base.
Args:
message ([type]): [description]
@Author: Rossi
Created At: 2021-02-21
wait until the es index gets ready | 194 | en | 0.689047 |
# -*- coding: utf-8 -*-
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
from .common import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', default... | config/settings/local.py | 1,961 | Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
-*- coding: utf-8 -*- noqa DEBUG ------------------------------------------------------------------------------ SECRET CONFIGURATION ----------------------------------------------------------... | 993 | en | 0.323688 |
import argparse
import torch.optim as optim
import sys
from utils import *
from data import data_generator
import time
import math
from setproctitle import setproctitle
import warnings
sys.path.append("../")
from model import TrellisNetModel
warnings.filterwarnings("ignore") # Suppress the RunTimeWarning on unicode... | char_PTB/char_ptb.py | 14,354 | Suppress the RunTimeWarning on unicode For most of the time, you should change these two together Set the random seed manually for reproducibility. Load data this flush method is needed for python 3 compatibility. this handles the flush command by doing nothing. you might want to specify some extra behavior here. Build... | 610 | en | 0.876647 |
import copy
import sys
from abc import ABC, abstractmethod
from enum import Enum
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Tuple, Union
import yaml
from ._utils import (
_DEFAULT_MARKER_,
ValueKind,
_ensure_container,
_get_value,
_is_interpolation,
_is_missing_lite... | omegaconf/basecontainer.py | 32,085 | Get node[key] and ensure it is compatible with value_type_hint, mutating if necessary.
Ensure node is compatible with type_hint, mutating if necessary.
merge src into dest and return a new copy, does not modified input
returns the value with the specified key, like obj.key and obj['key']
Changes the value of the node k... | 2,287 | en | 0.747943 |
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... | src/braket/device_schema/dwave/dwave_device_capabilities_v1.py | 4,396 | These are the capabilities specific to D-Wave device
Attributes:
provider: Properties specific to D-Wave provider
Examples:
>>> import json
>>> input_json = ...{
... "braketSchemaHeader": {
... "name": "braket.device_schema.dwave.dwave_device_capabilities",
... "version": "1",... | 3,467 | en | 0.438944 |
from pathlib import Path
from subprocess import PIPE, CalledProcessError
from typing import Iterable, List, Tuple, Union
import matplotlib.pyplot as plt
PathLike = Union[Path, str]
conf_opening, conf_closing = "+++++", "-----"
def profile_config_file(
binary_path: PathLike,
config_path: PathLike,
output... | hpvm/projects/hpvm-profiler/hpvm_profiler/__init__.py | 7,849 | Plot the QoS-speedup information in an HPVM configuration file.
It is recommended to profile the config file first (using `profile_configs`)
to obtain real speedup numbers.
This function creates a `matplotlib.pyplot.Figure`, plots on it, and returns it.
:param config_path: Path to the config file (HPVM configuration f... | 2,207 | en | 0.821002 |
# pylint: disable=too-many-lines
import os
import random
import shutil
import time
import uuid
from retval import RetVal
from pycryptostring import CryptoString
from pymensago.encryption import EncryptionPair
from pymensago.hash import blake2hash
from pymensago.serverconn import ServerConnection
from integration_set... | tests/integration/test_fscmds.py | 42,375 | Generate a test file containing nothing but zeroes. If the file size is negative, a random
size between 1 and 10 Kb will be chosen. If the file name is empty, a random one will be
generated.
Returns:
name: (str) name of the test file generated
size: (int) size of the test file generated
Creates a tes... | 4,486 | en | 0.673196 |
# Copyright 2017 Battelle Energy Alliance, 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 agreed t... | framework/SupervisedLearning/pickledROM.py | 3,820 | Placeholder for ROMs that will be generated by unpickling from file.
This should return an estimation of the quality of the prediction.
@ In, featureVals, 2-D numpy array, [n_samples,n_features]
@ Out, confidence, float, the confidence
Evaluates a point.
@ In, featureVals, list, of values at which to evaluate the ROM
@... | 2,453 | en | 0.687333 |
#******************************************************************************
# Copyright (C) 2013 Kenneth L. Ho
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain t... | scipy/linalg/interpolative.py | 32,091 | Estimate matrix rank to a specified relative precision using randomized
methods.
The matrix `A` can be given as either a :class:`numpy.ndarray` or a
:class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used
for each case. If `A` is of type :class:`numpy.ndarray`, then the output
rank is typically abo... | 22,814 | en | 0.577698 |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | generated/ansible-collection/subscriptionssubscriptionfactory.py | 13,032 | !/usr/bin/python Copyright (c) 2019 Zim Kalinowski, (@zikalino) GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) this is handled in azure_rm_common if not old_response: else: self.results['changed'] = old_response.__ne__(response) make sure instance is actually deleted, for... | 754 | en | 0.698617 |
from __future__ import print_function
import gevent
import gevent.core
import os
import time
filename = 'tmp.test__core_stat.%s' % os.getpid()
hub = gevent.get_hub()
DELAY = 0.5
EV_USE_INOTIFY = getattr(gevent.core, 'EV_USE_INOTIFY', None)
try:
open(filename, 'wb', buffering=0).close()
assert os.path.exis... | greentest/test__core_stat.py | 2,155 | If we don't specify an interval, we default to zero. libev interprets that as meaning to use its default interval, which is about 5 seconds. If we go below it's minimum check threshold, it bumps it up to the minimum. The watcher interval changed after it started; -1 is illegal | 277 | en | 0.892647 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
from django.urls import include, url
except ImportError:
from django.conf.urls import include, url # noqa: F401
| src/rest_framework_jwt/compat.py | 193 | -*- coding: utf-8 -*- noqa: F401 | 32 | en | 0.651544 |
#!/usr/bin/env python
import urllib,urllib2
import json
import csv
import time
from datetime import date, timedelta
class Admin:
'''A class of tools for administering AGO Orgs or Portals'''
def __init__(self, username, portal=None, password=None):
from . import User
self.user = User(username,... | admin.py | 32,423 | !/usr/bin/env pythonif not roles: roles = ['org_admin', 'org_publisher', 'org_user']roles = ['org_admin', 'org_publisher', 'org_author', 'org_viewer'] new roles to support Dec 2013 updatethe role property of a user is either one of the standard roles or a custom role ID. Loop through and build a list of ids from the... | 1,908 | en | 0.839523 |
import re
from typing import TypeVar
import questionary
EnumType = TypeVar("EnumType")
# 驼峰命名转蛇形命名
def camel_to_snake(text: str) -> str:
return re.sub(r"(?<!^)(?=[A-Z])", "_", text).lower()
# 蛇形命名转驼峰命名
def snake_to_camel(text: str) -> str:
return text.split('_')[0] + "".join(x.title() for x in text.split('... | fastapi_builder/helpers.py | 980 | 驼峰命名转蛇形命名 蛇形命名转驼峰命名 驼峰命名转帕斯卡命名 type: ignore | 43 | zh | 0.879463 |
# 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
fro... | sdk/python/pulumi_azure_native/network/v20201101/network_virtual_appliance.py | 23,872 | The set of arguments for constructing a NetworkVirtualAppliance resource.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input[str]]] boot_strap_configuration_blobs: BootStrapConfigurationBlobs storage URLs.
:param pulumi.Input[str] cloud_init_configura... | 4,345 | en | 0.527846 |
"""Integration tests for Glesys"""
from unittest import TestCase
import pytest
from lexicon.tests.providers.integration_tests import IntegrationTestsV1
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# pass, by inheritanc... | lexicon/tests/providers/test_glesys.py | 830 | TestCase for Glesys
Integration tests for Glesys
Hook into testing framework by inheriting unittest.TestCase and reuse the tests which *each and every* implementation of the interface must pass, by inheritance from define_tests.TheTests TODO: migrate to IntegrationTestsV2 and its extended test suite TODO: enable the ... | 333 | en | 0.817241 |
from datetime import timedelta
from random import randint
from ichnaea.data.tasks import (
monitor_api_key_limits,
monitor_api_users,
monitor_queue_size,
)
from ichnaea import util
class TestMonitor(object):
def test_monitor_api_keys_empty(self, celery, stats):
monitor_api_key_limits.delay()... | ichnaea/data/tests/test_monitor.py | 4,709 | add some other items into Redis add the same IPs + one new one again add one entry which is too old we count unique IPs over the entire 7 day period, so it's just 3 uniques the too old key was deleted manually | 209 | en | 0.947902 |
"""
# =============================================================================
# Creates the stiffness matrix as requested, using the material properties
# provided in the TPD file (for v2020 files).
#
# Author: William Hunter, Tarcísio L. de Oliveira
# Copyright (C) 2008, 2015, William Hunter.
# Copyright (C) 2... | topy/data/H8T_K.py | 2,459 | Initialize variables element dimensions (half-lengths) modulus of rigidity SymPy symbols: Shape functions: Create strain-displacement matrix B: Create conductivity matrix: Integration: Convert SymPy Matrix to NumPy array: Set small (<< 0) values equal to zero: Return result: EOF H8T_K.py | 288 | en | 0.38778 |
import math
def is_prime_power(n):
#even number divisible
factors = set()
while n % 2 == 0:
factors.add(2)
n = n / 2
#n became odd
for i in range(3,int(math.sqrt(n))+1,2):
while (n % i == 0):
factors.add(i)
n = n / i
if n > 2:
factors.add(n)
ret... | Prime Powers/prime_powers.py | 565 | even number divisiblen became odd | 33 | en | 0.991762 |
# 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... | test/integration/component/test_stopped_vm.py | 82,016 | Test Stopped VM Life Cycle Services
Test Deploy HA enabled Virtual Machine with startvm=false
Test Deploy Virtual Machine with no startVM parameter
Test Deploy Virtual Machine with no startVM parameter
Test Deploy HA enabled Virtual Machine from ISO
Test Deploy Virtual Machine w... | 7,122 | en | 0.731438 |
# Created by Qingzhi Ma at 2019-07-24
# All right reserved
# Department of Computer Science
# the University of Warwick
# Q.Ma.2@warwick.ac.uk
from dbestclient.ml.density import DBEstDensity
from dbestclient.ml.modelwraper import SimpleModelWrapper, GroupByModelWrapper
from dbestclient.ml.regression import DBEstReg
fro... | dbestclient/ml/modeltrainer.py | 2,607 | Created by Qingzhi Ma at 2019-07-24 All right reserved Department of Computer Science the University of Warwick Q.Ma.2@warwick.ac.uk print(self.groupby_model_wrapper) | 166 | en | 0.764769 |
from sanic import Sanic, response, Blueprint
from sanic.request import RequestParameters
from sanic_jinja2 import SanicJinja2
from sanic_session import Session, AIORedisSessionInterface
import aiosqlite
import aiofiles
import aioredis
import asyncio
import json
import html
import sys
import os
import re
... | app.py | 42,730 | 위키 설정 주소 설정 오류 페이지 구현 필요 오류 페이지 구현 필요 오류 페이지 구현 필요 오류 페이지 구현 필요 오류 페이지 구현 필요 오류 페이지 구현 필요 오류 페이지 구현 필요 추후 권한 개편 시 member가 아닌 직접 선택하도록 변경. 오류 페이지 구현 필요 오류 구현 필요 오류 구현 필요 비효율적인 구조, 추후 개선 예정. | 188 | ko | 1.00007 |
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Intel Corporation
#
# 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... | neural_compressor/ux/web/service/optimization.py | 1,359 | Optimization related services.
Return data for requested Workload.
Optimization service.
-*- coding: utf-8 -*- Copyright (c) 2022 Intel Corporation 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 ... | 669 | en | 0.854558 |
# A lista a seguir possui mais uma lista interna, a lista de preços.
# A lista de preços possui 3 sublistas dentro dela com os preços dos produtos.
# para exemplificar, o preço do mamão é de 10.00 - alface crespa é de 2.99 e o feijão 9.0
# Será solicitado o preço de alguns produtos. para imprimir deve ser por f-string ... | Aula18/rev3.py | 1,853 | A lista a seguir possui mais uma lista interna, a lista de preços. A lista de preços possui 3 sublistas dentro dela com os preços dos produtos. para exemplificar, o preço do mamão é de 10.00 - alface crespa é de 2.99 e o feijão 9.0 Será solicitado o preço de alguns produtos. para imprimir deve ser por f-string refrenci... | 1,016 | pt | 0.927055 |
# Copyright 2018, Erlang Solutions Ltd, and S2HC Sweden AB
#
# 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... | pyrlang/net_kernel.py | 1,326 | A special process which registers itself as ``net_kernel`` and handles
one specific ``is_auth`` message, which is used by ``net_adm:ping``.
:param node: pyrlang.node.Node
Copyright 2018, Erlang Solutions Ltd, and S2HC Sweden AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use t... | 756 | en | 0.844528 |
#!/bin/python
import platform
import fabric.api
from fabric.contrib.files import exists as remote_exists
from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
def _get_distro_info():
distro, _, release = platform.linux_distribution(
full_distribution_name=False)
return '{0} {... | components/nginx/scripts/retrieve_agents.py | 1,895 | !/bin/python This is a workaround for mapping Centos release names to versions to provide a better UX when providing agent inputs. | 130 | en | 0.841333 |
# Generated by Django 3.0.5 on 2020-04-22 02:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0057_sugestaoturma_horarios'),
]
operations = [
migrations.RemoveField(
model_name='sugestaoturma',
name='ho... | core/migrations/0058_auto_20200421_2342.py | 516 | Generated by Django 3.0.5 on 2020-04-22 02:42 | 45 | en | 0.621098 |
"""This module defines classes that handle mesh and mesh operations.
This module defines a factory class for mesh, similar to geometry and
size function factory class. It also defines concrete mesh types.
Currently two concrete mesh types are defined for generic Eucledian
mesh and specific 2D Eucledian mesh.
"""
from ... | ocsmesh/mesh/mesh.py | 66,711 | Helper class for mesh boundary condition calculation
Attributes
----------
data : dict
Mapping for boundary information
Methods
-------
__call__()
Retrieves a dataframe for all boundary shapes and type info.
__len__()
Gets the number of calculated boundary segments.
ocean()
Retrieves a dataframe conta... | 24,834 | en | 0.638265 |
#
# Solution to Project Euler problem 287
# Copyright (c) Project Nayuki. All rights reserved.
#
# https://www.nayuki.io/page/project-euler-solutions
# https://github.com/nayuki/Project-Euler-solutions
#
# Let R = 2^(N-1) denote the radius of the circle (filled disk) being drawn.
#
# First, we can simplify the pr... | solutions/p287.py | 3,739 | Solution to Project Euler problem 287 Copyright (c) Project Nayuki. All rights reserved. https://www.nayuki.io/page/project-euler-solutions https://github.com/nayuki/Project-Euler-solutions Let R = 2^(N-1) denote the radius of the circle (filled disk) being drawn. First, we can simplify the problem by translating (s... | 2,798 | en | 0.776481 |
from probs import Binomial
class TestBinomial:
@staticmethod
def test_binomial() -> None:
d = Binomial()
assert d.expectation() == 0
assert d.variance() == 0
# TODO: Python 3.7 implementation differs from 3.8+
# assert P(d == 0) == 1
# assert P(d == 1) == 0
... | tests/discrete/binomial_test.py | 1,131 | TODO: Python 3.7 implementation differs from 3.8+ assert P(d == 0) == 1 assert P(d == 1) == 0 assert P(d == 2) == 0 d = Binomial(n=6, p=0.7) assert P(d == 0) == 0.000729 assert P(d == 1) == 0.010206 assert P(d == 2) == 0.059535 assert P(d == 3) == 0.18522 assert P(d == 4) == 0.324135 assert P(d == 5) == 0.302526 assert... | 446 | en | 0.425191 |
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_cnn import TextCNN
from tensorflow.contrib import learn
# Parameters
# ==================================================
# Data loading params 语料文件路径定义
tf.flags.DEFINE... | test.py | 3,276 | ! /usr/bin/env python Parameters ================================================== Data loading params 语料文件路径定义 Model Hyperparameters 定义网络超参数 Training parameters Misc Parameters Data Preparation ================================================== Load data Build vocabulary 将词向量填充至max_length的长度 Randomly shuffle data | 316 | fr | 0.392463 |
import pytest
import json
from collections import OrderedDict
from great_expectations.profile.base import DatasetProfiler
from great_expectations.profile.basic_dataset_profiler import BasicDatasetProfiler
from great_expectations.profile.columns_exist import ColumnsExistProfiler
from great_expectations.dataset.pandas_... | tests/profile/test_profile.py | 13,084 | Unit test to check the expectations that BasicDatasetProfiler creates for a high cardinality
non numeric column.
The test is executed against all the backends (Pandas, Spark, etc.), because it uses
the fixture.
Unit test to check the expectations that BasicDatasetProfiler creates for a low cardinality
non numeric colum... | 2,669 | en | 0.774634 |
import os
import codecs
from busSchedules import schedule1B
from busSchedules import schedule2
from busSchedules import schedule3
from busSchedules import schedule4
from busSchedules import schedule5
from busSchedules import schedule6
from busZonesTimes import busZonesTimesOne
from busZonesTimes import busZone... | app.py | 10,264 | Create a class called BusStop that will take line, name, address, latitude and longitude. Horarios por ZONA ============================================================ Horarios por ZONA Domingo ============================================================ Horarios por ZONA Sabado ======================================... | 617 | fr | 0.410955 |
"""
Concatenate the labels with the notes data and split using the saved splits
"""
import csv
from datetime import datetime
import random
from constants import DATA_DIR
from constants import MIMIC_3_DIR
import pandas as pd
DATETIME_FORMAT = "%Y-%m-%d %H-%M-%S"
def concat_data(labelsfile, notes_file):
"""
... | dataproc/concat_and_split.py | 4,453 | INPUTS:
labelsfile: sorted by hadm id, contains one label per line
notes_file: sorted by hadm id, contains one note per line
Generator for label sets from the label file
Generator for notes from the notes file
This will also concatenate discharge summaries and their addenda, which have the same subject and hadm... | 718 | en | 0.865547 |
import os
import json
import logging
from dataclasses import dataclass, field
from typing import Dict, Optional, Callable
import torch
import wandb
import numpy as np
from tqdm.auto import tqdm
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.distrib... | src/mtl_trainer.py | 15,704 | Sample tasks using uncertainty measure.
Prediction/evaluation loop, shared by `evaluate()` and `predict()`.
Works both with or without labels.
self.data_collator = DefaultDataCollator() free GPU mem Handled the last batch if it is lower than the batch size for determinism across runs https://github.com/pytorc... | 827 | en | 0.804577 |
# coding: utf-8
"""
Influx API Service
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: 0.1.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F40... | influxdb_client/service/health_service.py | 4,235 | NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
Get the health of an instance anytime during execution. Allow us to check if the instance is still healthy. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asyn... | 1,573 | en | 0.770791 |
# -*- coding: utf-8 -*-
# Copyright 2022 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... | samples/generated_samples/aiplatform_v1_generated_specialist_pool_service_create_specialist_pool_async.py | 1,827 | -*- coding: utf-8 -*- Copyright 2022 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 agreed to in writin... | 1,141 | en | 0.778987 |
#!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import os
import argparse
from os.path import join as pjoin
import numpy as np
import networkx as nx
from textworld.render import visualize
from textworld.generator import Game
from textworld.generat... | scripts/sample_quests.py | 3,493 | !/usr/bin/env python Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. Load game for which to sample quests for. Sample quests. Convert chains to networkx graph/tree | 205 | en | 0.799064 |
#modo indireto
'''import math
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print('A raiz de {} é {}'.format(num, math.ceil(raiz)))'''
#modo direto
from math import sqrt, floor
num = int(input('Digite um número:'))
raiz = sqrt(num)
print('A raiz de {} é {:.2f}'.format(num, floor(raiz)))
| Python/PycharmProjects/aula 8/1.py | 308 | import math
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print('A raiz de {} é {}'.format(num, math.ceil(raiz)))
modo indiretomodo direto | 154 | pt | 0.702445 |
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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
#
# ... | osdf/adapters/policy/utils.py | 3,617 | Filter policies using the following steps:
1. Apply prioritization among the policies that are sharing the same policy type and resource type
2. Remove redundant policies that may applicable across different types of resource
3. Filter policies based on type and return
:param flat_policies: list of flat policies
:retur... | 1,853 | en | 0.709535 |
#!/usr/bin/env python
#
# File Name : ptbtokenizer.py
#
# Description : Do the PTB Tokenization and remove punctuations.
#
# Creation Date : 29-12-2014
# Last Modified : Thu Mar 19 09:53:35 2015
# Authors : Hao Fang <hfang@uw.edu> and Tsung-Yi Lin <tl483@cornell.edu>
import os
import sys
import subprocess
import temp... | densevid_eval-master/coco-caption/pycocoevalcap/tokenizer/ptbtokenizer.py | 2,827 | Python wrapper of Stanford PTBTokenizer
!/usr/bin/env python File Name : ptbtokenizer.py Description : Do the PTB Tokenization and remove punctuations. Creation Date : 29-12-2014 Last Modified : Thu Mar 19 09:53:35 2015 Authors : Hao Fang <hfang@uw.edu> and Tsung-Yi Lin <tl483@cornell.edu> path to the stanford corenl... | 951 | en | 0.47535 |
""" Implementation of mooda.read_pkl(path) """
import pickle
from .. import WaterFrame
def read_pkl(path_pkl):
"""
Get a WaterFrame from a pickle file.
Parameters
----------
path_pkl: str
Location of the pickle file.
Returns
-------
wf_pkl: WaterFram... | mooda/input/read_pkl.py | 598 | Get a WaterFrame from a pickle file.
Parameters
----------
path_pkl: str
Location of the pickle file.
Returns
-------
wf_pkl: WaterFrame
Implementation of mooda.read_pkl(path) | 193 | en | 0.535675 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: requirement_instance.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google... | console_gateway_sdk/model/tuna_service/requirement_instance_pb2.py | 8,108 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: requirement_instance.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:tuna_service.RequirementInstance) @@protoc_insertion_point(module_scope) | 257 | en | 0.528753 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# cob documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 7 18:09:10 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autoge... | docs/conf.py | 5,863 | !/usr/bin/env python3 -*- coding: utf-8 -*- cob documentation build configuration file, created by sphinx-quickstart on Sun Jan 7 18:09:10 2018. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All con... | 4,084 | en | 0.674222 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Textfont(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scatter3d"
_path_str = "scatter3d.textfont"
_valid_props = {"color", "colorsrc", "family",... | packages/python/plotly/plotly/graph_objs/scatter3d/_textfont.py | 10,225 | Construct a new Textfont object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.Textfont`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that w... | 5,097 | en | 0.581344 |
# qubit number=5
# total number=48
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=3
pr... | benchmark/startPyquil1068.py | 2,162 | qubit number=5 total number=48 circuit begin number=3 number=28 number=4 number=39 number=5 number=6 number=21 number=1 number=40 number=35 number=2 number=7 number=8 number=25 number=26 number=27 number=36 number=37 number=38 number=41 number=45 number=46 number=47 number=43 number=34 number=24 number=29 number=44 num... | 448 | en | 0.180322 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Internet Explorer WebCache database."""
import unittest
from plaso.lib import definitions
from plaso.parsers.esedb_plugins import msie_webcache
from tests.parsers.esedb_plugins import test_lib
class MsieWebCacheESEDBPluginTest(test_lib.ESEDB... | tests/parsers/esedb_plugins/msie_webcache.py | 3,923 | Tests for the MSIE WebCache ESE database plugin.
Tests the _ConvertHeadersValues function.
Tests the Process function on database with a PartitionsEx table.
Tests the Process function on database with a Partitions table.
Tests for the Microsoft Internet Explorer WebCache database.
!/usr/bin/env python3 -*- coding: utf... | 585 | en | 0.599794 |
""" converted from Matlab code
source: http://www.robots.ox.ac.uk/~fwood/teaching/AIMS_CDT_ML_2015/homework/HW_2_em/
"""
import numpy as np
def m_step_gaussian_mixture(data, gamma):
"""% Performs the M-step of the EM algorithm for gaussain mixture model.
%
% @param data : n x d matrix with rows as d dim... | src/ML_Algorithms/ExpectationMaximization/m_step_gaussian_mixture.py | 1,217 | % Performs the M-step of the EM algorithm for gaussain mixture model.
%
% @param data : n x d matrix with rows as d dimensional data points
% @param gamma : n x k matrix of resposibilities
%
% @return pi : k x 1 array
% @return mu : k x d matrix of maximized cluster centers
% @return sigma : cell array of maxi... | 441 | en | 0.518752 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
__all__ = [
"wigner3j",
"get_camb_cl",
"scale_dust",
]
def blackbody(nu, ref_freq=353.0):
"""
The ratio of the blackbody function for dust at frequency nu
over the v... | xfaster/spec_tools.py | 6,067 | The ratio of the blackbody function for dust at frequency nu
over the value for reference frequency ref_freq
Arguments
---------
nu : float
Frequency in GHz.
ref_freq : float
Reference frequency in GHz.
Returns
-------
blackbody_ratio : float
B(nu, T_dust) / B(nu_ref, T_dust)
Compute camb spectrum with te... | 3,238 | en | 0.544749 |
#!/usr/bin/env python
# coding: utf-8
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# Permission is hereby granted, fr... | pyFAI/test/test_pickle.py | 4,371 | !/usr/bin/env python coding: utf-8 Project: Azimuthal integration https://github.com/silx-kit/pyFAI Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu) Permission is hereby granted, free of charge, to any ... | 1,366 | en | 0.827593 |
import string
import random
from functools import wraps
from urllib.parse import urlencode
from seafileapi.exceptions import ClientHttpError, DoesNotExist
def randstring(length=0):
if length == 0:
length = random.randint(1, 30)
return ''.join(random.choice(string.lowercase) for i in range(length))
def... | seafileapi/utils.py | 1,442 | Decorator to turn a function that get a http 404 response to a
:exc:`DoesNotExist` exception. | 93 | en | 0.723587 |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... | tencentcloud/mongodb/v20180408/models.py | 50,620 | AssignProject请求参数结构体
AssignProject返回参数结构体
客户端连接信息,包括客户端IP和连接数
CreateDBInstanceHour请求参数结构体
CreateDBInstanceHour返回参数结构体
CreateDBInstance请求参数结构体
CreateDBInstance返回参数结构体
DescribeClientConnections请求参数结构体
DescribeClientConnections返回参数结构体
DescribeDBInstances请求参数结构体
D... | 13,021 | zh | 0.502527 |
import numpy as np
import pytest
import tensorflow as tf
from garage.tf.models.gru import gru
from tests.fixtures import TfGraphTestCase
from tests.helpers import recurrent_step_gru
class TestGRU(TfGraphTestCase):
def setup_method(self):
super().setup_method()
self.batch_size = 2
self.hi... | garaged/tests/garage/tf/models/test_gru.py | 17,963 | yapf: disable noqa: E122 yapf: enable Compute output by doing t step() on the gru cell noqa: E126 yapf: disable noqa: E122 yapf: enable Compute output by doing t step() on the gru cell noqa: E126 yapf: disable yapf: enable Compute output by doing t step() on the gru cell noqa: E126 Compute output by doing t step() on t... | 590 | en | 0.661182 |
# -*- coding: utf-8 -*-
"""This file contains a basic Skype SQLite parser."""
import logging
from plaso.events import time_events
from plaso.parsers import sqlite
from plaso.parsers.sqlite_plugins import interface
__author__ = 'Joaquin Moreno Garijo (bastionado@gmail.com)'
class SkypeChatEvent(time_events.PosixTi... | plaso/parsers/sqlite_plugins/skype.py | 16,602 | Convenience class for account information.
Convenience EventObject for the calls.
Convenience class for a Skype event.
SQLite plugin for Skype main.db SQlite database file.
Convenience EventObject for SMS.
Evaluate the action of send a file.
Parses the Accounts database.
Args:
parser_mediator: A parser mediator obje... | 4,757 | en | 0.747821 |
import pycrfsuite
import sklearn
from itertools import chain
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import LabelBinarizer
import re
import json
annotypes = ['Participants', 'Intervention', 'Outcome']
annotype = annotypes[0]
path = '/nlp/data/romap/crf/'
#path = '... | crf-seq/sets/sets/4/seq_detect_1p.py | 10,351 | path = '/Users/romapatel/Desktop/crf/'filename = annotype.lower() + '_words.txt'word = line[:-1]all lowercasedfilename = annotype.lower() + '_pattern_copy.txt'word = line[:-1].lower()prev previous wordprevious wordnext to next wordnext wordif count >= 100: break | 262 | en | 0.388581 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.