content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
from types import BeaverException, Variable, Collection, EmptyCollection, updated_context
from copy import deepcopy as copy
class Statement(object):
'''A generic statement containing any number of variable parts.'''
def __init__(self, subject, verb_objects):
self.subject = subject
self.verb_ob... | lib/statement.py | 2,998 | A generic statement containing any number of variable parts.
Returns true if a given argument matches the definition.
Checks each part of the statement against defined variables. If any
matches are found, the statement is updated. If the statement is a function
call, a new set of statements is returned; otherwise, None... | 435 | en | 0.851862 |
import copy
import numpy as np
import torch
from mmpose.core import (aggregate_results, get_group_preds,
get_multi_stage_outputs)
def test_get_multi_stage_outputs():
fake_outputs = [torch.zeros((1, 4, 2, 2))]
fake_flip_outputs = [torch.ones((1, 4, 2, 2))]
# outputs_f... | tests/test_evaluation/test_bottom_up_eval.py | 6,525 | outputs_flip with heatmaps & with ae size_projected | 51 | en | 0.902308 |
import typing
from typing import List
from quarkchain.core import (
CrossShardTransactionList,
MinorBlock,
MinorBlockHeader,
RootBlock,
TransactionReceipt,
Log,
FixedSizeBytesSerializer,
biguint,
Constant,
)
from quarkchain.core import (
TypedTransaction,
Optional,
Prepe... | quarkchain/cluster/rpc.py | 36,516 | Notify master about a list of successfully added minor block.
Mostly used for minor block sync triggered by root block sync
Notify master about a successfully added minor block.
Piggyback the ShardStats in the same request.
For adding blocks mined through JRPC
Add root block to each slave
For adding blocks mined t... | 1,500 | en | 0.878613 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import marshal
from math import log, exp
from ..utils.frequency import AddOneProb
class Bayes(object):
def __init__(self):
self.d = {}
self.total = 0
def save(self, fname):
d = {}
d['total'] = self.t... | snownlp/classification/bayes.py | 1,621 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# -*- coding: utf-8 -*-
# (C) 2015 Muthiah Annamalai
# setup the paths
from opentamiltests import *
from solthiruthi.data_parser import *
from solthiruthi.solthiruthi import Solthiruthi
import sys
class CmdLineIO(unittest.TestCase):
def test_CLI_interface_help(self):
return
# find a way to run th... | tests/solthiruthi_data_parser.py | 1,780 | -*- coding: utf-8 -*- (C) 2015 Muthiah Annamalai setup the paths find a way to run this test which exits the suite self.assertEqual(r['total'],141) | 147 | en | 0.751123 |
# Copyright 2015 OpenStack Foundation
# 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 requ... | nova/conf/wsgi.py | 3,577 | Copyright 2015 OpenStack Foundation 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 l... | 606 | en | 0.869052 |
import math
from pyvolution.EvolutionManager import *
from pyvolution.GeneLibrary import *
"""
This example attempts to find a solution to the following system of equations:
a + b + c + d - 17 = 0
a^2 + b^2 - 5 = 0
sin(a) + c - d - 20 = 0
"""
def fitnessFunction(chromosome):
"""
Given a "chromosome", this ... | examples/EquationSolver_simple.py | 2,566 | Given a "chromosome", this function must determine its fitness score
The fitness score should be a floating point value. If the fitness is zero or smaller
then the chromosome will not be allowed to "reproduce"
you can access the attributes of a chromosome using square bracketsthe key is the description of the genef... | 1,188 | en | 0.813346 |
import json
import argparse
from time import sleep
import psycopg2
import subprocess
import os
import signal
def connTemp(puser, phost, pport, stmt):
conn = psycopg2.connect(database = 'postgres', user = puser, host = phost, port = pport)
conn.autocommit = True
cur = conn.cursor()
cur.execute(stmt)
... | person/charles/PGX/pgx_install.py | 18,308 | res = cur.fetchall()print(ahost) create env file scp package & env file to each instance ====================== -------------------------- gtm ------------------------------------- init gtm master node ================================== change gtm configuration =================================== start gtm ============... | 1,933 | en | 0.29501 |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 07 2016
@author: Matthew Carse
"""
#@ Class containing methods for machine learning.
#@ Chromosomes must be preprocessed through feature scaling standardisation prior to being
#@ used in machine learning. The class implements Scikit-learn to apply feature scaling... | machineLearning.py | 16,607 | -*- coding: utf-8 -*-@ Class containing methods for machine learning.@ Chromosomes must be preprocessed through feature scaling standardisation prior to being @ used in machine learning. The class implements Scikit-learn to apply feature scaling to the@ training chromosomes. The scaling factors are retained for use wit... | 5,127 | en | 0.783423 |
"""
In this exercise you are going to apply what you learned about stacks with a real world problem.
We will be using stacks to make sure the parentheses are balanced in mathematical expressions such as:
((3^2 + 8)*(5/2))/(2+6)
In real life you can see this extend to many things such as text editor plugins
and... | 3. data_structures/stack/balanced_parantheses.py | 1,781 | Check equation for balanced parentheses
Check equation for balanced parentheses
Args:
equation(string): String form of equation
Returns:
bool: Return if parentheses are balanced or not
In this exercise you are going to apply what you learned about stacks with a real world problem.
We will be using stacks to ma... | 718 | en | 0.859393 |
import os
import re
import uuid
import typing as t
import logging
import pathlib
import functools
from typing import TYPE_CHECKING
from distutils.dir_util import copy_tree
from simple_di import inject
from simple_di import Provide
import bentoml
from bentoml import Tag
from bentoml.exceptions import BentoMLException
... | bentoml/_internal/frameworks/tensorflow_v2.py | 20,533 | Import a model from `Tensorflow Hub <https://tfhub.dev/>`_ to BentoML modelstore.
Args:
identifier (:code:`Union[str, tensorflow_hub.Module, tensorflow_hub.KerasLayer]`): Identifier accepts
two type of inputs:
- if `type` of :code:`identifier` either of type :code:`tensorflow_hub.Module` (**leg... | 8,312 | en | 0.50811 |
"""
Django settings for modelos project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
#... | src/modelos/settings.py | 3,207 | Django settings for modelos project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
Build paths inside ... | 1,002 | en | 0.627144 |
"""nflDAs URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... | nflDAs/nflDAs/urls.py | 748 | nflDAs URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | 622 | en | 0.624706 |
from spn.structure.Base import Product, Sum, get_nodes_by_type
from spn.structure.leaves.cltree.CLTree import CLTree
from spn.algorithms.Validity import is_consistent
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.sparse.csgraph import depth_first_order
from error import RootVarError
import numpy ... | utils.py | 10,747 | used to model a dependency tree
used to model a Vtree
for fast np dot to avoid normalization errors (weights of sum nodes have to sum up to 1) create a dependency tree for each scope in scopes concatenate dtrees return a dictionary of dtrees where keys are scope lengths ordering is not needed, but useful for printi... | 389 | en | 0.856603 |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | official/cv/brdnet/preprocess.py | 2,411 | Copyright 2021 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw... | 800 | fr | 0.283949 |
from __future__ import absolute_import
# Copyright (c) 2010-2019 openpyxl
import pytest
from io import BytesIO
from zipfile import ZipFile
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
from ..manifest import WORKSHEET_TYPE
@pytest.fixture
def FileExtension():
... | openpyxl/packaging/tests/test_manifest.py | 9,812 | LibreOffice does not use the Default element
Copyright (c) 2010-2019 openpyxl | 79 | en | 0.465622 |
import asyncio
import logging
import ssl
import time
import traceback
from ipaddress import IPv6Address, ip_address, ip_network, IPv4Network, IPv6Network
from pathlib import Path
from secrets import token_bytes
from typing import Any, Callable, Dict, List, Optional, Union, Set, Tuple
from aiohttp import ClientSession,... | greenberry/server/server.py | 32,187 | If node has public cert use that one for id, if not use private.
Keeps track of all connections to and from this node. TCP port to identify our node Task list to keep references to tasks, so they don't get GCd Our unique random node id that we will send to other peers, regenerated on launch Also garbage collect banne... | 815 | en | 0.931976 |
# Copyright 2019-2020 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... | causalnex/structure/pytorch/notears.py | 13,168 | Learn the `StructureModel`, the graph structure with lasso regularisation
describing conditional dependencies between variables in data presented as a numpy array.
Based on DAGs with NO TEARS.
@inproceedings{zheng2018dags,
author = {Zheng, Xun and Aragam, Bryon and Ravikumar, Pradeep and Xing, Eric P.},
bookti... | 6,936 | en | 0.779083 |
import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... | Tensorflow_LightGBM_Scipy_nightly/source/markdown/treeprocessors.py | 12,649 | A Treeprocessor that traverses a tree, applying inline patterns.
Add linebreaks to the html document.
Treeprocessors are run on the ElementTree object before serialization.
Each Treeprocessor implements a "run" method that takes a pointer to an
ElementTree, modifies it as necessary and returns an ElementTree
object.
... | 2,854 | en | 0.753993 |
from selenium import webdriver
import time
url = "http://localhost/litecart/admin/"
browser = webdriver.Chrome()
browser.implicitly_wait(1)
without_title = 0
try:
browser.get(url)
# логинемся
login = browser.find_element_by_css_selector("[name='username']")
login.send_keys("admin")
password = ... | selenium/find_elements/app_main_menu.py | 1,780 | логинемся без этого слипа программа перестает работать, очень хотелось бы обсудить этот момент читаем основное меню читаем подменю условие для пунктов меню, в которых отсутствует подменю | 186 | ru | 0.999324 |
"""
Considerando duas listas de inteiros ou floats (lista A e lista B)
Some os valores nas listas retornando uma nova lista com os valores somados:
Se uma lista for maior que a outra, a soma só vai considerar o tamanho da
menor.
Exemplo:
lista_a = [1, 2, 3, 4, 5, 6, 7]
lista_b = [1, 2, 3, 4]
===================... | aulaspythonintermediario/exercicios06/exercicio01.py | 498 | Considerando duas listas de inteiros ou floats (lista A e lista B)
Some os valores nas listas retornando uma nova lista com os valores somados:
Se uma lista for maior que a outra, a soma só vai considerar o tamanho da
menor.
Exemplo:
lista_a = [1, 2, 3, 4, 5, 6, 7]
lista_b = [1, 2, 3, 4]
=================== res... | 353 | pt | 0.944817 |
import functools
from teamiclink.slack.model import GoalContent
from typing import Any, Dict
from slack_bolt import Ack
from slack_bolt.context import BoltContext
from pydantic import ValidationError
CREATE_GOAL_CALLBACK_ID = "create_goal_view_id"
CREATE_GOAL_INPUT = "create_goal_action"
CREATE_GOAL_INPUT_BLOCK = "cr... | teamiclink/slack/view_goal_create.py | 1,608 | Adds a goal to payload for 't-goal' key. | 40 | en | 0.863309 |
import concurrent.futures
import contextlib
import http.client
import json
import math
import os
import time
from .common import FileDownloader
from .http import HttpFD
from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
from ..compat import compat_os_name, compat_struct_pack, compat_urllib_error
from ..utils import ... | yt_dlp/downloader/fragment.py | 22,684 | A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
Available options:
fragment_retries: Number of times to retry a fragment for HTTP error (DASH
and hlsnative only)
skip_unavailable_fragments:
Skip unavailable fragments (DASH and hlsnative only)
keep... | 2,686 | en | 0.854526 |
from functools import partial
from typing import Any, Callable, List, Optional, Sequence, Type, Union
from torch import nn
from torchvision.prototype.transforms import VideoClassificationEval
from torchvision.transforms.functional import InterpolationMode
from ....models.video.resnet import (
BasicBlock,
Basi... | torchvision/prototype/models/video/resnet.py | 4,350 | type: ignore[list-item] | 23 | fr | 0.272261 |
from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... | Alignment/OfflineValidation/python/TkAlAllInOneTool/genericValidation.py | 36,034 | Subclass of `GenericValidation` which is the base for validations using
datasets.
This method adds additional items to the `self.general` dictionary
which are only needed for validations using datasets.
Arguments:
- `valName`: String which identifies individual validation instances
- `alignment`: `Alignment` instance ... | 1,835 | en | 0.763299 |
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... | pylith/apps/ConfigSearchApp.py | 9,501 | Application for searching PyLith .cfg files.
Constructor.
Apply filters to metadata.
Args:
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
Returns: (bool)
True if metadata meets filter requirements, False otherwise.
Apply filters to metadata to find incompatible parameter... | 2,064 | en | 0.483434 |
# Interview Questions
"""
Given the following list of objects {user, loginTime, logoutTime}. What is the maximum number of concurrent users logged in at the same time?
Input:
[
{user: A, login: 1, logout: 3},
{user: B, login: 3, logout: 4},
{user: C, login: 1, logout: 2},
{user: D, login: 123123123, logo... | interview/booking.com/max_concurrent.py | 1,052 | Given the following list of objects {user, loginTime, logoutTime}. What is the maximum number of concurrent users logged in at the same time?
Input:
[
{user: A, login: 1, logout: 3},
{user: B, login: 3, logout: 4},
{user: C, login: 1, logout: 2},
{user: D, login:... | 453 | en | 0.758208 |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | python/paddle/fluid/tests/unittests/test_roll_op.py | 3,876 | Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agree... | 615 | en | 0.852302 |
import importlib
import os
from datasets.hdf5 import get_test_loaders
from unet3d import utils
from unet3d.config import load_config
from unet3d.model import get_model
logger = utils.get_logger('UNet3DPredictor')
def _get_predictor(model, loader, output_file, config):
predictor_config = config.get('pr... | predict.py | 1,420 | model: UNet3D, loader: test_loader, output_file: data.h5, config: config.yaml Load configuration Create the model Load model state | 130 | en | 0.270328 |
# -*- coding: utf-8 -*-
#
# django-staticbuilder documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 30 22:32:51 2013.
#
# 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 ... | docs/source/conf.py | 8,079 | -*- coding: utf-8 -*- django-staticbuilder documentation build configuration file, created by sphinx-quickstart on Wed Jan 30 22:32:51 2013. 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 configur... | 6,654 | en | 0.652461 |
# coding: utf-8
"""
Purity//FB REST Client
Client for Purity//FB REST API (1.0 - 1.6), developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.6
Contact: info@purestorage.com
... | purity_fb/purity_fb_1dot6/apis/usage_users_api.py | 7,269 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
A list of usage user entries
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to... | 3,068 | en | 0.764704 |
"""
Unit tests for the structured metamodel component.
"""
import unittest
import inspect
import numpy as np
from numpy.testing import assert_almost_equal
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal, assert_warning, assert_check_partials
from openmdao.utils.general_utils import... | openmdao/components/tests/test_meta_model_structured_comp.py | 54,074 | Tests the regular grid map component. specifically the analytic derivatives
vs. finite difference estimates.
Tests the regular grid map component. specifically the analytic derivatives
vs. finite difference estimates.
Runs check_partials and compares to analytic derivatives.
Runs check_partials and compares to analytic... | 2,384 | en | 0.753891 |
"""Collection of Jax network layers, wrapped to fit Ivy syntax and
signature.
"""
# global
import jax.numpy as jnp
import jax.lax as jlax
# local
from ivy.functional.backends.jax import JaxArray
def conv1d(
x: JaxArray,
filters: JaxArray,
strides: int,
padding: str,
data_format: str = "NWC",
... | ivy/functional/backends/jax/layers.py | 1,525 | Collection of Jax network layers, wrapped to fit Ivy syntax and
signature.
global local | 89 | en | 0.608649 |
import numpy
import torch
import pytorch_pfn_extras as ppe
from torch.utils.data import Dataset
class TabularDataset(Dataset):
"""An abstract class that represents tabular dataset.
This class represents a tabular dataset.
In a tabular dataset, all examples have the same number of elements.
For examp... | pytorch_pfn_extras/dataset/tabular/tabular_dataset.py | 11,149 | An abstract class that represents tabular dataset.
This class represents a tabular dataset.
In a tabular dataset, all examples have the same number of elements.
For example, all examples of the dataset below have three elements
(:obj:`a[i]`, :obj:`b[i]`, and :obj:`c[i]`).
.. csv-table::
:header: , a, b, c
0,... | 6,886 | en | 0.695728 |
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | nova/tests/unit/console/test_serial.py | 4,892 | Tests for Serial Console.
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... | 598 | en | 0.874696 |
# Copyright 2018-2021 Streamlit 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 wr... | notebook/lib/python3.9/site-packages/streamlit/bootstrap.py | 12,616 | Set Matplotlib backend to avoid a crash.
The default Matplotlib backend crashes Python on OSX when run on a thread
that's not the main thread, so here we set a safer backend as a fix.
Users can always disable this behavior by setting the config
runner.fixMatplotlib = false.
This fix is OS-independent. We didn't see a... | 4,506 | en | 0.82448 |
{
'repo_type' : 'archive',
'download_locations' : [
#UPDATECHECKS: http://fftw.org/download.html
#{ "url" : "http://fftw.org/fftw-3.3.9.tar.gz", "hashes" : [ { "type" : "sha256", "sum" : "bf2c7ce40b04ae811af714deb512510cc2c17b9ab9d6ddcf49fe4487eea7af3d" }, ], },
#{ "url" : "https://fossies.org/linux/misc/fftw-3... | packages/dependencies/fftw3_dll_double.py | 2,022 | UPDATECHECKS: http://fftw.org/download.html{ "url" : "http://fftw.org/fftw-3.3.9.tar.gz", "hashes" : [ { "type" : "sha256", "sum" : "bf2c7ce40b04ae811af714deb512510cc2c17b9ab9d6ddcf49fe4487eea7af3d" }, ], },{ "url" : "https://fossies.org/linux/misc/fftw-3.3.9.tar.gz", "hashes" : [ { "type" : "sha256", "sum" : "bf2c7ce4... | 492 | en | 0.504637 |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
category_list = Category.objects.order_by('-name')[:5]
#category_list = Category.objects().order_by('-name')
context = {'categories': category_list} # Aquí van la las variables para la... | rango/views.py | 382 | Create your views here.category_list = Category.objects().order_by('-name') Aquí van la las variables para la plantilla | 119 | es | 0.411851 |
import numpy as np
from LoopStructural.utils import getLogger
logger = getLogger(__name__)
def gradients(vals, func, releps=1e-3, abseps=None, mineps=1e-9, reltol=1,
epsscale=0.5):
"""
Calculate the partial derivatives of a function at a set of values. The
derivatives are calculated using th... | LoopStructural/probability/_gradient_calculator.py | 4,432 | Calculate the partial derivatives of a function at a set of values. The
derivatives are calculated using the central difference, using an iterative
method to check that the values converge as step size decreases.
Parameters
----------
vals: array_like
A set of values, that are passed to a function, at which to cal... | 1,620 | en | 0.811213 |
'''
@author: xiayuanhuang
'''
import csv
import matchECtoDemog
import decisionTreeV7
import family_treeV4
import inference
import combine_new_ped
def combine(addressFile, nameFile, demoFile, accountFile, outputFile, patientFile, ecFile, familyTreeOutput):
reader_add = csv.reader(open(addressFile, 'r'), delimite... | Source/combine.py | 4,965 | @author: xiayuanhuang
run combined algorithm riftehr fppanewFamilyTree.connected('fppa_pedigree.csv')new_infer.assignFamilies(familyTreeOutput) run combined algorithm riftehr fppanewFamilyTree.connected('fppa_pedigree.csv') | 225 | en | 0.668918 |
import acequia as aq
from acequia import KnmiStations
if 1: # test KnmiStations.prec_stns()
knmi = KnmiStations()
print("Retrieving list of all available precipitation stations.")
#filepath = r'..\02_data\knmi_locations\stn-prc-available.csv'
filepath = 'stn-prc-available.csv'
dfprc = knmi.p... | old_tests/test_read_knmistations.py | 785 | test KnmiStations.prec_stns()filepath = r'..\02_data\knmi_locations\stn-prc-available.csv' test KnmiStations.wheater_stns()filepath = r'..\02_data\knmi_locations\stn-wht-available.csv' | 184 | en | 0.360748 |
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from ins import *
from ruffier import*
f... | main.py | 8,742 | имя экрана должно передаваться конструктору класса Screen имя экрана должно передаваться конструктору класса Screen имя экрана должно передаваться конструктору класса Screen имя экрана должно передаваться конструктору класса Screen имя экрана должно передаваться конструктору класса Screen | 289 | ru | 0.996645 |
from rest_framework import serializers
class HelloSerializer(serializers.Serializer):
"""serializers a name field for testing our APIView"""
name = serializers.CharField(max_length = 10) | profile_api/serializers.py | 195 | serializers a name field for testing our APIView | 48 | en | 0.717424 |
#!/usr/bin/env python3
import iterm2
# To install, update, or remove packages from PyPI, use Scripts > Manage > Manage Dependencies...
import subprocess
async def main(connection):
component = iterm2.StatusBarComponent(
short_description = 'k8s current context',
detailed_description = 'Dis... | k8s-context.py | 1,099 | !/usr/bin/env python3 To install, update, or remove packages from PyPI, use Scripts > Manage > Manage Dependencies... This instructs the script to run the "main" coroutine and to keep running even after it returns. | 214 | en | 0.809949 |
# celery settings
broker_url = 'amqp://guest:guest@rabbitmq:5672/'
result_backend = 'rpc://'
accept_content = ['json']
task_serializer = 'json'
task_soft_time_limit = 60 * 3 # 3 minute timeout
result_serializer = 'json'
timezone = 'UTC'
enable_utc = True
| config/celeryconfig.py | 258 | celery settings 3 minute timeout | 32 | en | 0.518293 |
# Copyright (C) 2019-2021 HERE Europe B.V.
# SPDX-License-Identifier: Apache-2.0
"""This module defines all the configs which will be required as inputs to autosuggest API."""
from .base_config import Bunch
class SearchCircle:
"""A class to define ``SearchCircle``
Results will be returned if they are locat... | here_location_services/config/autosuggest_config.py | 1,622 | A Class to define constant values for political view
``RUS``:
expressing the Russian view on Crimea
``SRB``:
expressing the Serbian view on Kosovo, Vukovar and Sarengrad Islands
``MAR``:
expressing the Moroccan view on Western Sahara
A class to define ``SearchCircle``
Results will be returned if they are located wi... | 1,091 | en | 0.760122 |
LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... | lab/lab05/lab05.py | 10,067 | Return a string containing the characters you need to add to w1 to get w2.
You may assume that w1 is a subsequence of w2.
>>> add_chars("owl", "howl")
'h'
>>> add_chars("want", "wanton")
'on'
>>> add_chars("rat", "radiate")
'diae'
>>> add_chars("a", "prepare")
'prepre'
>>> add_chars("resin", "recursion")
'curo'
>>> a... | 5,678 | en | 0.613587 |
import itertools
import re
import detectEnglish
import freqAnalysis
vigenereCipher = __import__('vigenereCipher')
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# SILENT_MODE = False # If set to True, program doesn't print anything.
SILENT_MODE = True
NUM_MOST_FREQ_LETTERS = 4 # Attempt this many letters per subkey.
MAX_KE... | crypto/vigenere/vigenere_breaker.py | 12,778 | SILENT_MODE = False If set to True, program doesn't print anything. Attempt this many letters per subkey. Will not attempt keys longer than this. Goes through the message and finds any 3 to 5 letter sequences that are repeated. Returns a dict with the keys of the sequence and values of a list of spacings (num of lette... | 3,708 | en | 0.855258 |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2020 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... | venv/Lib/site-packages/pyrogram/raw/functions/messages/get_dialog_unread_marks.py | 2,020 | Telegram API method.
Details:
- Layer: ``117``
- ID: ``0x22e24e22``
**No parameters required.**
Returns:
List of :obj:`DialogPeer <pyrogram.raw.base.DialogPeer>`
Pyrogram - Telegram MTProto API Client Library for Python Copyright (C) 2017-2020 Dan <https://github.com/delivrance> This file is part of... | 1,171 | en | 0.821111 |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | tools/concrete_model/model/entity.py | 3,581 | Class to represent entities within the concrete model.
Attributes:
name: Human readable name of an entity.
guid: UUID4 value for an entity.
cloud_device_id: IoT application device id.
type_name: Instance of EntityType class.
fields: Mapping of standard field names to EntityField instances.
is_reporting: if... | 2,321 | en | 0.795702 |
#!/usr/bin/env python
#encoding: utf8
import unittest, rostest
import rosnode, rospy
import time
from pimouse_ros.msg import MotorFreqs
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
from pimouse_ros.srv import TimedMotion
class MotorTest(unittest.TestCase):
def setUp(self):
... | test/travis_test_motors.py | 3,022 | !/usr/bin/env pythonencoding: utf8 | 34 | ca | 0.189331 |
# Python GLFW hello world example based on C++ guide at
# http://www.glfw.org/docs/latest/quick.html
import sys
import glfw
import numpy
from OpenGL import GL
from OpenGL.GL.shaders import compileShader, compileProgram
from OpenGL.arrays import vbo
from openvr.glframework.glmatrix import rotate_z, ortho,... | src/python/vrprim/mesh/glfw_triangle.py | 3,844 | Python GLFW hello world example based on C++ guide at http://www.glfw.org/docs/latest/quick.html Initialize GLFW OpenGL API Use modern OpenGL version 4.5 core Create OpenGL window and context Create vertex array object, apparently required for modern OpenGL Create triangle geometry: corner 2D location and colors x, y,... | 529 | en | 0.554313 |
"""general utility functions for HTML Map templates"""
def safe_quotes(text, escape_single_quotes=False):
"""htmlify string"""
if isinstance(text, str):
safe_text = text.replace('"', """)
if escape_single_quotes:
safe_text = safe_text.replace("'", "\'")
return safe... | cartoframes/viz/html/utils.py | 652 | htmlify string
general utility functions for HTML Map templates | 63 | en | 0.472752 |
import unittest
from quarkchain.cluster.tests.test_utils import (
create_transfer_transaction,
ClusterContext,
)
from quarkchain.core import (
Address,
Branch,
Identity,
TokenBalanceMap,
XshardTxCursorInfo,
)
from quarkchain.evm import opcodes
from quarkchain.utils import call_async, assert_... | quarkchain/cluster/tests/test_cluster.py | 63,239 | Test the cross shard transactions are broadcasted to the destination shards
Test the broadcast is only done to the neighbors
Test the broadcast is only done to the neighbors
Test the broadcast is only done to the neighbors
Test the broadcast is only done to the neighbors
Test the broadcast is only done to the neig... | 4,312 | en | 0.918712 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
from ..utils import all_numeric_dtypes
class Max(Base):
@staticmethod
... | onnx/backend/test/case/node/max.py | 1,962 | type: ignore type: () -> None type: () -> None | 46 | en | 0.314945 |
import theano.tensor as T
import theano
import numpy as np
from scipy.spatial.distance import pdist, squareform, cdist
import random
import time
'''
Sample code to reproduce our results for the Bayesian neural network example.
Our settings are almost the same as Hernandez-Lobato and Adams (ICML15) https://jmhl... | python/bayesian_nn_subset.py | 27,850 | We define a one-hidden-layer-neural-network specifically. We leave extension of deep neural network as our future work.
Input
-- X_train: training dataset, features
-- y_train: training labels
-- batch_size: sub-sampling batch size
-- max_iter: maximum iterations for the training procedure
-- M: nu... | 3,316 | en | 0.624863 |
'''
This file contains test cases for tflearn
'''
import tensorflow as tf
import zqtflearn
import unittest
class TestInputs(unittest.TestCase):
'''
This class contains test cases for serval input types
'''
INPUT_DATA_1 = [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ]
INPUT_DATA_2 = [ [ 6 ], [ 7 ], ... | zqtflearn2/tests/test_inputs.py | 2,253 | This class contains test cases for serval input types
Build a simple model for test
Returns:
DNN, [ (input layer name, input placeholder, input data) ], Target data
Test input a dict with layer name
Test input a dict with placeholder
Test input a list
This file contains test cases for tfl... | 348 | en | 0.496812 |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | tests/ut/python/parallel/test_transpose.py | 3,369 | Copyright 2019 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw... | 561 | en | 0.849356 |
# Quiet TensorFlow.
import os
import numpy as np
# from transformers import AutoTokenizer, TFAutoModelForSequenceClassification, pipeline
from transformers import BertTokenizer, BertForSequenceClassification
import textattack
from textattack import Attacker
from textattack.attack_recipes.my_attack.my_textfooler import... | experiments/sst/attack_bert_textfooler_sst.py | 2,116 | Quiet TensorFlow. from transformers import AutoTokenizer, TFAutoModelForSequenceClassification, pipeline sentence_list = [] label_list = [] dataset = HuggingFaceDataset("allocine", split="test") attack_args = textattack.AttackArgs(num_examples = -1, log_to_txt = './log/textfooler_sst_bertbase_query2000.txt', query_budg... | 435 | en | 0.478609 |
from utilities import *
from model import get_model
from data import get_data, get_loaders
from augmentations import get_augs
from test_epoch import test_epoch
import gc
import neptune
from accelerate import Accelerator, DistributedType
import pandas as pd
import numpy as np
def run_inference(df,
... | code/run_inference.py | 4,693 | Run inference loop
tests placeholders inference initialize accelerator feedback get data get test loader prepare model handle device placement inference for validation data produce OOF preds store OOF preds inference for test data produce test preds store test preds clear memory export OOF preds export test preds | 316 | en | 0.519201 |
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from settings import Microsoft
'''
See the Microsoft DirectLine api documentation for how to get a user access token.
https://docs.botframework.com/en-us/restapi/directline/
'''
chatbot = ChatBot(
'Micro... | examples/microsoft_bot.py | 947 | -*- coding: utf-8 -*- The following loop will execute each time the user enters input Press ctrl-c or ctrl-d on the keyboard to exit | 132 | en | 0.770185 |
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.capture('image.jpg')
#camera.resolution = (640, 480) #max resolution is 2592 x 1944 for stills,
# 1920 x 1080 (<15fps) for video
#camera.framerate = 45
camera.vflip = True
camera.start_recording('... | src/test.py | 612 | camera.resolution = (640, 480) max resolution is 2592 x 1944 for stills, 1920 x 1080 (<15fps) for videocamera.framerate = 45 | 141 | en | 0.747164 |
# coding: utf-8
"""
Adobe Experience Manager (AEM) API
Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
OpenAPI spec version: 2.2.0
Contact: opensource@shinesolutions.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import ab... | clients/python/generated/swaggeraem/apis/crx_api.py | 25,860 | coding: utf-8 python 2 and python 3 compatibility library HTTP header `Accept` Authentication setting HTTP header `Accept` Authentication setting verify the required parameter 'cmd' is set HTTP header `Accept` Authentication setting verify the required parameter 'path' is set verify the required parameter 'cmd' is set ... | 805 | en | 0.260959 |
import json
import re
from django.http import JsonResponse
from django.db.models import Q
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from apps.vit.models import Vit
from apps.notification.utilities import notify
from apps.vit.utilities import find_mention, find_plustag
from .... | apps/vit/api.py | 5,280 | Add a new vit with API, currently image and video are not supported
Delete a vit with API
Edit a vit with API | 109 | en | 0.94291 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
#-------------------------------------------------#
# MISH激活函数
#-------------------------------------------------#
class Mish(nn.Module):
def __init__(self):
super(Mish, self).__init__()
def forward(self, x):
re... | .history/nets/CSPdarknet_20210816140029.py | 7,299 | ------------------------------------------------- MISH激活函数---------------------------------------------------------------------------------------------------- 卷积块 -> 卷积 + 标准化 + 激活函数 Conv2d + BatchNormalization + Mish---------------------------------------------------pad = kernel_size//2,表示1x1卷积不补零,3x3卷积补一圈0,这样输出图... | 2,110 | zh | 0.260455 |
# -*- coding: utf-8 -*-
# Scrapy settings for mySpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topi... | mySpider/mySpider/settings.py | 3,089 | -*- coding: utf-8 -*- Scrapy settings for mySpider project For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: https://doc.scrapy.org/en/latest/topics/settings.html https://doc.scrapy.org/en/latest/topics/downloader-mid... | 2,698 | en | 0.621626 |
# Generated by Django 3.1.2 on 2020-12-07 05:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('zooniverse', '0006_auto_20201207_0713'),
]
operations = [
migrations.CreateModel(
... | quality_control/migrations/0001_initial.py | 777 | Generated by Django 3.1.2 on 2020-12-07 05:13 | 45 | en | 0.74866 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... | pywallet/utils/ethereum.py | 55,633 | Base class for HDPrivateKey and HDPublicKey.
Args:
key (PrivateKey or PublicKey): The underlying simple private or
public key that is used to sign/verify.
chain_code (bytes): The chain code associated with the HD key.
depth (int): How many levels below the master node this key is. By
definiti... | 26,199 | en | 0.75154 |
# -*- coding: utf-8 -*-
from tkinter import (
Frame,
LabelFrame,
Text,
Scrollbar,
Button,
Label,
RIDGE,
W,
E,
N,
S,
FLAT,
CENTER,
SUNKEN,
END,
INSERT,
)
from tkinter.simpledialog import askinteger, askstring
from tkinter.messagebox ... | Emulatore.py | 23,048 | Interfaccia grafica per l'emulatore del pdp8
Inizializza i frame per l'interfaccia dell'emulatore
Aggiorna tutto
Aggiorna gli input ed output di sistema
Aggiorna le microistruzioni eseguite
Aggiorna micro e input/output
Aggiorna lo stato della RAM
Aggiorna lo stato dei Registri
Aggiorna lo stato dell'unita' di controll... | 2,467 | it | 0.950258 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import sys
from pathlib import Path
from typing import Any
import nevergrad as ng
from hydra.core.override_parser.overrides_parser import OverridesParser
from hydra.core.plugins import Plugins
from hydra.plugins.sweeper import Sweeper
from hydra.te... | plugins/hydra_nevergrad_sweeper/tests/test_nevergrad_sweeper_plugin.py | 6,336 | Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved small budget to test fast make a full test only once (faster) small budget to test fast avoid random failures this argument should be easy to find check that all job folders are created small budget to test fast | 280 | en | 0.898251 |
#!/usr/bin/env python3
def sum_recursin(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + sum_recursin(numList[1:])
if __name__ == "__main__":
print(sum_recursin(list(range(1, 101))))
| 07_RSI/ch03/sum.py | 240 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
#!/content/Python/bin/python3.6
import os
import torch
from setuptools import setup, find_packages
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from compiler_args import nvcc_args, cxx_args
setup(
name='interpolation_cuda',
ext_modules=[
CUDAExtension('interpolation_cuda', [
... | my_package/Interpolation/setup.py | 531 | !/content/Python/bin/python3.6 | 30 | en | 0.826878 |
# Copyright 2018-2020 Streamlit 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 wr... | lib/streamlit/DeltaGenerator.py | 112,188 | Creator of Delta protobuf messages.
Parameters
----------
container: BlockPath_pb2.BlockPath or None
The root container for this DeltaGenerator. If None, this is a null
DeltaGenerator which doesn't print to the app at all (useful for
testing).
cursor: cursor.AbstractCursor or None
Return this from DeltaGenerato... | 56,211 | en | 0.639757 |
from collections import OrderedDict
import numpy as np
from gym.spaces import Box, Dict
from multiworld.envs.env_util import get_stat_in_paths, \
create_stats_ordered_dict, get_asset_full_path
from multiworld.core.multitask_env import MultitaskEnv
from multiworld.envs.mujoco.sawyer_xyz.push.sawyer_push import SawyerP... | multiworld/envs/mujoco/sawyer_xyz/pickPlace/sawyer_coffee.py | 7,279 | :param zangle in rad
:return: quaternion
return (Quaternion(axis=[0,1,0], angle=np.pi) * Quaternion(axis=[0, 0, -1], angle= zangle)).elementsreturn (Quaternion(axis=[1,0,0], angle=np.pi) * Quaternion(axis=[0, -1, 0], angle= zangle)).elementsreturn (Quaternion(axis=[1,0,0], angle=np.pi) * Quaternion(axis=[-1, 0, 0], an... | 1,668 | en | 0.255103 |
"""
Evolutionary optimization of something
"""
import random
import multiprocessing
import numpy as np
import numpy.random as npr
import matplotlib.pylab as plt
from tqdm import tqdm
from automata import SnowDrift
class EvolutionaryOptimizer(object):
""" Optimize!
"""
def __init__(self):
""" ... | evolutionary_optimization.py | 3,905 | Optimize!
Optimize snowdrift game by assuming each individual to be the pair of
benefit and cost floats
Set some parameters
Generate offspring from parents
Compute fitness of individual of population
Generate initial population
Setup environment
Mutate single individual
... | 593 | en | 0.733882 |
"""Define SetConfig message."""
# System imports
# Third-party imports
# Local imports
from pyof.v0x01.common.header import Type
from pyof.v0x01.controller2switch.common import SwitchConfig
__all__ = ('SetConfig',)
class SetConfig(SwitchConfig):
"""Set config message."""
def __init__(self, xid=None, flag... | pyof/v0x01/controller2switch/set_config.py | 838 | Set config message.
Create a SetConfig with the optional parameters below.
Args:
xid (int): xid to be used on the message header.
flags (~pyof.v0x01.controller2switch.common.ConfigFlag):
OFPC_* flags.
miss_send_len (int): UBInt16 max bytes of new flow that the
datapath should send to the co... | 406 | en | 0.375165 |
import numpy as np
import scipy.interpolate
from numpy import polyint, polymul, polyval
from scipy.interpolate import BSpline as SciBSpline, PPoly
from ..._utils import _domain_range
from ._basis import Basis
class BSpline(Basis):
r"""BSpline basis.
BSpline basis elements are defined recursively as:
..... | skfda/representation/basis/_bspline.py | 12,484 | BSpline basis.
BSpline basis elements are defined recursively as:
.. math::
B_{i, 1}(x) = 1 \quad \text{if } t_i \le x < t_{i+1},
\quad 0 \text{ otherwise}
.. math::
B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)
+ \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)
Where k indicate... | 4,855 | en | 0.752205 |
import json
import logging
import traceback
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from helpers.cache_clearer import CacheClearer
from helpers.firebase.firebase_pusher import FirebasePusher
from helpers.notification_helper import NotificationHelper
from helpers.manipulator_bas... | helpers/match_manipulator.py | 6,335 | Only continue if the event is currently happening There is a score update for this match, push a notification The match has not been played and we're changing a property that affects the event's schedule So send a schedule update notification for the parent event Enqueue task to calculate matchstats These build key_nam... | 512 | en | 0.905675 |
"""Test config validators."""
from datetime import timedelta, datetime, date
import enum
import os
from socket import _GLOBAL_DEFAULT_TIMEOUT
from unittest.mock import Mock, patch
import pytest
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
def test_boolean():
"""Test boolean vali... | tests/helpers/test_config_validation.py | 14,544 | Test enum.
Test boolean validation.
Test config validation for component entity IDs.
Test date validation.
Test date time validation.
Test deprecation log.
Test ensure_list.
Test ensure_list_csv.
Test entities domain validation.
Test entity domain validation.
Test entity ID validation.
Test entity ID validation.
Test e... | 1,171 | en | 0.386413 |
#!/usr/bin/env python
from wsgiref.simple_server import make_server
import sys
import os
import json
import urlparse
import json
EXTRA_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__)))
if EXTRA_DIR not in sys.path:
sys.path.append(EXTRA_DIR)
import dao
try:
import requests
except ImportError:... | api/getTags.py | 1,330 | !/usr/bin/env python the environment variable CONTENT_LENGTH may be empty or missing | 84 | en | 0.361576 |
import io
import os
import ssl
import boto3
import gzip
import json
import time
import uuid
import unittest
import datetime
import requests
from io import BytesIO
from pytz import timezone
from botocore.exceptions import ClientError
from six.moves.urllib.request import Request, urlopen
from localstack import config
fro... | tests/integration/test_s3.py | 70,713 | Class to handle putting with urllib
create test bucket put bucket policy retrieve and check policy config put an object where the bucket_name is in the path put an object where the bucket_name is in the host it doesn't care about the authorization header as long as it's present verify=False must be set as this test ... | 4,827 | en | 0.850412 |
# Generated by Django 2.2.1 on 2019-11-18 10:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0020_auto_20191112_1048'),
]
operations = [
migrations.AlterModelOptions(
name='payment',
options={'ordering': ('dat... | backend/core/migrations/0021_auto_20191118_1144.py | 409 | Generated by Django 2.2.1 on 2019-11-18 10:44 | 45 | en | 0.574809 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 10 19:37:19 2018
@author: kaustabh
"""
#making a single list representing all sides in a serial fashion
r = ['w1','w2','w3','w4','w5','w6','w7','w8','w9','b1','b2','b3','r1','r2','r3','g1','g2','g3','o1','o2','o3','b4','b5','b6','r4','r5','r6',... | Rubikmovement.py | 7,534 | Created on Wed Jan 10 19:37:19 2018
@author: kaustabh
!/usr/bin/env python3 -*- coding: utf-8 -*-making a single list representing all sides in a serial fashion cube is the list and we can't use random.shuffle because certain colors stay togetherr is cube list ; L is 12 element array to be shifteda face will also rot... | 323 | en | 0.849661 |
from pavilion import result_parsers
import yaml_config as yc
import re
import sre_constants
class Regex(result_parsers.ResultParser):
"""Find matches to the given regex in the given file. The matched string
or strings are returned as the result."""
def __init__(self):
super().__init__(name='regex... | lib/pavilion/plugins/results/regex.py | 7,812 | Find matches to the given regex in the given file. The matched string
or strings are returned as the result.
Use the built-in matches element. If the value is an int, it seems to work better to cast it as a float first, just in case it is a float. Check for range specification as (<lesser value>:<greater value>) Find... | 687 | en | 0.881832 |
#define functions that will extract the data from SDSS based on an input RA/DEC
from astroquery.sdss import SDSS
from astropy import coordinates as coords
import pandas as pd
from astroquery.ned import Ned
import matplotlib.pyplot as plt
from astropy.convolution import convolve, Box1DKernel
import numpy as np
from a... | exampledoc/Extractor.py | 6,875 | This function uses extracted information in order to dwonaload spectra,
separating the data from th SDSS and BOSS.
downloader(pd.Dataframe) --> [list(fits)]
This function extracts the information from the SDSS database and returns
a pandas dataframe with the query region. Please ensure that the 'position'
input is fo... | 2,997 | en | 0.740858 |
import re
import types
import logging
from banal import ensure_list
from normality import stringify
from balkhash.utils import safe_fragment
from email.utils import parsedate_to_datetime, getaddresses
from normality import safe_filename, ascii_text
from followthemoney.types import registry
from ingestors.support.html ... | services/ingest-file/ingestors/support/email.py | 8,352 | Extract metadata from email messages.
Parse E-Mail headers into FtM properties.
This should be using formataddr, but I cannot figure out how to use that without encoding the name. Hello, Outlook. https://cr.yp.to/immhf/thread.html forward linking: from message ID to entity ID backward linking: prepare entity ID for m... | 334 | en | 0.691491 |
import setuptools
with open("../README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="cog",
version="0.0.1",
author_email="team@replicate.com",
description="Containers for machine learning",
long_description=long_description,
long_description_conte... | python/setup.py | 709 | intionally loose. perhaps these should be vendored to not collide with user code? | 81 | en | 0.984239 |
from handlers.kbeServer.Editor.Interface import interface_workmark
from methods.DBManager import DBManager
#点赞
def Transactions_Code_2008( self_uid , self_username , json_data):
# 回调json
json_back = {
"code": 0,
"msg": "",
"pam": ""
}
# json_data 结构
uid = int(json_data["... | handlers/kbeServer/Editor/response/response_workmark.py | 2,954 | 点赞 回调json json_data 结构uid ,wid ,lid ,siscid ,tid ,dian ,ctype 获取下db的句柄,如果需要操作数据库的话评分/评论 回调json json_data 结构uid ,wid ,lid ,siscid ,tid ,dian ,ctype 获取下db的句柄,如果需要操作数据库的话获取评分数据 回调json json_data 结构uid ,wid ,lid ,siscid ,tid ,dian ,ctype 获取下db的句柄,如果需要操作数据库的话获取评论数据 回调json json_data 结构 获取下db的句柄,如果需要操作数据库的话 | 300 | zh | 0.69952 |
# Copyright 2019-2021 Wingify Software Pvt. Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | vwo/services/segmentor/segment_evaluator.py | 2,225 | Class to evaluate segments defined in VWO app
Initializes this class with VWOLogger and OperandEvaluator
A parser which recursively evaluates the custom_variables passed against
the expression tree represented by segments, and returns the result.
Args:
segments(dict): The segments representing the expression tre... | 989 | en | 0.809164 |
"""
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the ... | 1-50/27_remove-element.py | 1,748 | :type nums: List[int]
:type val: int
:rtype: int
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed.... | 1,433 | en | 0.884086 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uofthacksemergencyfunds.settings')
try:
from django.core.management import execute_from_command_line... | manage.py | 679 | Run administrative tasks.
Django's command-line utility for administrative tasks.
!/usr/bin/env python | 103 | en | 0.725633 |
# MINLP written by GAMS Convert at 08/20/20 01:30:53
#
# Equation counts
# Total E G L N X C B
# 3360 1353 785 1222 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | models_nonconvex_simple2/crudeoil_lee3_06.py | 374,879 | MINLP written by GAMS Convert at 08/20/20 01:30:53 Equation counts Total E G L N X C B 3360 1353 785 1222 0 0 0 0 Variable counts x b i s1s s2s sc si Tota... | 680 | en | 0.679479 |
#!/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.
# Test mempool limiting together/eviction with the wallet
from test_framework.test_framework import Bitc... | qa/rpc-tests/mempool_limit.py | 2,282 | !/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. Test mempool limiting together/eviction with the walletcreate a mempool tx that will be evicted specifically fund... | 464 | en | 0.732659 |
import json
import time, asyncio
from smsgateway import sink_sms
from smsgateway.config import *
from smsgateway.sources.utils import *
from slackclient import SlackClient
def init():
global IDENTIFIER, app_log
IDENTIFIER = "SL"
app_log = setup_logging("slack")
def main():
init()
sc = SlackClien... | smsgateway/sources/slack.py | 3,534 | loop = asyncio.get_event_loop() loop.run_until_complete(main()) | 63 | en | 0.253612 |
#!/usr/bin/env python
#
# pyLearn documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# 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... | docs/conf.py | 4,805 | !/usr/bin/env python pyLearn documentation build configuration file, created by sphinx-quickstart on Fri Jun 9 13:47:02 2017. 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 configuration values h... | 3,556 | en | 0.699765 |
"""
Base settings for Mad Taxi project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (mad_taxi/config/se... | config/settings/base.py | 10,609 | Base settings for Mad Taxi project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
(mad_taxi/config/settings/base.py - 3 = mad_taxi/) Load operating system environme... | 5,254 | en | 0.529893 |
'''cleanup intermediary files '''
import os
def run(c): # run something at terminal and wait to finish
print(c)
a = os.system(c)
run('rm *.png') # remove figures
run('rm test* truth*') # wipe test and truth data
run('rm -rf test truth') # wipe test and truth data segment files
| presentations/20210526_simple_character_recognition/cleanup.py | 291 | cleanup intermediary files
run something at terminal and wait to finish remove figures wipe test and truth data wipe test and truth data segment files | 153 | en | 0.776297 |
#
# Copyright 2021 IBM All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | ibm_appconfiguration/version.py | 664 | Version of ibm-appconfiguration-python-sdk
Copyright 2021 IBM 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... | 607 | en | 0.857021 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... | tests/test_filters.py | 11,940 | Create and return test view class instance
Args:
es_ordering_fields (tuple): ordering fields
Returns:
ElasticAPIView: test view instance
Create and return test view class instance
Args:
es_filter_fields ([ESFieldFilter]): filtering fields
Returns:
ElasticAPIView: test view instance
Create and return t... | 683 | en | 0.569665 |
from __future__ import absolute_import
from datetime import datetime
from enum import Enum
from checkout_sdk.common.common import Address, Phone, CustomerRequest
from checkout_sdk.common.enums import Currency, PaymentSourceType, ChallengeIndicator, Country
class Exemption(str, Enum):
LOW_VALUE = 'low_value'
... | checkout_sdk/payments/payments.py | 5,789 | Request Source Request Destination Request Captures Refunds Voids | 65 | en | 0.583717 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.