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 |
|---|---|---|---|---|---|---|
'''
BVH Parser Class
By Omid Alemi
Created: June 12, 2017
Based on: https://gist.github.com/johnfredcee/2007503
'''
import re
import numpy as np
from data import Joint, MocapData
class BVHScanner:
'''
A wrapper class for re.Scanner
'''
def __init__(self):
def identifier(scanner, token):
... | app/resources/pymo/pymo/parsers.py | 8,255 | A class to parse a BVH file.
Extracts the skeleton and channel values
A wrapper class for re.Scanner
Returns all of the channels parsed from the file as a pandas DataFrame
BVH Parser Class
By Omid Alemi
Created: June 12, 2017
Based on: https://gist.github.com/johnfredcee/2007503
(r'-*[0-9]+(\.[0-9]+)?', digit), wo... | 463 | en | 0.68317 |
import requests
import logging
import os
import selenium
import unittest
import time
import requests, re
from django.core.management.base import BaseCommand
from search.models import Product, Category, DetailProduct
from django.db import IntegrityError
from django.core.exceptions import MultipleObjectsReturned
from lo... | search/management/commands/test_selenium.py | 5,155 | self.testResetPassword() self.driver.maximize_window() self.driver.maximize_window() self.driver.maximize_window() | 114 | en | 0.179059 |
import asyncio
import datetime
import importlib
import itertools
import os
import random
import re
import shutil
import signal
import subprocess
import sys
import time
import zipfile
import discord
import psutil
from src import const
from src.algorithms import levenshtein_distance
from src.bc import DoNotUpdateFlag
f... | src/bot.py | 25,162 | Sightly patched implementation from discord.py discord.Client (parent) class Reference: https://github.com/Rapptz/discord.py/blob/master/discord/client.py Inherit parent channel settings for threads Check whether bot is already running Some variable initializations Handle --nohup flag Selecting YAML parser Saving appli... | 675 | en | 0.724693 |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
... | qa/pull-tester/rpc-tests.py | 8,739 | !/usr/bin/env python2 Copyright (c) 2014-2015 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.If imported values are not defined then set to zero (or disabled)Create a set to store arguments and create the pa... | 1,265 | en | 0.789271 |
'''
URL: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
Difficulty: Easy
Description: Maximum Nesting Depth of the Parentheses
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It c... | 1614 Maximum Nesting Depth of the Parentheses.py | 1,733 | URL: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
Difficulty: Easy
Description: Maximum Nesting Depth of the Parentheses
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It can b... | 1,351 | en | 0.848085 |
def remove_nan_entries(df, key_columns, verbose=True):
n_row = len(df)
for column in key_columns:
df = df[df[column] == df[column]]
if verbose:
print("Prune ({}/{}) rows.".format(n_row - len(df), n_row))
return df
def parse_relationship_path(relationship_path):
# TODO: get the rela... | vbridge/utils/entityset_helpers.py | 5,296 | Find a path of the source entity to the target_entity.
TODO: get the relationship with a public function instead Transfer cutoff_times to "child", e.g., PATIENTS -> ADMISSIONS Transfer cutoff_times to "parent", e.g., ADMISSIONS -> PATIENTS select records by SUBJECT_ID select records before or at the cutoff_time TODO ... | 422 | en | 0.778927 |
from django.test import TestCase
# Create your tests here.
class Account(TestCase):
def test_register(self):
self.assertTrue(True)
| hhcms/apps/account/tests.py | 147 | Create your tests here. | 23 | en | 0.899389 |
import gc
import string
import random
class ActiveGarbageCollection:
def __init__(self, title):
assert gc.isenabled(), "Garbage collection should be enabled"
self.title = title
def __enter__(self):
self._collect("start")
return self
def __exit__(self, exc_type, exc_val, ... | src/gobupload/utils.py | 1,930 | Get the highest event id from the entities and the eventid of the most recent event
:param storage: GOB (events + entities)
:return:highest entity eventid and last eventid
Returns a random string of length :length: consisting of lowercase characters and digits
:param length:
:return:
no events, no entities events b... | 480 | en | 0.904267 |
import tensorflow as tf
import cPickle as pickle
import rnn_model
import cnn_model
from dataloader import Dataloader
import os
import datetime
import numpy as np
import argparse
from cnn_model import unroll
def main():
parser = argparse.ArgumentParser(description='Evaluate .')
parser.add_argument('rundir', ty... | evaluate.py | 12,145 | This function initialized a model from the <init_from> directory and calculates
probabilities, and confusion matrices based on all data stored in
one epoch of dataloader (usually test data)
:param model: rnn_model object containing tensorflow graph
:param dataloader: DataLoader object f... | 2,702 | en | 0.683857 |
#! /usr/bin/env python
# coding=utf-8
import os
import time
import shutil
import numpy as np
import tensorflow as tf
import core.utils as utils
from tqdm import tqdm
from core.dataset import Dataset
from core.yolov3 import YOLOV3
from core.config import cfg
class YoloTrain(object):
def __init__(self): # 从config文... | train.py | 9,978 | ! /usr/bin/env python coding=utf-8 从config文件获取到一些变量 日志保存地址 定义输入层 定义损失函数 定义学习率 指数平滑,可以让算法在最后不那么震荡,结果更有鲁棒性 指定需要恢复的参数。层等信息, 位置提前,减少模型体积。 第一阶段训练,只训练指定层 第二阶段训练,释放所有层 日志保存地址 阶段学习率 tqdm is a visualization tool that displays an Iterable object in a progree bar | 253 | zh | 0.947621 |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
from collections import namedtuple
from flask import session
from flask.ext.lo... | src/ggrc/rbac/permissions_provider.py | 5,103 | All contexts in which the user has create permission.
All contexts in which the user has delete permission.
Whether or not the user is allowed to create a resource of the specified
type in the context.
Whether or not the user is allowed to delete a resource of the specified
type in the context.
Whether or not the user ... | 1,352 | en | 0.867623 |
"""
Django settings for session_words project.
Generated by 'django-admin startproject' using Django 1.11.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
im... | Django/session_words/session_words/settings.py | 3,135 | Django settings for session_words project.
Generated by 'django-admin startproject' using Django 1.11.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
Build pat... | 1,003 | en | 0.643611 |
import unittest
import tfexpt
import expt
from tensorlog import matrixdb
from tensorlog import program
from tensorlog import dataset
class TestNative(unittest.TestCase):
def setUp(self):
(self.n,self.maxD,self.epochs) = (16,8,20)
(self.factFile,trainFile,testFile) = expt.genInputs(self.n)
# (self.factF... | datasets/grid/testexpt.py | 1,474 | (self.factFile,self.trainFile,self.testFile) = ('inputs/g16.cfacts','inputs/g16-train.exam','inputs/g16-test.exam') | 115 | en | 0.233345 |
import hashlib
import random
from typing import Tuple, Dict
from self_driving.beamng_config import BeamNGConfig
from self_driving.beamng_evaluator import BeamNGEvaluator
from core.member import Member
from self_driving.catmull_rom import catmull_rom
from self_driving.road_bbox import RoadBoundingBox
from self_driving.... | DeepHyperion-BNG/self_driving/beamng_member.py | 6,969 | A class representing a road returned by the RoadGenerator.
assert not self.needs_evaluation()TODOreturn frechet_dist(self.sample_nodes, other.sample_nodes)return frechet_dist(self.sample_nodes[0::3], other.sample_nodes[0::3]) Choose the mutation extentmut_value = random.randint(self.lower_bound, self.upper_bound) Avoi... | 485 | en | 0.500883 |
#
# Copyright 2019 The FATE 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... | federatedml/feature/feature_scale/standard_scale.py | 6,596 | Standardize features by removing the mean and scaling to unit variance. The standard score of a sample x is calculated as:
z = (x - u) / s, where u is the mean of the training samples, and s is the standard deviation of the training samples
Apply standard scale for input data
Parameters
----------
data: data_instance, ... | 1,313 | en | 0.727556 |
# -*- coding: utf-8 -*
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
----------------------------------------------... | src/api/auth/bkiam/urls.py | 3,088 | Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
--------------------------------------------------------------------
Perm... | 1,359 | en | 0.852174 |
#link (https://neps.academy/problem/443)
voltas,placas= input().split()
result = int(voltas) * int(placas)
numbers = []
resultado = result * float(str(0) + str('.') + str(1))
for x in range(2,11):
if int(resultado)==resultado:
numbers.append(int(resultado))
else:
numbers.append(int(resultado)+1... | Python/Hora da Corrida - SBC 2019.py | 431 | link (https://neps.academy/problem/443) | 39 | en | 0.541387 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tethys_datasets', '0002_auto_20150119_1756'),
]
operations = [
migrations.CreateModel(
name='SpatialDatasetServi... | tethys_datasets/migrations/0003_spatialdatasetservice.py | 1,282 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import Mode... | train_more.py | 1,877 | model.compile(optimizer = 'Adam',loss = 'binary_crossentropy',metrics = ['accuracy'])checkpoints = ModelCheckpoint("checkpoints/weights.{epoch:02d}.h5", save_weights_only = False, verbose = 1)step_size_train = train_generator.n//train_gen... | 363 | en | 0.5415 |
# -*- coding: utf-8 -*-
# Natural Language Toolkit: Interface to the Stanford Part-of-speech and Named-Entity Taggers
#
# Copyright (C) 2001-2017 NLTK Project
# Author: Nitin Madnani <nmadnani@ets.org>
# Rami Al-Rfou' <ralrfou@cs.stonybrook.edu>
# URL: <http://nltk.org/>
# For license information, see LICENSE.T... | env/lib/python3.6/site-packages/nltk/tag/stanford.py | 7,818 | A class for Named-Entity Tagging with Stanford Tagger. The input is the paths to:
- a model trained on training data
- (optionally) the path to the stanford tagger jar file. If not specified here,
then this jar file must be specified in the CLASSPATH envinroment variable.
- (optionally) the encoding of the training ... | 2,993 | en | 0.635709 |
##############################################################################
#
# Copyright 2019 Leap Beyond Emerging Technologies B.V. (unless otherwise stated)
#
# 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... | catwalk/cicd/build_steps.py | 3,289 | Builds the model into a Dockerised model server image.
Prepares the model to be Dockerised by generating a dockerimage
Docker step by step building blocks:
generate docker image, prepare model, and build model
Copyright 2019 Leap Beyond Emerging Technologies B.V. (unless otherwise stated) Licensed under the Apache ... | 901 | en | 0.838173 |
#!/usr/bin/env python
#
# Copyright (c) 2014 Google, Inc
#
# SPDX-License-Identifier: GPL-2.0+
#
# Intel microcode update tool
from optparse import OptionParser
import os
import re
import struct
import sys
MICROCODE_DIR = 'arch/x86/dts/microcode'
class Microcode:
"""Holds information about the microcode for... | qemu_mode/qemu-2.10.0/roms/u-boot/tools/microcode-tool.py | 11,074 | !/usr/bin/env python Copyright (c) 2014 Google, Inc SPDX-License-Identifier: GPL-2.0+ Intel microcode update tool Convert data into a list of hex words The model is in the 4rd hex word Ignore blank line Omit anything after the last comma Allow a full name to be used Change each word so it will be little-endian in ... | 520 | en | 0.719714 |
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2007-2008 Trolltech ASA. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## Licensees holding a valid Qt License Agreement may use this file in
## accordance... | src/python/Lib/site-packages/PySide/examples/phonon/capabilities.py | 5,051 | !/usr/bin/env python Copyright (C) 2007-2008 Trolltech ASA. All rights reserved. This file is part of the example classes of the Qt Toolkit. Licensees holding a valid Qt License Agreement may use this file in accordance with the rights, responsibilities and obligations contained therein. Please consult your licensing ... | 776 | en | 0.843279 |
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | google/auth/_service_account_info.py | 2,359 | Validates a dictionary containing Google service account data.
Creates and returns a :class:`google.auth.crypt.Signer` instance from the
private key specified in the data.
Args:
data (Mapping[str, str]): The service account data
require (Sequence[str]): List of keys required to be present in the
info.... | 1,531 | en | 0.788716 |
"""
ASGI config for infosafe project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETT... | infosafe/asgi.py | 393 | ASGI config for infosafe project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ | 214 | en | 0.720323 |
from rest_framework import generics
from rest_framework.exceptions import NotFound
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from workprogramsapp.expertise.models import UserExpertise, ExpertiseComments, Expertise
from workprogramsapp.expertise.serializers import UserE... | application/workprogramsapp/expertise/views.py | 6,570 | Редактирование экспертизы
Редактирование экспертизы отдельного пользователя
Редактирование экспертизы отдельного пользователя
создание коммента к экспертизе
View для получения и отправки комментариев
Комментарии можно получить или отправить, указав в адресе id экспертизы,
При желании можно в параметрах указать блок ком... | 870 | ru | 0.996548 |
import datetime
from ..errors import NaiveDateTimeNotAllowed
from ..ewsdatetime import EWSDateTime
from ..util import create_element, set_xml_value, xml_text_to_value, peek, TNS, MNS
from ..version import EXCHANGE_2010
from .common import EWSService
class GetServerTimeZones(EWSService):
"""
MSDN: https://msd... | exchangelib/services/get_server_time_zones.py | 5,814 | MSDN: https://msdn.microsoft.com/en-us/library/office/dd899371(v=exchg.150).aspx
Convert e.g. "trule:Microsoft/Registry/W. Europe Standard Time/2006-Daylight" to (2006, 'Daylight') Apply same conversion to To as for period IDs Apply same conversion to To as for period IDs See TimeZoneTransition.from_xml() We encounte... | 376 | en | 0.763411 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/tensorboard/plugins/projector/projector_plugin_test.py | 5,280 | Integration tests for the Embedding Projector.
Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE... | 802 | en | 0.838456 |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def compute_lr(target_lr, n_epochs, train_set_size, batch_size, warmup):
total = (n_epochs - 1) * int(np.ceil(train_set_size / batch_size))
progress = [float(t) / total for t in range(0, total)]
factor = [p / warmup if p < w... | qurator/sbb_ned/models/evaluation.py | 1,376 | instantiate a second axes that shares the same x-axis | 53 | en | 0.86361 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | documentation/monetdbe/conf.py | 1,957 | Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- If extensions (or mod... | 1,634 | en | 0.691947 |
# Copyright 2015 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" file acc... | dist/awscli/customizations/datapipeline/__init__.py | 16,503 | Convert CLI arguments to Query arguments used by QueryObject.
Copyright 2015 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.amaz... | 1,764 | en | 0.834377 |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ProtectionInfo(object):
"""Implementation of the 'ProtectionInfo' model.
dataLocation defines data location related information.
Attributes:
end_time_usecs (long|int): Specifies the end time for object
retention.
l... | cohesity_management_sdk/models/protection_info.py | 3,747 | Implementation of the 'ProtectionInfo' model.
dataLocation defines data location related information.
Attributes:
end_time_usecs (long|int): Specifies the end time for object
retention.
location (string): Specifies the location of the object.
policy_id (string): Specifies the id of the policy.
... | 1,363 | en | 0.739122 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of Archdiffer and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Created on Sun Mar 4 10:23:41 2018
@author: Pavla Kratochvilova <pavla.kratochvilova@gmail.com>
"""
import operator
import datetime
from f... | archdiffer/flask_frontend/request_parser.py | 5,304 | Make filter template for filtering column values greater or equal to
datetime.
:param column: database model
:param string name: name used in the filter template
:return dict: resulting template
Make filter template for filtering column values less or equal to
datetime.
:param column: database model
:param string nam... | 2,252 | en | 0.51455 |
#
# mcfly
#
# Copyright 2017 Netherlands eScience Center
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | mcfly/modelgen.py | 18,305 | Generate a hyperparameter set that define a CNN model.
Parameters
----------
min_layers : int
minimum of Conv layers
max_layers : int
maximum of Conv layers
min_filters : int
minimum number of filters per Conv layer
max_filters : int
maximum number of filters per Conv layer
min_fc_nodes : int
minim... | 9,677 | en | 0.717775 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions to draw various pygimli matrices with matplotlib."""
import numpy as np
import matplotlib.pyplot as plt
import pygimli as pg
def drawSparseMatrix(ax, mat, **kwargs):
"""Draw a view of a matrix into the axes.
Parameters
----------
ax : mpl a... | pygimli/viewer/mpl/matrixview.py | 3,685 | Draw a view of a matrix into the axes.
Arguments
---------
ax : mpl axis instance, optional
Axis instance where the matrix will be plotted.
mat: pg.Matrix.BlockMatrix
Keyword Arguments
-----------------
spy: bool [False]
Draw all matrix entries instead of colored blocks
Returns
-------
ax:
Examples
------... | 1,648 | en | 0.515833 |
"""This is the core module for accessing using and accessing the bot"""
from .core import Bot
| bot/__init__.py | 95 | This is the core module for accessing using and accessing the bot | 65 | en | 0.64874 |
from abaqusConstants import *
from .BoundaryConditionState import BoundaryConditionState
class DisplacementBaseMotionBCState(BoundaryConditionState):
"""The DisplacementBaseMotionBCState object stores the propagating data for a velocity base
motion boundary condition in a step. One instance of this object is ... | src/abaqus/BoundaryCondition/DisplacementBaseMotionBCState.py | 2,646 | The DisplacementBaseMotionBCState object stores the propagating data for a velocity base
motion boundary condition in a step. One instance of this object is created internally
by the DisplacementBaseMotionBC object for each step. The instance is also deleted
internally by the DisplacementBaseMotionBC object.
The Dis... | 2,117 | en | 0.690103 |
from abc import abstractmethod, ABCMeta
from collections import deque
from functools import partial
from plenum.common.constants import VIEW_CHANGE_START, PreVCStrategies, VIEW_CHANGE_CONTINUE
from plenum.common.messages.node_messages import ViewChangeStartMessage, ViewChangeContinueMessage, PrePrepare, Prepare, \
... | plenum/server/view_change/pre_view_change_strategies.py | 6,439 | Abstract class for routines before starting viewChange procedure
Strategy logic:
- when startViewChange method was called, then put 'local' ViewChangeStart message and set corresponded handlers
- on processing startViewChange message on the nodeInBoxRouter's side the next steps will be performed:
- call nodestack.s... | 708 | en | 0.807794 |
#!/usr/bin/env python3
import os
from aws_cdk import core as cdk
# For consistency with TypeScript code, `cdk` is the preferred import name for
# the CDK's core module. The following line also imports it as `core` for use
# with examples from the CDK Developer's Guide, which are in the process of
# being updated to ... | app.py | 1,436 | !/usr/bin/env python3 For consistency with TypeScript code, `cdk` is the preferred import name for the CDK's core module. The following line also imports it as `core` for use with examples from the CDK Developer's Guide, which are in the process of being updated to use `cdk`. You may delete this import if you don't n... | 1,017 | en | 0.825708 |
#
# Copyright(c) 2019-2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
import logging
from tests import conftest
from core.test_run import TestRun
from api.cas import git
from api.cas import cas_module
from test_utils import os_utils
from test_utils.output import CmdException
def rsync_opencas_sour... | test/functional/api/cas/installer.py | 2,887 | Copyright(c) 2019-2021 Intel Corporation SPDX-License-Identifier: BSD-3-Clause | 78 | en | 0.288062 |
#
# Pyserini: Reproducible IR research with sparse and dense representations
#
# 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... | pyserini/hsearch/__main__.py | 8,453 | Pyserini: Reproducible IR research with sparse and dense representations Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law o... | 1,078 | en | 0.765018 |
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from sentry.models import GroupTagValue, TagKey, TagValue
from sentry.testutils import TestCase
class GroupTagExportTest(TestCase):
def test_simple(self):
key, value = 'foo', 'bar'
# Drop mic... | tests/sentry/web/frontend/test_group_tag_export.py | 1,877 | Drop microsecond value for MySQL | 32 | en | 0.571744 |
ifconfig -a | grep PROMISC
cat /var/log/messages |grep promisc
1 #!/usr/bin/python 2 3 import sys 4 from scapy.all import promiscping 5 6 if len(sys.argv) < 2: 7 print sys.argv[0] + " <net>" 8 sys.exit() 9 10 promiscping(sys.argv[1]) | 05_tcp_ip_tricks/Sniffer Detection.py | 237 | !/usr/bin/python 2 3 import sys 4 from scapy.all import promiscping 5 6 if len(sys.argv) < 2: 7 print sys.argv[0] + " <net>" 8 sys.exit() 9 10 promiscping(sys.argv[1]) | 167 | en | 0.170636 |
# -*- coding: utf-8 -*-
from functools import cache
INPUT = 33100000
def sigma_pentagonal_numbers(limit):
"""
>>> list(sigma_pentagonal_numbers(16))
[1, 2, 5, 7, 12, 15]
"""
n = 1
p = 1
while p <= limit:
yield p
if n > 0:
n = -n
else:
n... | advent/year2015/day20.py | 2,091 | # Takes too long so commented out
# >>> part1(INPUT)
# 776160
>>> part2(INPUT)
786240
https://math.stackexchange.com/a/22744
>>> presents_for_house(1)
10
>>> presents_for_house(2)
30
>>> presents_for_house(3)
40
>>> presents_for_house(8)
150
>>> presents_for_house(9)
130
>>> list(sigma_pentagonal_numbers(16))
[1, 2, 5... | 356 | en | 0.689199 |
import datetime
import functools
import os
import subprocess
def get_version(version=None):
"""Return a PEP 440-compliant version number from VERSION."""
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha release... | django-src/utils/version.py | 2,393 | Return a tuple of the django version. If version argument is non-empty,
check for correctness of the tuple provided.
Return a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unli... | 644 | en | 0.78733 |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
###########################################################################
#
# Copyright (c) 2018 www.codingchen.com, Inc. All Rights Reserved
#
##########################################################################
'''
@brief leetcode algorithm
@author chenhui(hui.ch... | 4+Median+of+Two+Sorted+Arrays/alg.py | 1,429 | :type nums1: List[int]
:type nums2: List[int]
:rtype: float
@brief leetcode algorithm
@author chenhui(hui.chen6789@gmail.com)
@date 2018/11/07 21:30:33
!/usr/bin/env python-*- coding: UTF-8 -*- Copyright (c) 2018 www.codingchen.com, Inc. All Rights Reserved | 258 | en | 0.351762 |
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
# 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... | nova/console/vmrc.py | 4,588 | VMRC console driver with ESX credentials.
VMRC console driver with VMRC One Time Sessions.
Encode password.
Returns VMRC Connection credentials.
Return string is of the form '<VM PATH>:<ESX Username>@<ESX Password>'.
Returns a VMRC Session.
Return string is of the form '<VM MOID>:<VMRC Ticket>'.
Get available port fo... | 1,145 | en | 0.81166 |
# Copyright 2017 ZTE 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 applicable law or agreed to in ... | res/manage.py | 804 | Copyright 2017 ZTE 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 applicable law or agreed to in writing, software ... | 557 | en | 0.86807 |
#
# Copyright (c) 2017 Intel Corporation
# SPDX-License-Identifier: BSD-2-Clause
#
import numba
import numpy as np
import argparse
import time
@numba.njit()
def linear_regression(Y, X, w, iterations, alphaN):
for i in range(iterations):
w -= alphaN * np.dot(X.T, np.dot(X,w)-Y)
return w
def main():
... | examples/linear_regression/linear_regression_numba.py | 1,200 | Copyright (c) 2017 Intel Corporation SPDX-License-Identifier: BSD-2-Clause | 74 | en | 0.441239 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | docs/source/conf.py | 6,878 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions ... | 4,791 | en | 0.615538 |
# coding: utf-8
"""
ProcessMaker API
This ProcessMaker I/O API provides access to a BPMN 2.0 compliant workflow engine api that is designed to be used as a microservice to support enterprise cloud applications. The current Alpha 1.0 version supports most of the descriptive class of the BPMN 2.0 specification... | test/test_input_output.py | 1,599 | InputOutput unit test stubs
Test InputOutput
ProcessMaker API
This ProcessMaker I/O API provides access to a BPMN 2.0 compliant workflow engine api that is designed to be used as a microservice to support enterprise cloud applications. The current Alpha 1.0 version supports most of the descriptive class of the BPMN ... | 1,006 | en | 0.844335 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/contrib/distribute/python/keras_test.py | 48,363 | Generates the inputs for correctness check when enable Keras with DS.
Tests for tf.keras models using DistributionStrategy.
Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You m... | 5,624 | en | 0.84422 |
#!/bin/python
# -*- coding: utf-8 -*-
# import numpy as np
# define additional functions used in the *.yaml.
# Of course, as this is a trivial function you could have defined it in the *.yaml directly
def calc_nu(nub):
nu = nub / (1 - nub)
return nu
| pydsge/examples/dfi_funcs.py | 262 | !/bin/python -*- coding: utf-8 -*- import numpy as np define additional functions used in the *.yaml. Of course, as this is a trivial function you could have defined it in the *.yaml directly | 191 | en | 0.927263 |
#!/usr/bin/env python3
# Copyright 2018 Johns Hopkins University (author: Daniel Povey)
# Apache 2.0.
# see get_args() below for usage message.
import argparse
import os
import sys
import math
import re
# The use of latin-1 encoding does not preclude reading utf-8. latin-1
# encoding means "treat words as sequen... | egs/wsj/s5/utils/lang/make_lexicon_fst.py | 19,129 | Returns true if s is a string and is space-free.
Reads, checks, and returns a list of left-context phones, in text form, one
per line. Returns a list of strings, e.g. ['a', 'ah', ..., '#nonterm_bos' ]
Reads the lexiconp.txt file in 'filename', with lines like 'word pron p1 p2 ...'.
Returns a list of tuples (word, pro... | 5,183 | en | 0.823022 |
# Copyright 2020 by Federico Caselli
#
# 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 wr... | falcon/inspect.py | 26,938 | Describes an application.
Args:
routes (List[RouteInfo]): The routes of the application.
middleware (MiddlewareInfo): The middleware information in the application.
static_routes (List[StaticRouteInfo]): The static routes of this application.
sinks (List[SinkInfo]): The sinks of this application.
e... | 9,742 | en | 0.735536 |
# -*- coding: utf-8 -*-
# Copyright 2019 Spotify AB. 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... | tests/storage_test.py | 13,916 | -*- coding: utf-8 -*- Copyright 2019 Spotify AB. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a... | 988 | en | 0.822118 |
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... | data/crop_and_pad_augmentations.py | 7,604 | crops data and seg (seg may be None) to crop_size. Whether this will be achieved via center or random crop is
determined by crop_type. Margin will be respected only for random_crop and will prevent the crops form being closer
than margin to the respective image border. crop_size can be larger than data_shape - margin -... | 2,409 | en | 0.819769 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | synth.py | 1,217 | This script is used to synthesize generated parts of this library.
Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless re... | 662 | en | 0.859913 |
# Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
# Splitting the dataset into the Training set and Test set
from sklear... | Part 2 - Regression/Section 4 - Simple Linear Regression/data_preprocessing_template.py | 684 | Data Preprocessing Template Importing the libraries Importing the dataset Splitting the dataset into the Training set and Test set Feature Scaling | 146 | en | 0.703396 |
import serial
import pynmea2
# Probando con el pincho usb azul
ser = serial.Serial('/dev/ttyUSB0',4800)
while 1:
try:
data = ser.readline().decode('utf-8')
if(data.startswith("$GPGGA")):
parse = pynmea2.parse(data)
print(repr(parse))
except UnicodeDecodeError:
c... | CTD_controller/gps_test1.py | 327 | Probando con el pincho usb azul | 31 | es | 0.863485 |
####################################################################################################
"""
adres_dataset.py
This module implements several classes to perform dataset-specific downloading, saving and
data-transformation operations.
Written by Swaan Dekkers & Thomas Jongstra
"""
##########################... | codebase/datasets/adres_dataset.py | 13,802 | Create a dataset for the adres data.
Add the hotline features to the adres dataframe.
Enrich the adres data with information from the BAG data. Uses the bag dataframe as input.
Add aggregated features relating to persons to the address dataframe. Uses the personen dataframe as input.
Add woning ids to the adres datafra... | 3,108 | en | 0.652637 |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | ws2122-lspm/Lib/site-packages/pm4py/visualization/decisiontree/__init__.py | 784 | This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PM4Py is dis... | 665 | en | 0.922242 |
from __future__ import division
from keras.callbacks import Callback
from .generic_plot import PlotLosses
metric2printable = {
"acc": "Accuracy",
"mean_squared_error": "Mean squared error",
"mean_absolute_error": "Mean absolute error",
"mean_absolute_percentage_error": "Mean absolute percentage error"... | livelossplot/keras_plot.py | 2,530 | etc if passed as a function if passed as a string slightly convolved due to model.complie(loss=...) stuff vide https://github.com/keras-team/keras/blob/master/keras/engine/training.py by far the most common scenario | 215 | en | 0.833561 |
import numpy as np
from .tensor import Function
# ************* unary ops *************
class ReLU(Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return np.maximum(input, 0)
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tens... | tinygrad/ops_cpu.py | 8,145 | ************* unary ops ************* ************* reduce ops ************* ************* binary ops ************* adjoint operation to broadcast is sum. Need to sum all axis with 1 = in_sh[i] < out.shape[i] ************* movement ops ************* ************* processing ops ************* ijYXyx,kjyx -> iYXk ->ikYX ... | 446 | en | 0.611234 |
import numpy as np
import tensorflow as tf
# ----------------------------------------------------------------------------
def SubPixel1D_v2(I, r):
"""One-dimensional subpixel upsampling layer
Based on https://github.com/Tetrachrome/subpixel/blob/master/subpixel.py
"""
with tf.compat.v1.name_scope('subpixel')... | src/models/layers/subpixel.py | 2,930 | One-dimensional subpixel upsampling layer
Calls a tensorflow function that directly implements this functionality.
We assume input has dim (batch, width, r)
One-dimensional subpixel upsampling layer
Calls a tensorflow function that directly implements this functionality.
We assume input has dim (batch, width, r).
Wo... | 792 | en | 0.558592 |
import logging
import boto3
from botocore.vendored.requests.packages.urllib3.exceptions import ResponseError
from django.core.mail.backends.base import BaseEmailBackend
from django_ses import settings
from datetime import datetime, timedelta
from time import sleep
try:
import importlib.metadata as importlib_met... | django_ses/__init__.py | 11,494 | A Django Email backend that uses Amazon's Simple Email Service.
Cast nonzero number to float; on zero or None, return None
Close any open HTTP connections to the API server.
Return signed email message if dkim package and settings are available.
Create a connection to the AWS API server. This can be reuse... | 2,269 | en | 0.853602 |
# -*- coding=UTF-8 -*-
# pyright: strict
from __future__ import annotations
import os
import sys
import subprocess
def main():
subprocess.call(
["npx", "pyright"],
env={
**os.environ,
"PATH": os.path.pathsep.join(
(
os.path.dirname(sy... | scripts/run_pyright.py | 490 | -*- coding=UTF-8 -*- pyright: strict | 36 | en | 0.683297 |
#!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013-2014 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from __future__ import pri... | contrib/linearize/linearize-hashes.py | 3,037 | !/usr/bin/python linearize-hashes.py: List blocks in a linear, no-fork version of the chain. Copyright (c) 2013-2014 The Bitcoin developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. assume replies are in-sequence skip commen... | 349 | en | 0.711358 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | src/azure-cli/azure/cli/__init__.py | 618 | The Azure Command-line tool.
This tools provides a command-line interface to Azure's management and storage
APIs.
-------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in t... | 453 | en | 0.505296 |
#!/usr/bin/python
import os
import unittest
""" Script to run the Python tests. """
def run_python_tests():
""" Runs the Python tests.
Returns:
True if the tests all succeed, False if there are failures. """
print("Starting tests...")
loader = unittest.TestLoader()
# Get the directory this module i... | run_tests.py | 636 | Runs the Python tests.
Returns:
True if the tests all succeed, False if there are failures.
!/usr/bin/python Get the directory this module is in. | 149 | en | 0.611513 |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | aiida/storage/psql_dos/migrations/versions/django_0009_base_data_plugin_type_string.py | 2,275 | Migrations for the downgrade.
Migrations for the upgrade.
Change `db_dbnode.type` for base `Data` types.
The base Data types Bool, Float, Int and Str have been moved in the source code, which means that their
module path changes, which determines the plugin type string which is stored in the databse.
The type string n... | 934 | en | 0.876987 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualMachineRuntimeInfo(vim, *args, **kwargs):
'''The RuntimeInfo data object type ... | pyvisdk/do/virtual_machine_runtime_info.py | 1,456 | The RuntimeInfo data object type provides information about the execution state
and history of a virtual machine.
Automatically generated, do not edit. do some validation checking... | 184 | en | 0.600621 |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add non-adjusted next cycle start date
Revision ID: 44047daa31a9
Revises: 1431e7094e26
Create Date: 2015-07-07 14:31:27.780564
"""
# revision identifiers, used by Alembic.
revision = '44047daa31a9'
dow... | src/ggrc_workflows/migrations/versions/20150707143127_44047daa31a9_add_non_adjusted_next_cycle_start_date.py | 6,752 | Add non-adjusted next cycle start date
Revision ID: 44047daa31a9
Revises: 1431e7094e26
Create Date: 2015-07-07 14:31:27.780564
Copyright (C) 2017 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> revision identifiers, used by Alembic. If somebody deleted all the tasks we must c... | 422 | en | 0.757924 |
A = 'A'
B = 'B'
Environment = {
A: 'Dirty',
B: 'Dirty',
'Current': A
}
def REFLEX_VACUUM_AGENT(loc_st): # Determine action
if loc_st[1] == 'Dirty':
return 'Suck'
if loc_st[0] == A:
return 'Right'
if loc_st[0] == B:
return 'Left'
def Sensors(): # Sense Environment
... | Lecture_3_Agents/Exercise1/Exercises/reflex_vacuum_agent.py | 1,302 | Determine action Sense Environment Modify Environment run the agent through n steps Sense Environment before action Sense Environment after action | 146 | en | 0.755196 |
def average_rating(rating_list):
if not rating_list:
# if rating_list is empty return 0
return 0
return round(sum(rating_list) / len(rating_list)) | bookr/reviews/utils.py | 172 | if rating_list is empty return 0 | 32 | en | 0.604533 |
import asyncio
import copy
import random
from typing import Callable
import pytest
from starkware.starknet.apps.starkgate.cairo.contracts import erc20_contract_def
from starkware.starknet.apps.starkgate.conftest import str_to_felt
from starkware.starknet.testing.contract import StarknetContract
from starkware.starkne... | src/starkware/starknet/apps/starkgate/cairo/token_test.py | 21,056 | Not initialized_account and not uninitialized_account. 0 < TRANSFER_AMOUNT < APPROVE_AMOUNT < initial_balance < HIGH_APPROVE_AMOUNT. Tests the case of sender = recipient. The contract fails when checking for sufficient allowance of account 0. Only because we cannot put a balance for address(0) or approve on its behalf.... | 411 | en | 0.906517 |
# 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 ... | src/virtual-network-tap/azext_vnettap/vendored_sdks/v2018_08_01/models/subnet_association.py | 1,302 | Network interface and its custom security rules.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Subnet ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules:
list[~azure.mgmt.network.v2018_08_01.models.SecurityRule]
... | 772 | en | 0.639006 |
from flask import render_template, url_for, request, flash, redirect, make_response
import email
from app import app
from werkzeug.utils import secure_filename
from app.predict_email import Prediction
import tempfile
predict_email = Prediction()
def parse_email(email_raw):
parser = email.parser.BytesParser()
... | app/routes.py | 3,055 | email_parsed = parse_email(email_raw) print(email["subject"]) Features = prepData(textData) prediction = int((np.asscalar(loaded_model.predict(Features))) * 100) @app.route("/predict", methods=["POST"]) def predict(): df = pd.read_csv("spam.csv", encoding="latin-1") df.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed... | 1,339 | en | 0.446009 |
class ParticleData(object):
""" Class for holding particle data such as charge.
"""
def __init__(self, charge=0):
self.charge=charge
def __repr__(self):
return "charge="+str(self.charge)
class ParticleDataList(object):
""" Class for generic handling particle ids, names and ... | FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py | 8,799 | Class for holding particle data such as charge.
Class for generic handling particle ids, names and properties.
Multiple ids can be mapped to multiple names of particle.
First name/id in the list is the default name. But additional names/ids can be given.
An examples can be found in the defaultParticleDataList.
A ... | 777 | en | 0.792197 |
import torch
from torch import nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import random
import numpy as np
import scipy as sp
import gurobipy as gp
from qpthlocal.qp import QPFunction
from qpthlocal.qp import QPSolvers
from qpthlocal.qp import make_gurobi_model
import... | shortespath/shortespath.py | 19,575 | from ip_model import * remove redundant (linearly dependent) rows from equality constraints if (sps.issparse(A_eq)): if rr and A_eq.size > 0: TODO: Fast sparse rank check? A_eq, b_eq, status, message = _remove_redundancy_sparse(A_eq, b_eq) if A_eq.shape[0] < n_rows_A: warn(redundancy_w... | 2,022 | en | 0.41191 |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Divi Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the zapwallettxes functionality.
- start two divid nodes
- create two transactions on node 0 - one i... | test/functional/wallet_zapwallettxes.py | 3,395 | Test the zapwallettxes functionality.
- start two divid nodes
- create two transactions on node 0 - one is confirmed and one is unconfirmed.
- restart node 0 and verify that both the confirmed and the unconfirmed
transactions are still available.
- restart node 0 with zapwallettxes and persistmempool, and verify tha... | 1,440 | en | 0.875002 |
"""
Filename: RobotsParser.py
Author: Maxwell Goldberg
Last modified: 06.09.17
Description: Helper class for parsing individual robots.txt records.
"""
# CONSTANTS
from constants import RECORD_MAX_LEN
# PYTHON BUILTINS
import re, unicodedata, logging
def test_ctrl_chars(s):
return len(s) != len("".join(ch for ch in ... | crawler/lib/RobotsParser.py | 1,742 | Filename: RobotsParser.py
Author: Maxwell Goldberg
Last modified: 06.09.17
Description: Helper class for parsing individual robots.txt records.
CONSTANTS PYTHON BUILTINS Get path length prior to parsing Attempt to separate a record by a colon delimiter. Parse the field Parse the path | 286 | en | 0.742863 |
# -*- coding: utf-8 -*-
# @Time : 2019/5/11 15:12
# @Author : LegenDong
# @User : legendong
# @File : __init__.py.py
# @Software: PyCharm
from .channel_attention_layer import *
from .nan_attention_layer import *
| models/layer/__init__.py | 223 | -*- coding: utf-8 -*- @Time : 2019/5/11 15:12 @Author : LegenDong @User : legendong @File : __init__.py.py @Software: PyCharm | 135 | en | 0.206452 |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import src.proto.predict_pb2 as predict__pb2
class PredictionServiceStub(object):
"""Missing associated documentation comment in .proto file."""
def __... | chapter2_training/cifar10/evaluate/src/proto/prediction_service_pb2_grpc.py | 2,523 | Missing associated documentation comment in .proto file.
Missing associated documentation comment in .proto file.
Missing associated documentation comment in .proto file.
Missing associated documentation comment in .proto file.
Constructor.
Args:
channel: A grpc.Channel.
Client and server classes corresponding to ... | 459 | en | 0.664279 |
#Importing Libraries
import os
import csv
import sys, getopt
import uuid
import SimpleITK as sitk
import cv2
import numpy as np
import tensorflow as tf
from flask import Flask, flash, request, redirect, render_template
from flask import jsonify
from flask import send_from_directory
from flask_materialize import Mat... | detection.py | 14,114 | Importing Libraries image = normalise_one_one(image, -250, 250) Read arguments Initialize parser Reading the input arguments Read arguments from command line Creating the result structure variablesLoad the sarcopenia-ai models set_session(sess)Updated functions to replace older versions listed in the sarcopenia-ai... | 1,297 | en | 0.719551 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py | 5,460 | Test the __init__ method.
Test string representation of plugin.
Test the _rescale_shape_parameters
Set up values for testing.
Test specifying a distribution other than truncated normal. In
this instance, no rescaling is applied.
Test string representation
Test scaling discrete shape parameters.
Test for an invalid dist... | 2,232 | en | 0.805121 |
"""
Item class for Jaseci
Each item has an id, name, timestamp.
"""
from jaseci.element.element import element
class item(element):
"""Item class for Jaseci"""
def __init__(self, value=None, *args, **kwargs):
self.item_value = value
super().__init__(*args, **kwargs)
@property
def va... | jaseci_core/jaseci/attr/item.py | 621 | Item class for Jaseci
Item class for Jaseci
Each item has an id, name, timestamp. | 82 | en | 0.695268 |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Hang Zhang
## Email: zhanghang0704@gmail.com
## Copyright (c) 2020
##
## LICENSE file in the root directory of this source tree
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import os
import time
i... | train.py | 16,174 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Created by: Hang Zhang Email: zhanghang0704@gmail.com Copyright (c) 2020 LICENSE file in the root directory of this source tree +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ data settings model params parser.add_argume... | 878 | en | 0.467402 |
"""
Implements harmonic_mean() function.
"""
from .mean import mean
def harmonic_mean(x):
"""
The `harmonic mean`_ is a kind of average that is calculated as
the reciprocal_ of the arithmetic mean of the reciprocals.
It is appropriate when calculating averages of rates_.
.. _`harmonic mean`: http... | simplestatistics/statistics/harmonic_mean.py | 1,337 | The `harmonic mean`_ is a kind of average that is calculated as
the reciprocal_ of the arithmetic mean of the reciprocals.
It is appropriate when calculating averages of rates_.
.. _`harmonic mean`: https://en.wikipedia.org/wiki/Harmonic_mean
.. _reciprocal: https://en.wikipedia.org/wiki/Multiplicative_inverse
.. _rat... | 968 | en | 0.742695 |
# Copyright 2020 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.txt" file acc... | tests/integration-tests/tests/tags/test_tag_propagation.py | 7,586 | Convert dicts of the form {key: value} to a list like [{"Key": key, "Value": value}].
Return the tags for the CFN stack with the given name
The returned values is a list like the following:
[
{'Key': 'Key2', 'Value': 'Value2'},
{'Key': 'Key1', 'Value': 'Value1'},
]
Return the given cluster's compute node's roo... | 1,774 | en | 0.750792 |
import torch
import random
import numpy as np
class InfiniteDataLoader(torch.utils.data.DataLoader):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dataset_iterator = super().__iter__()
def __iter__(self):
return self
def __next__(self):
... | commons.py | 3,395 | Make results deterministic. If seed == -1, do not make deterministic.
Running your script in a deterministic way might slow it down.
Note that for some packages (eg: sklearn's PCA) this function is not enough.
Set up logging files and console output.
Creates one file for INFO logs and one for DEBUG logs.
Args:
outp... | 872 | en | 0.75426 |
from bedlam import Game
from bedlam import Scene
from bedlam import Sprite
from balls import Ball
# __pragma__('skip')
document = window = Math = Date = console = 0 # Prevent complaints by optional static checker
# __pragma__('noskip')
# __pragma__('noalias', 'clear')
DEBUG = False
class PVector:
def __init__... | boids.py | 8,899 | __pragma__('skip') Prevent complaints by optional static checker __pragma__('noskip') __pragma__('noalias', 'clear') | 116 | en | 0.299979 |
# -*- coding: utf-8 -*-
from pandas import DataFrame
from pandas_ta.utils import get_offset, verify_series
def donchian(high, low, lower_length=None, upper_length=None, offset=None, **kwargs):
"""Indicator: Donchian Channels (DC)"""
# Validate arguments
high = verify_series(high)
low = verify_series(l... | pandas_ta/volatility/donchian.py | 2,935 | Indicator: Donchian Channels (DC)
-*- coding: utf-8 -*- Validate arguments Calculate Result Handle fills Offset Name and Categorize it Prepare DataFrame to return | 164 | en | 0.391952 |
import unittest
from unittest.mock import Mock
# PyATS
from pyats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError, \
SchemaMissingKeyError
from genie.libs.parser.asa.show_vpn import ShowVPNLoadBalancing
# ============================... | src/genie/libs/parser/asa/tests/test_show_vpn.py | 4,072 | unit test for show vpn load-balancing
PyATS ============================================ unit test for 'show vpn load-balancing' ============================================= | 176 | en | 0.427064 |
# <editor-fold desc="Basic Imports">
import os
import os.path as p
import requests
from time import time
from argparse import ArgumentParser
import sys
sys.path.append(p.join(p.dirname(__file__), '..'))
sys.path.append(p.join(p.dirname(__file__), '../..'))
# </editor-fold>
# <editor-fold desc="Parse Command Line Args... | py_scripts/preprocessing/prep_shard.py | 7,924 | <editor-fold desc="Basic Imports"> </editor-fold> <editor-fold desc="Parse Command Line Args"> </editor-fold> Suppress TF logging Init Track progress Preprocesses one news.jl per call Check File Content Preprocess Vectorize Make faiss subindex Clear graph Restart TF session if necessary Merge TODO: Title indexes Record... | 363 | en | 0.417188 |
from __future__ import print_function, absolute_import, division
import argparse
import os
import zipfile
import tarfile
import numpy as np
import h5py
from glob import glob
from shutil import rmtree
import sys
sys.path.append('../')
from common.h36m_dataset import H36M_NAMES
output_filename_pt = 'data_2d_h36m_sh_... | data/prepare_data_2d_h36m_sh.py | 4,384 | Stacked Hourglass produces 16 joints. These are the names. Permutation that goes from SH detections to H36M ordering. Discard corrupted video positions = hf['poses'].value | 182 | en | 0.865426 |
# -*- coding: utf-8 -*-
# pylint: disable=C,R,W
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import sqlparse
from sqlparse.sql import Identifier, IdentifierList
from sqlparse.tokens import Keyword, N... | superset/sql_parse.py | 4,910 | Reformats the query into the create table as query.
Works only for the single select SQL statements, in all other cases
the sql query is not modified.
:param superset_query: string, sql query that will be executed
:param table_name: string, will contain the results of the
query execution
:param overwrite, boolean,... | 824 | en | 0.705335 |
import dynet as dy
import time
import random
LAYERS = 2
INPUT_DIM = 256 #50 #256
HIDDEN_DIM = 256 # 50 #1024
VOCAB_SIZE = 0
from collections import defaultdict
from itertools import count
import argparse
import sys
import util
class RNNLanguageModel:
def __init__(self, model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOC... | examples/rnnlm/rnnlm.py | 4,542 | 50 256 50 1024 will hold expressions assume word is already a word-id assume word is already a word-idlm = RNNLanguageModel(model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=dy.SimpleRNNBuilder)print "TM:",(time.time() - _start)/len(sent) | 248 | en | 0.551469 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from mcts.webapi_tests.fm_radio.fm_radio_test import FMRadioTestCommon
from mcts.webapi_tests.fm_radio.test_fm_radio_bas... | mcts/webapi_tests/fm_radio/__init__.py | 347 | This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. | 192 | en | 0.934305 |
"""Views of problem2 app."""
from django.shortcuts import render
from .forms import FiboForm
def display(request):
"""Function view to display form in the standard manner."""
if request.method == 'POST':
form = FiboForm(request.POST)
if form.is_valid():
fibo = form.save(commit=Fa... | problem2/views.py | 620 | Function view to display form in the standard manner.
Views of problem2 app. | 76 | en | 0.7785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.