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
# File: gsgmail_process_email.py # Copyright (c) 2017-2021 Splunk Inc. # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) import email import tempfile from collections import OrderedDict import os import re from bs4 import BeautifulSoup, UnicodeDammit import phantom.app as phantom import p...
Apps/phgsgmail/gsgmail_process_email.py
42,076
This method is used to get appropriate error message from the exception. :param e: Exception object :return: error message File: gsgmail_process_email.py Copyright (c) 2017-2021 Splunk Inc. Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) Don't run any playbooks, when this artifact is added...
4,337
en
0.844701
# Copyright 2021 ETH Zurich, Media Technology 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...
preprocessing.py
10,315
Loads the horizontal user item data from folder and creates a user-wise a 70% train, 20% validation, 10% test split. This means for each user the first 70% read articles are in the train the next 20% in validation and the last 10% read articles in the test set. We remove users with less than 10 clicked articles. This i...
4,319
en
0.861619
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os from foundations.step import Step from training.metric_logger import MetricLogger from testing import test_case class ...
training/test/test_metric_logger.py
2,845
Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
168
en
0.897895
import logging import os from enum import Enum from functools import lru_cache from typing import Optional from pydantic import BaseSettings, PostgresDsn logger = logging.getLogger(__name__) class EnvironmentEnum(str, Enum): PRODUCTION = "production" LOCAL = "local" class GlobalConfig(BaseSettings): T...
services/endorser/api/core/config.py
3,343
Local configurations. Production configurations. the following defaults match up with default values in scripts/.env.example these MUST be all set in non-local environments. application connection is async fmt: off noqa: E501 migrations connection uses owner role and is synchronous noqa: E501 fmt: on Api V1 prefix op...
338
en
0.768724
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet accounts properly when there are cloned transactions with malleated scriptsigs.""" fro...
test/functional/wallet_txn_clone.py
5,972
Test the wallet accounts properly when there are cloned transactions with malleated scriptsigs. !/usr/bin/env python3 Copyright (c) 2014-2016 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Start with split...
1,384
en
0.850748
import collections from collections import defaultdict import sys import json import random from jsmin import jsmin from io import StringIO import numpy as np import copy import os script_n = os.path.basename(__file__).split('.')[0] script_n = script_n.split('_', 1)[1] def to_ng(loc): return (int(loc[0]/4), int(l...
analysis/gen_db/mf_grc/gen_mf_locs_210518.py
4,520
print(mfs_locs[mf]); asdf white list for big boutons bouton_synapse_threshold = 6 safe for determining big bouton locations 4 is a bit iffy, since it has some semi big boutons bouton_synapse_threshold = 6 this threshold has quite a bit of FPs max dist set to 8um dbscan = DBSCAN(eps=10000, min_samples=2) max dist ...
433
en
0.750874
# third-party from flask import render_template, url_for, request, jsonify # locals from . import warehouse @warehouse.route('/element_types', methods=['GET']) def index(): return render_template("warehouse/element_types.html") @warehouse.route('/element_type', methods=['POST']) def create_new_element_type(): ...
warehouse/views.py
710
third-party locals @warehouse.route('/element_type', methods=['GET']) @warehouse.route('/element_type/<element_type_id>', methods=['GET']) def element_type(element_type_id=None): pass @warehouse.route('/element_type', methods=['POST']) def new_element_type()
262
en
0.114816
# copyright (c) 2018 paddlepaddle authors. all rights reserved. # # licensed under the apache license, version 2.0 (the "license"); # you may not use this file except in compliance with the license. # you may obtain a copy of the license at # # http://www.apache.org/licenses/license-2.0 # # unless required by app...
python/paddle/fluid/contrib/slim/tests/test_quantization_pass.py
29,224
copyright (c) 2018 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...
984
en
0.808731
#!/usr/bin/envpython # -*- coding: utf-8 -*- def black(string): return'\033[30m'+string+'\033[0m' def blue(string): return'\033[94m'+string+'\033[0m' def gray(string): return'\033[1;30m'+string+'\033[0m' def green(string): return'\033[92m'+string+'\033[0m' def cyan(string): return'\033[96m'+str...
utils/color.py
749
!/usr/bin/envpython -*- coding: utf-8 -*-
41
en
0.402683
import cProfile import json import logging import os import pstats import signal import tempfile import time import traceback from django.conf import settings from django.utils.timezone import now as tz_now from django.db import DatabaseError, OperationalError, connection as django_connection from django.db.utils impo...
awx/main/dispatch/worker/callback.py
8,699
A worker implementation that deserializes callback event data and persists it into the database. The code that *generates* these types of messages is found in the ansible-runner display callback plugin. buffer stat recording to once per (by default) 5s if an exception occurs, we should re-attempt to save the events ...
863
en
0.92048
from flask import render_template, flash, redirect, url_for, request from flask.views import MethodView from app.middleware import auth from app.models.user import User from app.validators.register_form import RegisterForm from app.services import avatar_service class RegisterController(MethodView): @auth.optional...
app/controllers/auth/register.py
1,193
Show register form Returns: Register template with form Handle the POST request and sign up the user if form validation passes Returns: A redirect or a template with the validation errors
193
en
0.679072
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # """ """ from abc import ABC, abstractproperty, abstractmethod class AbstractType(ABC): @abstractproperty def length(self): pass @abstractmethod def __call__...
cbexplorer/types/AbstractType.py
417
!/usr/bin/env python3 -*- coding: utf-8 -*- Copyright 2020- IBM Inc. All rights reserved SPDX-License-Identifier: Apache2.0
123
en
0.32005
""" Copyright (C) 2018-2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
tools/calibration/process_dataset_callbacks/collect_results_callback.py
3,160
Copyright (C) 2018-2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing...
568
en
0.857326
from django.shortcuts import render from wiki.models import Page from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.shortcuts import get_object_or_404,render class PageList(ListView): """ This view grabs all the pages out of the database returns a...
wiki/views.py
1,034
This view returns a page for a unique wiki using it's slug as an identifier or a 404 message if the page does not exist This view grabs all the pages out of the database returns a list of each unique wiki page for the user to access on the website through 'list.html' Returns a list of wiki pages.
297
en
0.68909
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
stock_trading_backend/agent/neural_network_model.py
3,829
Torch neural network model. Neural netowrk model class. Initializer for linear model. Args: num_inputs: the dimension of input data. num_hidden_layers: the number of hidden layers. num_inner_features: the number of features in the hidden layers Initializer for model class. Args: learning_rat...
1,176
en
0.735824
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
plugins/modules/oci_waas_access_rules_facts.py
19,748
Supported operations: list !/usr/bin/python Copyright (c) 2020, 2021 Oracle and/or its affiliates. This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) Apache License v2.0 See ...
410
en
0.747432
import enum import warnings from optuna import exceptions from optuna import logging from optuna import type_checking if type_checking.TYPE_CHECKING: from datetime import datetime # NOQA from typing import Any # NOQA from typing import Dict # NOQA from typing import Optional # NOQA from optun...
optuna/structs.py
11,497
Status and results of a :class:`~optuna.trial.Trial`. Attributes: number: Unique and consecutive number of :class:`~optuna.trial.Trial` for each :class:`~optuna.study.Study`. Note that this field uses zero-based numbering. state: :class:`TrialState` of the :class:`~optuna.trial.Trial`. ...
4,290
en
0.609432
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class UsageP...
sdk/python/pulumi_aws/apigateway/usage_plan.py
9,677
Provides an API Gateway Usage Plan. ## Example Usage ```python import pulumi import pulumi_aws as aws myapi = aws.apigateway.RestApi("myapi") dev = aws.apigateway.Deployment("dev", rest_api=myapi.id, stage_name="dev") prod = aws.apigateway.Deployment("prod", rest_api=myapi.id, stage_name="prod") my...
4,696
en
0.58603
# -*- coding: utf-8 -*- """Tests for NullTask plugin.""" import unittest from pomito.plugins.task import nulltask, TaskPlugin class NullTaskTests(unittest.TestCase): """Tests for NullTask.""" def setUp(self): self.task = nulltask.NullTask(None) def test_nulltask_is_a_task_plugin(self): ...
tests/plugins/task/test_nulltask.py
802
Tests for NullTask. Tests for NullTask plugin. -*- coding: utf-8 -*-
70
en
0.492654
#!/usr/bin/python # Copyright (c) 2017, 2020 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
plugins/modules/oci_network_ip_sec_connection_device_status_facts.py
6,476
Supported operations: get !/usr/bin/python Copyright (c) 2017, 2020 Oracle and/or its affiliates. This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) Apache License v2.0 See L...
409
en
0.758759
from plotly_study.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Font(_BaseTraceHierarchyType): # color # ----- @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#f...
plotly_study/graph_objs/streamtube/hoverlabel/__init__.py
11,103
Construct a new Font object Sets the font used in hover labels. Parameters ---------- arg dict of properties compatible with this constructor or an instance of plotly_study.graph_objs.streamtube.hoverlabel.Font color colorsrc Sets the source reference on plot.ly for color . family HTML font fami...
5,471
en
0.570346
class MGDHCPSettings(object): def __init__(self, session): super(MGDHCPSettings, self).__init__() self._session = session def getNetworkCellularGatewaySettingsDhcp(self, networkId: str): """ **List common DHCP settings of MGs** https://developer.cisco.com/meraki/api/...
meraki/api/mg_dhcp_settings.py
1,884
**List common DHCP settings of MGs** https://developer.cisco.com/meraki/api/#!get-network-cellular-gateway-settings-dhcp - networkId (string) **Update common DHCP settings of MGs** https://developer.cisco.com/meraki/api/#!update-network-cellular-gateway-settings-dhcp - networkId (string) - dhcpLeaseTime (string): DHC...
709
en
0.636551
"""Config Port Stats message tests.""" from pyof.v0x04.controller2switch.common import PortStats from tests.test_struct import TestStruct class TestPortStats(TestStruct): """Config Port Stats message tests.""" @classmethod def setUpClass(cls): """Configure raw file and its object in parent class ...
build/lib/tests/v0x04/test_controller2switch/test_port_stats.py
511
Config Port Stats message tests. Configure raw file and its object in parent class (TestDump). Config Port Stats message tests.
127
en
0.555224
"""Report routes.""" import os from urllib import parse import bottle import requests from pymongo.database import Database from database import sessions from database.datamodels import latest_datamodel from database.measurements import recent_measurements_by_metric_uuid from database.reports import insert_new_repor...
components/server/src/routes/report.py
6,123
Return all subjects and metrics that have the tag. Delete a report. Download the report as pdf. Get a report with all metrics that have the specified tag. Set a report attribute. Copy a report. Import a preconfigured report into the database. Add a new report. Report routes. Set pdf scale to 70% or otherwise the dash...
344
en
0.846093
# Copyright 2019 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, ...
third_party/augment_ops.py
13,825
Implements Autocontrast function from PIL using TF ops. Implements blend of autocontrast with original image. Blend image1 and image2 using 'factor'. A value of factor 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values be...
5,429
en
0.812088
""" Scrape quotes, books and authors from ``Good Reads`` website. """ import bs4 from .utils import * def get_author_name(soup): """Get the author's name from its main page. Args: soup (bs4.element.Tag): connection to the author page. Returns: string: name of the author. Examples::...
scrapereads/scrape.py
11,987
Get the author ``<a>`` element from a table ``<tr>`` element. Args: book_tr (bs4.element.Tag): ``<tr>`` book element. Returns: bs4.element.Tag: author name ``<a>`` element. Examples:: >>> for book_tr in scrape_author_books(soup): ... book_author = get_author_book_author(book_tr) ... print...
5,867
en
0.657749
from pyspark.sql import Column, DataFrame, SparkSession, functions from pyspark.sql.functions import * from py4j.java_collections import MapConverter from delta.tables import * import shutil import threading tableName = "tbltestpython" # Enable SQL/DML commands and Metastore tables for the current spark session. # W...
examples/python/quickstart_sql.py
2,663
Enable SQL/DML commands and Metastore tables for the current spark session. We need to set the following configs Clear any previous runs Create a table Read the table Upsert (merge) new data Update table data Update every even value by adding 100 to it Delete every even value Read old version of data using time travel ...
327
en
0.781274
"""Welcome to MLToolset, a package to simplify machine learning research! Author: Ryan Eloff Contact: ryan.peter.eloff@gmail.com Date: May 2018 """ from . import data from . import nearest_neighbour from . import neural_blocks from . import siamese from . import training from . import utils from ._globals import T...
src/mltoolset/__init__.py
417
Welcome to MLToolset, a package to simplify machine learning research! Author: Ryan Eloff Contact: ryan.peter.eloff@gmail.com Date: May 2018
141
en
0.679663
""" This file implements the signature scheme from "Unique Ring Signatures: A Practical Construction" by Matthew Franklin and Haibin Zhang """ import sys import math from random import randint import hashlib from libsig.AbstractRingSignatureScheme import AbstractRingSignatureScheme #from AbstractRingSignatureScheme im...
libsig/FZZ_unique_ring_signature.py
9,481
| output: pp = (lamdba, q, G, H, H2) with, | q is prime, | g is generator of G, | G is multiplicative Group with prime order q, | H1 and H2 are two Hash functions H1: {0,1}* -> G, | (as well as H2: {0,1}* -> Zq which is the same). This is the "function to find divisors in order to find generators" module. This DocTest ...
3,126
en
0.789918
import crcmod from selfdrive.car.hyundai.values import CAR, CHECKSUM hyundai_checksum = crcmod.mkCrcFun(0x11D, initCrc=0xFD, rev=False, xorOut=0xdf) def create_lkas11(packer, car_fingerprint, bus, apply_steer, steer_req, cnt, enabled, lkas11, hud_alert, lane_visible, left_lane_depar...
selfdrive/car/hyundai/hyundaican.py
6,466
"CF_Lkas_LdwsSysState": 3 if steer_req else lane_visible,"CF_Lkas_LdwsLHWarning": lkas11["CF_Lkas_LdwsLHWarning"],"CF_Lkas_LdwsRHWarning": lkas11["CF_Lkas_LdwsRHWarning"],values["CF_Lkas_Bca_R"] = int(left_lane) + (int(right_lane) << 1)values["CF_Lkas_FcwOpt_USM"] = 2 if enabled else 1 FcwOpt_USM 5 = Orange blinking ca...
935
en
0.583977
""" Current-flow betweenness centrality measures for subsets of nodes. """ # Copyright (C) 2010-2011 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __all_...
networkx/algorithms/centrality/current_flow_betweenness_subset.py
9,545
Compute current-flow betweenness centrality for subsets of nodes. Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to betweenness centrality which uses shortest paths. Current-flow betweenness centrality is also known as random-walk betweenness centrality [2]_...
5,201
en
0.800813
# Generated by Django 3.1.4 on 2021-09-28 13:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='payment', name='paystack_response', ),...
apps/store/migrations/0002_remove_payment_paystack_response.py
327
Generated by Django 3.1.4 on 2021-09-28 13:49
45
en
0.687631
#!/usr/bin/python3 import functools from copy import deepcopy from .grammar import BASE_NODE_TYPES class NodeBase: """Represents a node within the solidity AST. Attributes: depth: Number of nodes between this node and the SourceUnit offset: Absolute source offsets as a (start, stop) tuple ...
solcast/nodes.py
9,868
Represents a node within the solidity AST. Attributes: depth: Number of nodes between this node and the SourceUnit offset: Absolute source offsets as a (start, stop) tuple contract_id: Contract ID as given by the standard compiler JSON fields: List of attributes for this node Get childen nodes of this ...
2,486
en
0.836349
#!/usr/bin/env python # -*- coding: utf-8 -*- from multiprocessing import Pool import requests PROCESS_POOL_SIZE = 10 REQUESTS = 10000 BASE_URL = "http://localhost:8888" RESOURCE_NAME = "resource" def f(process_number): resource_name = RESOURCE_NAME raw_body = '{"title": "%i", "lifetime": 300, "wait": 20}' ...
tests/bomb1.py
817
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Splits the gencost variable into two pieces if costs are given for Qg. """ from sys import stderr from numpy import array, arange def pqcost(gencost, ng, on...
pandapower/pypower/pqcost.py
1,210
Splits the gencost variable into two pieces if costs are given for Qg. Checks whether C{gencost} has cost information for reactive power generation (rows C{ng+1} to C{2*ng}). If so, it returns the first C{ng} rows in C{pcost} and the last C{ng} rows in C{qcost}. Otherwise, leaves C{qcost} empty. Also does some error c...
723
en
0.829125
""" Full assembly of the parts to form the complete network """ import torch.nn.functional as F from .unet_parts import * from .channels import C class UNet3D(nn.Module): def __init__(self, n_channels, n_classes, bilinear=True, apply_sigmoid_to_output=False): super(UNet3D, self).__init__() self....
pytorch/unet_3d/unet_model.py
1,376
Full assembly of the parts to form the complete network switch do Double CONV if stick do 8x spatial down
108
en
0.696753
# 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 # distributed u...
neutron/conf/policies/security_group.py
6,444
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 distributed under the License ...
761
en
0.830217
import re find_image_scheme = re.compile(r'(?P<image_construction><img\b[^>]*src="(?P<image_url>[^"]+?)"[^>]*?\/>)') # find_link_around_image_scheme = re.compile(r"<a\b[^>]*>(.*?)<img\b(.*?)<\/a>") def move_image_to_attachment(content, attachment_object): # collect images from the post body intext_image_l...
rssbot/utils.py
758
find_link_around_image_scheme = re.compile(r"<a\b[^>]*>(.*?)<img\b(.*?)<\/a>") collect images from the post body delete images form text insert link to image into attachments
174
en
0.760214
import numpy as np import matplotlib.pyplot as plt import gym import random # hyper parameters # test 1 # alpha = 0.5 # gamma = 0.95 # epsilon = 0.1 epsilon = 0.1 alpha = 0.1 gamma = 0.1 def update_sarsa_table(sarsa, state, action, reward, next_state, next_action, alpha, gamma): ''' update sarsa state-action...
TD/double_q_learning.py
5,010
epsilon greedy policy for q learning to generate actions epsilon greedy policy for q learning to generate actions update sarsa state-action pair value, main difference from q learning is that it uses epsilon greedy policy return action hyper parameters test 1 alpha = 0.5 gamma = 0.95 epsilon = 0.1 corresponding ...
1,539
en
0.561277
""" Meta Data Extension for Python-Markdown ======================================= This extension adds Meta Data handling to markdown. See <https://Python-Markdown.github.io/extensions/meta_data> for documentation. Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com). All changes Copyright 200...
venv/lib/python3.6/site-packages/markdown/extensions/meta.py
2,395
Meta-Data extension for Python-Markdown. Get Meta-Data. Add MetaPreprocessor to Markdown instance. Parse Meta-Data and store in Markdown.Meta. Meta Data Extension for Python-Markdown ======================================= This extension adds Meta Data handling to markdown. See <https://Python-Markdown.github.io/...
672
en
0.442522
from datetime import datetime, timedelta from typing import List, Optional from django.conf import settings from django.core.cache import cache from django.utils.translation import ugettext as _ from celery.schedules import crontab from celery.task import periodic_task, task from celery.utils.log import get_task_logg...
corehq/apps/data_interfaces/tasks.py
8,651
type: Literal['resend', 'cancel', 'requeue'] 3.8+ type: Literal['resend', 'cancel', 'requeue'] 3.8+
103
en
0.134853
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from hermes_python.hermes import Hermes INTENT_HOW_ARE_YOU = "mikpan:how_are_you" INTENT_GOOD = "bezzam:feeling_good" INTENT_BAD = "bezzam:feeling_bad" INTENT_ALRIGHT = "bezzam:feeling_alright" INTENT_FILTER_FEELING = [INTENT_GOOD, INTENT_BAD, INTENT_ALRIGHT] def main(...
V2_action-how-are-you.py
1,518
!/usr/bin/env python2 -*- coding: utf-8 -*-
43
en
0.380934
"""Python 3.9.5""" import cv2 import HandTrackingModule as htm def thumbIncrementCheck(lmList: list[list[int]]) -> int: """Checks whether your thumb is up or not. No matter what hand you use. returns 1 if thumb is up else 0""" count = 0 t_x = lmList[4][1] p_x = lmList[17][1] if t_x > p_x:...
forOutput.py
2,606
Returns an appropriate text output depending on `count` and `cc`. Checks whether your thumb is up or not. No matter what hand you use. returns 1 if thumb is up else 0 Python 3.9.5 If true: RIGHT hand ELse: LEFT hand cap = cv2.VideoCapture(0) opens the camera If a hand is not detected value will be 0 else non-zero ...
655
en
0.688529
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
python/mxnet/gluon/nn/basic_layers.py
15,431
Applies an activation function to input. Parameters ---------- activation : str Name of activation function to use. See :func:`~mxnet.ndarray.Activation` for available choices. Input shape: Arbitrary. Output shape: Same shape as input. Batch normalization layer (Ioffe and Szegedy, 2014). Normalizes ...
6,294
en
0.713549
import numpy as np np.random.seed(0) from bokeh.io import curdoc from bokeh.layouts import widgetbox, row, column from bokeh.models import ColumnDataSource, Select, Slider from bokeh.plotting import figure from bokeh.palettes import Spectral6 from sklearn import cluster, datasets from sklearn.neighbors import kneighb...
examples/app/clustering/main.py
6,043
define some helper functions normalize dataset for easier parameter selection estimate bandwidth for mean shift connectivity matrix for structured Ward make connectivity symmetric Generate the new colors: set up initial data set up plot (styling in theme.yaml) set up widgets set up callbacks set up layout add to docume...
322
en
0.546946
import csv source_file = "Resources/budget_data.csv" output_file = "Resources/budget_data_analysis.txt" #initialize months counter, total income, decrease and increase in revenue amounts number_of_months = 0 # to track the total number of months income_total = 0 #variable to hold total income as we iterate through t...
PyBank/main.py
2,924
initialize months counter, total income, decrease and increase in revenue amounts to track the total number of monthsvariable to hold total income as we iterate through the csvvariable to hold previously eveluated value from csv list to hold the greatest profit increase, inaitialized to lowest value 0list to hold the g...
809
en
0.852688
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
WebKit/Tools/Scripts/webkitpy/layout_tests/layout_package/json_results_generator.py
25,303
Copyright (C) 2010 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following discla...
3,754
en
0.870698
################################################################################ # # MIT License # # Copyright (c) 2020 Advanced Micro Devices, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # ...
igemm_codegen.py
5,531
MIT License Copyright (c) 2020 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,...
1,311
en
0.816655
from __future__ import unicode_literals from boto.ec2.instancetype import InstanceType from moto.core.responses import BaseResponse from moto.core.utils import camelcase_to_underscores from moto.ec2.utils import instance_ids_from_querystring, filters_from_querystring, \ dict_from_querystring, optional_from_querystr...
moto/ec2/responses/instances.py
28,296
Handles requests which are generated by code similar to: instance.modify_attribute('blockDeviceMapping', {'/dev/sda1': True}) The querystring contains information similar to: BlockDeviceMapping.1.Ebs.DeleteOnTermination : ['true'] BlockDeviceMapping.1.DeviceName : ['/dev/sda1'] For now we only support t...
552
en
0.859155
import urllib.parse from functools import partial, wraps from pathlib import Path from drfs import config from drfs.util import prepend_scheme, remove_scheme def get_fs(path, opts=None, rtype="instance"): """Helper to infer filesystem correctly. Gets filesystem options from settings and updates them with gi...
drfs/filesystems/util.py
3,791
Allow methods to receive pathlib.Path objects. Parameters ---------- func: callable function to decorate must have the following signature self, path, *args, **kwargs Returns ------- wrapper: callable Helper to infer filesystem correctly. Gets filesystem options from settings and updates them with given `opt...
806
en
0.735791
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
tests/cli/commands/test_plugins_command.py
5,043
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file...
825
en
0.868997
"""Conversion tool from SQD to FIF. RawKIT class is adapted from Denis Engemann et al.'s mne_bti2fiff.py. """ # Authors: Teon Brooks <teon.brooks@gmail.com> # Joan Massich <mailsik@gmail.com> # Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) from collections import defaul...
venv/lib/python3.8/site-packages/mne/io/kit/kit.py
41,874
Epochs Array object from KIT SQD file. Parameters ---------- input_fname : str Path to the sqd file. events : str | array, shape (n_events, 3) Path to events file. If array, it is the events typically returned by the read_events function. If some events don't match the events of interest as specified b...
14,252
en
0.814151
#!/usr/bin/python3 # --- 001 > U5W2P1_Task6_w1 def solution( n ): if(n > 2 and n < 7 ): return True; else: return False; if __name__ == "__main__": print('----------start------------') n = 10 print(solution( n )) print('------------end------------')
src/CodeLearn/plaintextCode/BloomTech/BTU5W1/U5W1P2_Task6_w1.py
292
!/usr/bin/python3 --- 001 > U5W2P1_Task6_w1
43
en
0.218291
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\objects\gardening\gardening_commands.py # Compiled at: 2017-11-18 00:09:10 # Size of source mod 2**3...
Scripts/simulation/objects/gardening/gardening_commands.py
1,362
uncompyle6 version 3.7.4 Python bytecode 3.7 (3394) Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] Embedded file name: T:\InGame\Gameplay\Scripts\Server\objects\gardening\gardening_commands.py Compiled at: 2017-11-18 00:09:10 Size of source mod 2**32: 1465 byte...
321
en
0.460865
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2015-2016 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
xsocs/gui/project/ScanPositionsItem.py
3,495
coding: utf-8 /* Copyright (c) 2015-2016 European Synchrotron Radiation Facility Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,...
1,104
en
0.870883
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2022/2/9 12:09 下午 # @Author: zhoumengjie # @File : tabledrawer.py import numpy as np import pandas as pd from matplotlib import pyplot as plt from matplotlib.font_manager import FontProperties def draw_table(columns_head:[], cell_vals=[]): # 设置字体及负数 plt...
wxcloudrun/common/tabledrawer.py
2,969
!/usr/bin/env python -*- coding:utf-8 -*- @Time : 2022/2/9 12:09 下午 @Author: zhoumengjie @File : tabledrawer.py 设置字体及负数 画布 数据 列与行 作图参数 设置颜色 柱状图 设置标题 显示数据标签 ax.bar_label(bar1, label_type='edge') ax.bar_label(bar2, label_type='edge') x,y刻度不显示 draw_table(['A', 'B'], [['中国', '必胜'], ['你好', '谢谢']]) print(4800 / 1100 / 1000...
343
zh
0.48027
from .TapChanger import TapChanger class RatioTapChanger(TapChanger): ''' A tap changer that changes the voltage ratio impacting the voltage magnitude but not the phase angle across the transformer. :tculControlMode: Specifies the regulation control mode (voltage or reactive) of the RatioTapChanger. Default: None...
cimpy/cgmes_v2_4_15/RatioTapChanger.py
1,623
A tap changer that changes the voltage ratio impacting the voltage magnitude but not the phase angle across the transformer. :tculControlMode: Specifies the regulation control mode (voltage or reactive) of the RatioTapChanger. Default: None :stepVoltageIncrement: Tap step increment, in per cent of nominal voltage, per...
519
en
0.663309
import torch import math from torch import nn, Tensor from torch.nn import functional as F from semseg.models.backbones import * from semseg.models.modules.common import ConvModule class SpatialPath(nn.Module): def __init__(self, c1, c2) -> None: super().__init__() ch = 64 self.conv_7x7 =...
semseg/models/bisenetv1.py
6,206
4x256x64x128, 4x512x32x64 4x128x64x128 4x128x32x64 4x128x1x1 4x128x32x64 4x128x32x64 4x128x64x128 4x128x64x128 4x128x64x128 4x128x128x256 4x128x128x256 4x3x1024x2048 4x128x128x256 4x128x128x256, 4x128x64x128 4x256x128x256 4xn_classesx1024x2048 4xn_classesx1024x2048 4xn_classesx1024x2048 model.init_pret...
371
en
0.25245
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
datalad/utils.py
87,210
Helper for a file entry in the create_tree/@with_tree It allows to define additional settings for entries Filter class to reject all records string.Formatter subclass with special behavior for sequences. This class delegates formatting of individual elements to another formatter object. Non-list objects are ...
34,521
en
0.81922
""" ORY Keto A cloud native access control server providing best-practice patterns (RBAC, ABAC, ACL, AWS IAM Policies, Kubernetes Roles, ...) via REST APIs. # noqa: E501 The version of the OpenAPI document: v0.0.0 Contact: hi@ory.sh Generated by: https://openapi-generator.tech """ import re # ...
clients/keto/python/ory_keto_client/model/delete_ory_access_control_policy_internal_server_error.py
7,071
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the a...
3,783
en
0.771459
from io import BytesIO from uniborg import util from telethon import types from telethon.errors import PhotoInvalidDimensionsError from telethon.tl.functions.messages import SendMediaRequest @borg.on(util.admin_cmd(r"^\.i$")) async def on_file_to_photo(event): await event.delete() target = await event.get_r...
stdplugins/file to img.py
1,199
This isn't an image Telegram doesn't let you directly send stickers as photos We'd get PhotoSaveFileInvalidError otherwise
122
en
0.927613
#!/bin/python import json import re import sys from datetime import datetime import dateutil.parser from dateutil.tz import tzutc from six.moves import range from mtools.util.pattern import json2pattern class DateTimeEncoder(json.JSONEncoder): """Custom datetime encoder for json output.""" def default(se...
mtools/util/logevent.py
32,665
Custom datetime encoder for json output. Extract information from log line and store properties/variables. line_str: the original line string split_tokens: a list of string tokens after splitting line_str using whitespace as split points datetime: a datetime object for the logevent. For logfiles created ...
5,646
en
0.758627
# -*- coding: utf-8 -*- """ Calculation of cumulant expressions for non-linear response functions of the third order for a multilevel three band system. """ from quantarhei.symbolic.cumulant import Ugde, Uedg, Uged, Uegd #, ExpdV from quantarhei.symbolic.cumulant import gg #, g1, g2 from quantarhei.symbolic.cumulan...
examples/symbolic/test_symbolic_8.py
8,025
Calculation of cumulant expressions for non-linear response functions of the third order for a multilevel three band system. -*- coding: utf-8 -*-, ExpdV, g1, g2, e, t, T, tau, x, ya = leading_index[0]A = (Uedg(a,t1+tau)*Ugde(b,t1+tau)*Uedg(b,t1+t2)*Ugde(b,t1+t2+t3) *Uedg(b,t1+tau)*Ugde(a,t1+tau)*Uedg(a,t1))A = (U...
1,873
en
0.354115
# This example is inspired by https://github.com/dasguptar/treelstm.pytorch import argparse, cPickle, math, os, random import logging logging.basicConfig(level=logging.INFO) import numpy as np from tqdm import tqdm import mxnet as mx from mxnet import gluon from mxnet.gluon import nn from mxnet import autograd as ag ...
example/gluon/tree_lstm/main.py
6,757
This example is inspired by https://github.com/dasguptar/treelstm.pytorch read dataset get network use pearson correlation and mean-square error for evaluation when evaluating in validation mode, check and see if pearson-r is improved if so, checkpoint and run evaluation on test dataset initialization with context set ...
671
en
0.794063
import os import glob import sys from typing import Optional, List, Union from .utils.utils import calc_mean_score, save_json, image_dir_to_json, image_file_to_json from .handlers.model_builder import Nima from deepinsight_iqa.common.utility import thread_safe_singleton, set_gpu_limit from deepinsight_iqa.data_pipeline...
deepinsight_iqa/nima/predict.py
2,273
Invoke a predict method of this class to predict image quality using nima model set_gpu_limit() load samples initialize data generator get predictions calc mean scores and add to samples print(json.dumps(samples, indent=2))
234
en
0.572556
# qubit number=3 # total number=60 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from...
data/p3BR/R2/benchmark/startQiskit_QC292.py
7,009
011 . x + 1 000 . x + 0 111 . x + 1 qubit number=3 total number=60 implement the oracle O_f NOTE: use multi_control_toffoli_gate ('noancilla' mode) https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-...
1,496
en
0.383851
import socket, threading, sys, traceback, os, tkinter from ui import Ui_MainWindow from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5 import QtCore, QtGui, QtWidgets from tkinter import * from PIL import Image, ImageTk from tkinter import messagebox, Tk from PIL import ImageFile ImageFile.LOAD_TRUNCATED_I...
Task2/Client_dev.py
11,439
Connect to the Server. Start a new RTSP/TCP session. Teardown the client. Let movie faster. Handler on explicitly closing the GUI window. Listen for RTP packets. Open RTP socket binded to a specified port. Parse the RTSP reply from the server. Pause movie. Play movie. Receive RTSP reply from the server. Send RTSP reque...
1,787
en
0.777664
""" core app configuration """ import os environment = os.getenv('LAMBTASTIC_ENV', 'development') if environment == 'testing': from .testing import * elif environment == 'production': from .production import * else: from .development import *
settings/__init__.py
257
core app configuration
22
en
0.551515
# -*- coding: utf-8 -*- TIME_OUT = 60 EXCEPT_FILE = ['test.py','login.py','mix.py'] class Api(object): login = "/api/users/login" user_info="/api/users/info" signin = "/api/users/sign/signIn" map = "/api/RedEnvelope/updateUserMap" find_redbag = "/api/RedEnvelope/findReds" get_redbag = "/api/re...
config.py
364
-*- coding: utf-8 -*-
21
en
0.767281
""" Copyright 2020 Inmanta 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 ...
tests/moduletool/test_python_dependencies.py
2,974
Test the code path used by the exporter Copyright 2020 Inmanta 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...
708
en
0.841192
from __future__ import division import fa import sys import os from fa import chunker if __name__ == "__main__": from sys import stderr import argparse parser = argparse.ArgumentParser(description=( "Create a set of synthetic genomes consisting " "of subgroups per tax level. Some kmers are ...
sim/main.py
5,017
Variables/settings for constructing synthetic genome and accessory files. Append slash Variables for constructing the parent_map dictionary. print("seqsubset len: %i" % len(seqsubset), file=stderr) or it not last_layer Add leaf node to parent connections Add higher nodes to parent connections This leaves the loop on th...
511
en
0.663166
# Copyright 2019 The TensorFlow Probability Authors. # # 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...
tensorflow_probability/python/internal/test_combinations_test.py
2,657
Tests generating test combinations. Copyright 2019 The TensorFlow Probability Authors. 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...
783
en
0.829514
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
airflow/executors/celery_executor.py
2,353
airflow worker 执行shell命令 . -*- coding: utf-8 -*- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Ver...
875
en
0.815397
from django.conf.urls import url from . import views app_name = 'reports' urlpatterns = [ # url(r'^graph/', views.graph, name='graph'), url(r'^graph/', views.statistics, name='graph'), url(r'^csv_export/', views.csv_export, name='csv_export'), ]
reports/urls.py
268
url(r'^graph/', views.graph, name='graph'),
44
en
0.704375
"""Preview mixins for Zinnia views""" from django.http import Http404 from django.utils.translation import ugettext as _ class EntryPreviewMixin(object): """ Mixin implementing the preview of Entries. """ def get_object(self, queryset=None): """ If the status of the entry is not PUBLI...
zinnia/views/mixins/entry_preview.py
855
Mixin implementing the preview of Entries. If the status of the entry is not PUBLISHED, a preview is requested, so we check if the user has the 'zinnia.can_view_all' permission or if it's an author of the entry. Preview mixins for Zinnia views
243
en
0.909162
from libs import reaction as reactioncommand class Reaction(reactioncommand.AdminReactionAddCommand): '''Retries a text command **Usage** React to the message you want to re-run with the retry emoji (The emoji is server-defined; ask your fellow server members for the correct emoji)''' def matches(self, react...
retry.py
481
Retries a text command **Usage** React to the message you want to re-run with the retry emoji (The emoji is server-defined; ask your fellow server members for the correct emoji)
178
en
0.893991
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Marc-Olivier Buob, Maxime Raynal" __maintainer__ = "Marc-Olivier Buob, Maxime Raynal" __email__ = "{marc-olivier.buob,maxime.raynal}@nokia.com" __copyright__ = "Copyright (C) 2020, Nokia" __license__ = "BSD-3" from collections imp...
pybgl/prune_incidence_automaton.py
1,763
Returns the set of vertices of a graph which are reachable from a set of source vertices. Args: g: Graph, an instance of `Graph` sources: set, a set of integers representing the source vertices Returns: The set of vertices that are reachable from the source vertices Prunes the vertices of an IncidenceAutoma...
517
en
0.83487
"""Module containing examples of report builder functions and classes.""" from collections import OrderedDict import numpy as np def example_fn_build_report(report, pvarray): """Example function that builds a report when used in the :py:class:`~pvfactors.engine.PVEngine` with full mode simulations. Here ...
pvfactors/report.py
3,158
A class is required to build reports when running calculations with multiprocessing because of python constraints Method that will build the simulation report. Here we're using the previously defined :py:function:`~pvfactors.report.example_fn_build_report`. Parameters ---------- report : dict Initially ``None``, t...
1,488
en
0.74372
# -*- coding: utf-8 -*- """ Created on Mon Apr 27 17:38:25 2020 @author: Wu Yichen """ from PIL import Image import os import os.path import errno import numpy as np import sys import pickle import torch.utils.data as data from torchvision.datasets.utils import download_url, check_integrity impo...
dataloader.py
14,764
returns a matrix with (1 - corruption_prob) on the diagonals, and corruption_prob concentrated in only one other entry for each row returns a matrix with (1 - corruption_prob) on the diagonals, and corruption_prob concentrated in only one other entry for each row returns a linear interpolation of a uniform matrix and a...
1,079
en
0.691974
import os import torch from typing import List from dqc.utils.datastruct import CGTOBasis __all__ = ["loadbasis"] _dtype = torch.double _device = torch.device("cpu") def loadbasis(cmd: str, dtype: torch.dtype = _dtype, device: torch.device = _device, requires_grad: bool = False) -> \ ...
dqc/api/loadbasis.py
4,842
Load basis from a file and return the list of CGTOBasis. Arguments --------- cmd: str This can be a file path where the basis is stored or a string in format ``"atomz:basis"``, e.g. ``"1:6-311++G**"``. dtype: torch.dtype Tensor data type for ``alphas`` and ``coeffs`` of the GTO basis device: torch.device ...
1,104
en
0.756467
import datetime import threading import contextlib import pyotp import qrcode from errbot import BotPlugin, botcmd, arg_botcmd, cmdfilter # OTP expires every hour _OTP_EXPIRE = datetime.timedelta(hours=1) _BASE_TIME = datetime.datetime(year=datetime.MINYEAR, month=1, day=1) class otp(BotPlugin): ''' ...
plugins/otp/otp.py
5,488
Implement One Time Passwords for command filtering. Internal method used to build the QRCode image for token provisioning. Wrapper to make sure the correct identity object is used. Add a command to OTP command filtering. Authenticate with OTP to the bot to pass OTP filtering. List the commands that are filtered by OTP....
858
en
0.888296
""" WSGI config for kweetservice project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_...
kweetservice/kweetservice/wsgi.py
401
WSGI config for kweetservice project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
218
en
0.765512
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. 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 r...
src/transformers/models/convbert/modeling_tf_convbert.py
58,533
Head for sentence-level classification tasks. Construct the embeddings from word, position and token_type embeddings. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to p...
4,768
en
0.808814
""" Third party api wrappers""" import os import json import nexmo import africastalking username = os.getenv('africastalking_username') api_key = os.getenv('africastalking_api_key') africastalking.initialize(username, api_key) sms = africastalking.SMS class ProvidersWrapper: """ Class with all the thirdy party ...
providers.py
745
Class with all the thirdy party helper functions Third party api wrappers
73
en
0.806787
import time import cv2 import numpy as np from collections import defaultdict class Tracker(object): def __init__(self, pLK=None): if pLK is None: # default LK param pLK = self.pLK0() self.lk_ = cv2.SparsePyrLKOpticalFlow_create( **pLK) self.tmp_ = de...
core/track.py
4,984
Arguments: img1(np.ndarray) : previous image. (color/mono) (HxWx?) img2(np.ndarray) : current image (color/mono) (HxWx?) pt1(np.ndarray) : previous points. (Mx2) pt2(np.ndarray) : [Optional] current points estimate (Mx2) thresh(float) : Flow Back-projection Error threshold Returns: pt2(np....
1,113
en
0.401842
from escpos.printer import Usb from pathlib import Path image = Path("/tamamo-no-mae/me-cloudy.png") printer = Usb(0x0416, 0x5011, 0, profile="ZJ-5870") printer.image(image); printer.cut() # with printer() as that: # that.write('Hello, world!\n\n') # # 000000000111111111122222222223 # # 123...
demo.py
759
with printer() as that: that.write('Hello, world!\n\n') 000000000111111111122222222223 123456789012345678901234567890 that.write('Soluta sed voluptatem ut\n') that.write('facere aut. Modi placeat et\n') that.write('eius voluptate sint ut.\n') that.write('Facilis minima ex q...
541
en
0.375138
import operator import numpy import pytest import cupy from cupy import testing class TestArrayElementwiseOp: @testing.for_all_dtypes_combination(names=['x_type', 'y_type']) @testing.numpy_cupy_allclose(rtol=1e-6, accept_error=TypeError) def check_array_scalar_op(self, op, xp, x_type, y_type, swap=Fals...
tests/cupy_tests/core_tests/test_ndarray_elementwise_op.py
27,032
There are some precission issues in HIP that prevent checking with atol=0 TODO(unno): sub for boolean array is deprecated in numpy>=1.13 TODO(unno): sub for boolean array is deprecated in numpy>=1.13 There are some precission issues in HIP that prevent checking with atol=0 Skip float16 because of NumPy 19514 Cast from ...
502
en
0.781484
def read_fasta(filename): """Returns a list of tuples of each header and sequence in a fasta (or multifasta) file. first element in tuple is header and second the sequence. Key Arguments: filename -- fasta file. """ tmp_seq = None seqs_list = [] with open(filename, 'r') as fasta...
pridcon/utils.py
3,354
Returns a list of tuples of each header and sequence in a fasta (or multifasta) file. first element in tuple is header and second the sequence. Key Arguments: filename -- fasta file. This function reads a FASTQ file storing the read and its ID in a dictionary where keys are IDs and read value. This function does n...
1,030
en
0.839018
from django import template from home.models import Recipe, MixingAgent, Base, Ingredient, FacePack, CustomFacePack import pdb register = template.Library() @register.inclusion_tag('facepack.html') def facepack_display(item_id): if not item_id: return mandatory = [] type = "primary" for cfp in...
f2f/farms2face/home/templatetags/common_tags.py
2,013
'base_url' : request.get_raw_uri().replace(request.get_full_path(),''),
75
en
0.194243
# 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/. """ FlowClient is a Python client to FlowAPI. """ from ._version import get_versions __version__ = get_versions()["vers...
flowclient/flowclient/__init__.py
2,963
FlowClient is a Python client to FlowAPI. 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/.
236
en
0.925807
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import requests # Disable insecure warnings requests.packages.urllib3.disable_warnings() API_KEY = demisto.getParam('APIKey') SERVER_URL = 'https://analyze.intezer.com/api' API_VERSION = '/v2-0' BASE_...
Packs/Intezer/Integrations/IntezerV2/IntezerV2.py
9,809
Disable insecure warnings This error is unlikely to happen, as the return code should indicate of error beforehand python2 uses __builtin__ python3 uses builtins
161
en
0.803378
from django.db import models from django.contrib.auth.models import AbstractBaseUser, \ BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if n...
app/core/models.py
1,214
Custom user model that supports using email instead of username Creates and saves a new super user Creates and saves a new user
127
en
0.874647
# Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
ironic/tests/unit/db/test_nodes.py
35,617
Tests for manipulating Nodes via the DB API Copyright 2013 Hewlett-Packard Development Company, L.P. 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...
1,205
en
0.848218
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
python/pyspark/sql/session.py
25,242
Builder for :class:`SparkSession`. The entry point to programming Spark with the Dataset and DataFrame API. A SparkSession can be used create :class:`DataFrame`, register :class:`DataFrame` as tables, execute SQL over tables, cache tables, and read parquet files. To create a SparkSession, use the following bu...
11,426
en
0.527757
""" director subsystem's configuration - config-file schema - settings """ from typing import Dict import trafaret as T from aiohttp import ClientSession, web from yarl import URL from servicelib.application_keys import APP_CLIENT_SESSION_KEY, APP_CONFIG_KEY APP_DIRECTOR_API_KEY = __name__ + ".director_api"...
services/web/server/src/simcore_service_webserver/director/config.py
1,074
director subsystem's configuration - config-file schema - settings storage API version basepath
98
en
0.484274
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-07 15:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion def add_author_to_blog(apps, schema_editor): # pylint: disable=unused-argument """Author is the claimant""" Blog = apps.ge...
lowfat/migrations/0090_auto_20170307_1518.py
1,389
Author is the claimant -*- coding: utf-8 -*- Generated by Django 1.10.5 on 2017-03-07 15:18 pylint: disable=unused-argument pylint: disable=invalid-name
154
en
0.619554
from __future__ import annotations from abc import abstractmethod from typing import Any, Generic, Optional, TypeVar from goodboy.errors import Error from goodboy.messages import DEFAULT_MESSAGES, MessageCollectionType, type_name from goodboy.schema import Rule, SchemaWithUtils N = TypeVar("N") class NumericBase(G...
src/goodboy/types/numeric.py
5,973
Accept ``float`` values. Integer values are converted to floats. When type casting enabled, strings and other values with magic method `__float__ <https://docs.python.org/3/reference/datamodel.html#object.__float__>`_ are converted to floats. :param allow_none: If true, value is allowed to be ``None``. :param message...
1,527
en
0.511337
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A tool to extract a build, executed by a buildbot slave. """ import optparse import os import shutil import sys import tracebac...
scripts/slave/extract_build.py
10,914
!/usr/bin/env python Copyright (c) 2012 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. If builddir isn't specified, assume buildbot used the builder name as the root folder for the build. assume filename not specified Append t...
1,048
en
0.869038
#!/Users/fahmi.abdulaziz/PycharmProjects/tmdb/bin/python3.8 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/l...
bin/fixup_oslogin_v1_keywords.py
6,293
Duplicate the input dir to the output dir, fixing file method calls. Preconditions: * in_dir is a real directory * out_dir is a real, empty directory A stable, out-of-place partition. !/Users/fahmi.abdulaziz/PycharmProjects/tmdb/bin/python3.8 -*- coding: utf-8 -*- Copyright 2020 Google LLC Licensed under the Apache L...
1,428
en
0.848648
# coding:utf-8 from django import forms from django.conf import settings from django.contrib.admin.widgets import AdminTextareaWidget from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.http import urlencode from . import settings as USettings from .comman...
DjangoUeditor/widgets.py
7,260
计算上传路径,允许是function coding:utf-8 修正输入的文件路径,输入路径的标准格式:abc,不需要前后置的路径符号 如果输入的路径参数是一个函数则执行,否则可以拉接受时间格式化,用来生成如file20121208.bmp的重命名格式 width=600, height=300, toolbars="full", imagePath="", filePath="", upload_settings={}, settings={},command=None,event_handler=None 扩展命令 上传路径 保存 以下处理工具栏设置,将normal,mini等模式名称转化为工具栏配置值 raise Valu...
520
zh
0.629573