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 |
|---|---|---|---|---|---|---|
'''
Preprocessor for Foliant documentation authoring tool.
Calls Elasticsearch API to generate an index based on Markdown content.
'''
import re
import json
from os import getenv
from pathlib import Path
from urllib import request
from urllib.error import HTTPError
from markdown import markdown
from bs4 import Beauti... | foliant/preprocessors/elasticsearch.py | 15,822 | Preprocessor for Foliant documentation authoring tool.
Calls Elasticsearch API to generate an index based on Markdown content. | 127 | en | 0.676076 |
"""
Settings for different models.
"""
import attr
@attr.s # pylint: disable=too-many-instance-attributes,too-few-public-methods
class BaseSettings:
"""
Base configuration settings.
"""
val_split = attr.ib(default=0.0)
test_split = attr.ib(default=0.15)
detect_type = attr.ib(default="dual")... | src/pybor/config.py | 2,765 | Base configuration settings.
Entropy model settings.
Markov model settings.
Neural model settings.
Recurrent model settings.
Settings for different models.
pylint: disable=too-many-instance-attributes,too-few-public-methods pylint: disable=too-many-instance-attributes,too-few-public-methods recurrent For Native model... | 780 | en | 0.676754 |
#!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013-2014 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from __future__ import pri... | contrib/linearize/linearize-hashes.py | 3,037 | !/usr/bin/python linearize-hashes.py: List blocks in a linear, no-fork version of the chain. Copyright (c) 2013-2014 The Bitcoin developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. assume replies are in-sequence skip commen... | 349 | en | 0.711358 |
from rest_framework import parsers, renderers, status
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.compat import coreapi, coreschema
from rest_framework.generics import DestroyAPIView, RetrieveAPIView
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from re... | polyaxon/api/users/views.py | 14,377 | Activate user.
Given a valid activation key, activate the user's
account. Otherwise, show an error message stating the account
couldn't be activated.
Login user and return user's token.
Delete user.
Grant a user the superuser role.
Register a new (inactive) user account, generate an activation key and email it to the u... | 1,663 | en | 0.832338 |
# encoding=utf8
"""Implementations of Cosine mixture functions."""
from numpy import cos, pi
from NiaPy.benchmarks.benchmark import Benchmark
__all__ = ['CosineMixture']
class CosineMixture(Benchmark):
r"""Implementations of Cosine mixture function.
Date: 2018
Author: Klemen Berkovič
License: MIT
Function:... | NiaPy/benchmarks/cosinemixture.py | 2,230 | Implementations of Cosine mixture function.
Date: 2018
Author: Klemen Berkovič
License: MIT
Function:
**Cosine Mixture Function**
:math:`f(\textbf{x}) = - 0.1 \sum_{i = 1}^D \cos (5 \pi x_i) - \sum_{i = 1}^D x_i^2`
**Input domain:**
The function can be defined on any input domain but it is... | 1,740 | en | 0.498401 |
# Read PV metadata and timeseries data
# Based on code in https://github.com/openclimatefix/pvoutput
# E.g. https://nbviewer.jupyter.org/github/openclimatefix/pvoutput/blob/master/examples/analyse_PV_data_for_9th_Aug_2019.ipynb
import cartopy.crs as ccrs
import numpy as np
import pandas as pd
import xarray as xr
ME... | predict_pv_yield_nwp/pv.py | 6,414 | Get all the PV system IDs from the timeseries file
Transform the system locations into the same coordinate system used by UKV
Transform the system locations into the same coordinate system used by UKV, using pyproj
Load metadata about PV systems
Load the PV timeseries as an xarray dataset, restricted to a given time ra... | 1,386 | en | 0.823491 |
"""
noxfile
~~~~~~~
Nox configuration script
"""
# pylint: disable=resource-leakage,3rd-party-module-not-gated
import datetime
import glob
import os
import shutil
import sys
import tempfile
# fmt: off
if __name__ == "__main__":
sys.stderr.write(
"Do not execute this file directly. Use nox instead, it wi... | noxfile.py | 35,872 | Python class to mimic linux tee behaviour
Because some python packages are provided by the distribution and cannot
be pip installed, and because we don't want the whole system python packages
on our virtualenvs, we copy the required system python packages into
the virtualenv
Generate salt's changelog
Build Salt's Docum... | 4,344 | en | 0.807577 |
#!/usr/bin/env python3
# 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 contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | classy_vision/tasks/classification_task.py | 49,493 | Basic classification training task.
This task encapsultates all of the components and steps needed to
train a classifier using a :class:`classy_vision.trainer.ClassyTrainer`.
Assumes a train / test phase per each epoch and that the datasets
have the same API as the map-style Dataset class in
`torch.utils.data.dataset... | 11,842 | en | 0.762314 |
"""The tests for day17."""
from days import day17
from ddt import ddt, data, unpack
import unittest
import helpers
@ddt
class MyTestCase(unittest.TestCase): # noqa D101
@data(
[[
'x=495, y=2..7',
'y=7, x=495..501',
'x=501, y=3..7',
'x=498, y=2..4',
... | test/test_day17.py | 1,354 | The tests for day17.
noqa D101 noqa D102 noqa D102 noqa D102 noqa D102 | 72 | gu | 0.384853 |
"""
pyart.lazydict
==============
A dictionary-like class supporting lazy loading of specified keys.
.. autosummary::
:toctree: generated/
:template: dev_template.rst
LazyLoadDict
"""
try:
# Python 3
from collections.abc import MutableMapping
except ImportError:
# Python 2.7, will be remove... | pycwr/configure/pyart_lazydict.py | 4,347 | A dictionary-like class supporting lazy loading of specified keys.
Keys which are lazy loaded are specified using the set_lazy method.
The callable object which produces the specified key is provided as the
second argument to this method. This object gets called when the value
of the key is loaded. After this initial ... | 2,256 | en | 0.785612 |
from apis.creat_account.api_account_setAlias import account_setAlias
from apis.creat_account.api_create_account import create_account, create_account_100
from apis.creat_account.api_get_addresslist import get_address_list
from apis.transfer.blockmgr_sendRawTransaction import sendRawTransaction
from apis.transfer.time_o... | apis/router.py | 2,632 | :param case_name:
:return: 注意格式 xxx(case_name)()
"creat_one_wallet_account": creat_one_wallet_account, API 总函数 | 114 | zh | 0.37862 |
from django.contrib import messages
from django.http import QueryDict
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.contrib.admin.views.decorators import staff_member_required
from django.template.defaulttags import register
from common.exp... | annotationweb/views.py | 22,269 | Check if user has processed any Show only tasks assigned to this user Admin page Classification tasks If only 1 exporter exists for this type, use that one Get unbound form Get unbound form TODO do cleanup after deleting task? Show all datasets Find start_number and total number of frames automatically Start frame can ... | 1,424 | en | 0.729083 |
import copy
import torch
from torch import nn
import numpy as np
from tokens import *
def tokenize(corpus, callback=lambda sent: sent.split()):
return [callback(sent) for sent in corpus]
def add_start_stop_tokens(corpus):
return [[START_TOKEN] + sent + [STOP_TOKEN] for sent in corpus]
def padding(corpus... | nlp_243/hw3/utils.py | 3,927 | Output Processing if is truncated padding if is expanded padding tokenization add special tokens padding functions for creating the embedding layer | 147 | en | 0.292231 |
import numpy as np
'''
dccol : 1-8
dcpad : 1-10
mcecol: 0,1
mcerow: 0-32
'''
#w,h = 10,8
# def det2mce(detcol,detrow,detpol):
# dccol,dcpad = det2dc(detcol,detrow,detpol)
# if dccol<0 or dcpad<0:
# return -1,-1
# mcecol,mcerow = dc2mce(dccol,dcpad)
# return mcecol,mcerow
def mce2det(mcecol,mcerow):
if mcecol... | ba150_ModuleMapping_fake.py | 568 | w,h = 10,8 def det2mce(detcol,detrow,detpol): dccol,dcpad = det2dc(detcol,detrow,detpol) if dccol<0 or dcpad<0: return -1,-1 mcecol,mcerow = dc2mce(dccol,dcpad) return mcecol,mcerowdetcol,detrow,detpol = dc2det(dccol,dcpad)not sure what this is | 251 | en | 0.274345 |
# -*- coding: utf-8 -*-
"""Tests for :mod:`docdata`."""
| tests/__init__.py | 57 | Tests for :mod:`docdata`.
-*- coding: utf-8 -*- | 49 | en | 0.400124 |
from enum import Enum
from .factory import createFromUri
import os
import requests
class Record(object):
"""
Create a Polarion test record,
:param polarion: Polarion client object
:param test_run: Test run instance
:param polarion_record: The data from Polarion of this testrun
:param index: T... | polarion/record.py | 10,697 | Create a Polarion test record,
:param polarion: Polarion client object
:param test_run: Test run instance
:param polarion_record: The data from Polarion of this testrun
:param index: The index of this record in the test run
Record result enum
Upload an attachment
:param file_path: Source file to upload
:param title: ... | 2,541 | en | 0.731466 |
#!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... | src/shotgunEventDaemon.py | 46,186 | A part of a plugin that can be called to process a Shotgun event.
Used when an error is detected in the config file.
A custom SMTPHandler subclass that will adapt it's subject depending on the
error severity.
The engine holds the main loop of event processing.
Base error for the Shotgun event system.
Linux Daemon wrapp... | 8,961 | en | 0.839895 |
"""
Project Euler Problem 7: https://projecteuler.net/problem=7
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
can see that the 6th prime is 13.
What is the 10001st prime number?
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import itertools
import math
def pri... | project_euler/problem_007/sol3.py | 1,222 | Determines whether a given number is prime or not
>>> prime_check(2)
True
>>> prime_check(15)
False
>>> prime_check(29)
True
Generate a sequence of prime numbers
Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
2
>>> solution(3)
5
>>> solution(20)
71
>>> solution(50)
229
>>> solution(100)
541
Project... | 586 | en | 0.688 |
import requests
from collections import OrderedDict
from django.utils.http import urlencode
from allauth.socialaccount.providers.core.oauth2.client import (
OAuth2Client,
OAuth2Error,
)
class WeixinOAuth2Client(OAuth2Client):
def get_redirect_url(self, authorization_url, extra_params):
params =... | allauth/socialaccount/providers/other/weixin/client.py | 1,813 | TODO: Proper exception handling | 31 | es | 0.211752 |
# ---------------------------------------------------------------------
# Rotek.BT.get_metrics
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# NOC module... | sa/profiles/Rotek/BT/get_metrics.py | 3,526 | --------------------------------------------------------------------- Rotek.BT.get_metrics --------------------------------------------------------------------- Copyright (C) 2007-2020 The NOC Project See LICENSE for details --------------------------------------------------------------------- NOC modules SNMP version ... | 358 | en | 0.196884 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chrome_path = r"C:\Users\iamdo\Downloads\chromedriver.exe" # specify your driver location
driver = webdriver.Chrome(chrome_path)
driver.get("https://github.com/login")
username = "your email" # specify your email
passwor... | github.py | 1,294 | specify your driver location specify your email specify your password specify your repository name | 98 | bn | 0.06914 |
from django.contrib import admin
from .models import Post
#pythonadmin.site.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ("pk","text", "pub_date", "author")
search_fields = ("text",)
list_filter = ("pub_date",)
empty_value_display = "-пусто-"
admin.site.register(Post, PostAdmin... | yatube/posts/admin.py | 328 | pythonadmin.site.register(Post) | 31 | en | 0.208742 |
import asyncio
from typing import List
from app.common import SkipListing
from app.scrapers.base import BaseScraper
class MaartenScraper(BaseScraper):
MAKELAARDIJ: str = "maarten"
BASE_URL: str = "https://www.maartenmakelaardij.nl"
# Specific functions
async def extract_object_urls(self, soup) -> L... | server/app/scrapers/maarten.py | 3,199 | Extract feature metadata from listing
Specific functions Features Other fields Bounce broken listings | 103 | en | 0.768303 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | lims/addressbook/migrations/0001_initial.py | 1,034 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artemis.settings')
from django.conf import settings
app = Celery('artemis')
app.config_from_object('djang... | artemis/celery.py | 551 | set the default Django settings module for the 'celery' program. Load task modules from all registered Django app configs. | 122 | en | 0.362336 |
import logging
import json
import paho.mqtt.client as mqttc
from ioctlgw import version
from ioctlgw.componentstate import ComponentState
LOG = logging.getLogger(__name__)
class MqttConnector(object):
def __init__(self, service):
self.service = service
self.config = self.service.config
s... | ioctlgw/mqttconnector.py | 4,395 | MQTT status jobs Start a background thread to maintain the MQTT connection Subscribe to interesting MQTT topics TODO: check number of parts | 139 | en | 0.697205 |
from tithiwa import *
tithiwabot = Tithiwa()
tithiwabot.open_session()
print("'" + tithiwabot.get_my_name() + "', '" + tithiwabot.get_my_about() + "'")
tithiwabot.quit()
browser = 3
#doing something else with browser
tithiwabot = Tithiwa(browser)
tithiwabot.browser = webdriver.Chrome()
tithiwabot.open_session()
print... | tithiwa/temp.py | 414 | doing something else with browser | 33 | en | 0.905629 |
from flask import Flask
from flask import make_response
from flask import render_template
from flask import request
from flask import session
from blog_site.common.database import Database
from blog_site.webapp.models.blog import Blog
from blog_site.webapp.models.user import User
app = Flask(__name__)
app.secret_key ... | blog_site/webapp/web_app.py | 3,269 | mismatch passwords TODO: Insert validation error TODO: User should be authenticated first before navigating to the post | 119 | en | 0.575734 |
# Copyright 2019 Extreme Networks, 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 i... | orquesta/constants.py | 835 | Copyright 2019 Extreme Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwar... | 559 | en | 0.862032 |
import time
from grapht.graph import DictGraph, StreamGraph
__author__ = 'willmcginnis'
if __name__ == '__main__':
print('DictGraph')
g = {0: [2], 1: [2, 3], 2: [1, 3], 3: [1, 2, 4, 6], 4: [3, 5], 5: [4, 6, 7], 6: [3, 4, 5], 7: [5, 8], 8: [7], 9: [8], 10: [9], 11: [8, 9], 12: [11], 13: [12], 14: [13], 15: [1]... | examples/adjacency.py | 1,317 | NOTE: You'll need a graph in a postgres db to actually do this. | 63 | en | 0.977025 |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class AuditEvent_EntitySchema:
"""
A record of an event made for purposes of mai... | spark_fhir_schemas/stu3/complex_types/auditevent_entity.py | 11,448 | A record of an event made for purposes of maintaining a security log. Typical
uses include detection of intrusion attempts and monitoring for inappropriate
usage.
A record of an event made for purposes of maintaining a security log. Typical
uses include detection of intrusion attempts and monitoring for inappropriate
u... | 2,970 | en | 0.893216 |
# Standard library
from unittest import mock
# Third-party
import polib
from django.test import TestCase, override_settings
from django.utils.translation import override
# First-party/Local
from i18n import DEFAULT_LANGUAGE_CODE
from licenses import FREEDOM_LEVEL_MAX, FREEDOM_LEVEL_MID, FREEDOM_LEVEL_MIN
from license... | licenses/tests/test_models.py | 30,759 | 3.0 formula:
/licenses/VERSION/JURISDICTION/LICENSE_deed_LANGAUGE.html
/licenses/VERSION/JURISDICTION/LICENSE_legalcode_LANGAUGE.html
3.0 examples:
/licenses/3.0/xu/by_deed_en.html
/licenses/3.0/xu/by_legalcode_en.html
/licenses/3.0/am/by_deed_hy.html
/licenses/3.0/am/by_legalcode_hy.html
/licenses/3.0/rs/by_deed_rs-C... | 3,004 | en | 0.352811 |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | magenta/models/rl_tuner/rl_tuner_ops.py | 9,922 | Gives the correlation coefficient for the signal's correlation with itself.
Args:
signal: The signal on which to compute the autocorrelation. Can be a list.
lag: The offset at which to correlate the signal with itself. E.g. if lag
is 1, will compute the correlation between the signal and itself 1 beat
late... | 4,978 | en | 0.819911 |
# -*- coding: utf-8 -*-
'''SRFax (www.srfax.com) python library'''
import re
import os.path
import base64
import logging
import requests
URL = 'https://www.srfax.com/SRF_SecWebSvc.php'
LOGGER = logging.getLogger(__name__)
RE_E164 = re.compile(r'^\+\d{7,15}$') # TODO: Replace this with phonenumberslite?
RE_NANP... | srfax/srfax.py | 9,351 | SRFax class
SRFax Exception
Delete fax files from server
Get exception cause
Get exception error code
Get fax inbox
Get fax outbox
Get fax status
Read and return file content Base64 encoded
Get retry option (should we retry the request?)
Simple check if number is in E.164 format
Simple check if number is inside North A... | 796 | en | 0.657561 |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/player/city/shared_hospital_corellia.iff"
result.attribute_template... | data/scripts/templates/object/building/player/city/shared_hospital_corellia.py | 455 | NOTICE: THIS FILE IS AUTOGENERATED MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES BEGIN MODIFICATIONS END MODIFICATIONS | 168 | en | 0.698026 |
from MoveGetter import MoveGetter
import chess
class CommandLineMoveGetter(MoveGetter):
def getMove(self, board):
print("\n")
print(board)
self.printLegalMoves(board)
return self.getMoveFromCLI(board)
def printLegalMoves(self, board):
for index, move in enumerate(board... | CommandLineMoveGetter.py | 862 | print(board.legal_moves) | 24 | pt | 0.323314 |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2017, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | qiime2/core/transform.py | 7,580 | Checks to see if there exist transformers for other
Parameters
----------
other : ModelType subclass
The object being checked for transformer
Returns
-------
bool
Does the specified transformer exist for other?
---------------------------------------------------------------------------- Copyright (c) 2016-20... | 2,046 | en | 0.824131 |
import torch
import torch.nn.functional as F
def clamp_probs(probs):
eps = torch.finfo(probs.dtype).eps
return torch.clamp(probs, min=eps, max=1-eps)
def concrete_sample(logits, temperature, shape=torch.Size([])):
'''
Sampling for Concrete distribution.
See Eq. 10 of Maddison et al., 2017.
'... | selection/layers/utils.py | 1,150 | Sampling for BinConcrete distribution.
See PyTorch source code, differs from Eq. 16 of Maddison et al., 2017.
Sampling for Concrete distribution.
See Eq. 10 of Maddison et al., 2017. | 184 | en | 0.781941 |
import os
import go_vncdriver
import tensorflow as tf
import argparse
import json
import envs
from model import policies
import checkpoint_utils
parser = argparse.ArgumentParser(description="Run commands")
parser.add_argument('logdir', type=str, help="Log directory path")
args = parser.parse_args()
with open(args.lo... | universe-starter-agent/run.py | 1,186 | import ipdb; ipdb.set_trace()saver = tf.train.Saver(sharded=True)saver.restore(sess, os.path.join(args.logdir, 'train/model.ckpt-0')) | 133 | en | 0.281142 |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: © 2022 Decompollaborate
# SPDX-License-Identifier: MIT
from __future__ import annotations
import enum
@enum.unique
class FileSectionType(enum.Enum):
Unknown = -2
Invalid = -1
Text = 1
Data = 2
Rodata = 3
Bss = 4
Reloc = 5
... | spimdisasm/common/FileSectionType.py | 2,633 | !/usr/bin/env python3 SPDX-FileCopyrightText: © 2022 Decompollaborate SPDX-License-Identifier: MIT | 98 | de | 0.391041 |
import numpy as np
import pytest
from pytools.obj_array import make_obj_array
# {{{ test_unstructured_vertex_grid
@pytest.mark.parametrize("ambient_dim", [2, 3])
@pytest.mark.parametrize("dformat", ["xml", "hdf", "binary"])
def test_unstructured_vertex_grid(ambient_dim, dformat, npoints=64):
"""Test constructin... | test/test_xdmf.py | 6,252 | Test constructing a grid with a more complicated topology.
Test constructing a vertex grid with different ways to define the
points and connectivity.
{{{ test_unstructured_vertex_grid {{{ set up connectivity }}} {{{ set up grids }}} }}} {{{ test_unstructured_simplex_grid NOTE: largely copied from meshmode/mesh/genera... | 433 | en | 0.575792 |
import unittest
import torch
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
BertConfig,
BertForSequenceClassification,
GlueDataset,
GlueDataTrainingArguments,
Trainer,
TrainingArguments,
)
from transformers.adapters.composition import Fuse
from transforme... | tests/test_adapter_trainer.py | 6,792 | create second model that should resume the training of the first | 64 | en | 0.945171 |
from sklearn.metrics import roc_curve, auc
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
import json
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
from pylab import rcParams
# rcParams['figure.figsize'] = 20, 20
rcParams... | utils.py | 5,001 | rcParams['figure.figsize'] = 20, 20 Create folder Log Train resultsclassification report AUC curve Confusion matrix Test resultsclassification report AUC curve Confusion matrix plot_confusion_matrix(cm, list(range(len(classes))), path=path, name='test-'+name) | 259 | en | 0.457655 |
import datetime
import os
import re
import ujson
from django.conf import settings
from django.http import HttpResponse
from django.test import override_settings
from mock import MagicMock, patch
import urllib
from typing import Any, Dict, List
from zerver.lib.actions import do_create_user
from zerver.lib.test_classe... | zerver/tests/test_home.py | 31,081 | Use this for tests that are geared toward specific edge cases, but
which still want the home page to load properly.
Keep this list sorted!!! Verify that the app styles get included Keep this list sorted!!! Verify fails if logged-out Create bot for realm_bots testing. Must be done before fetching home_page. Verify suc... | 1,774 | en | 0.92562 |
################################################
# backend.py is part of COVID.codelongandpros.repl.co
# You should have recieved a copy of the three-clause BSD license.
# If you did not, it is located at:
# https://opensource.org/licenses/BSD-3-Clause
# Made by Scott Little, with help from StackOverflow
############... | backend.py | 1,598 | backend.py is part of COVID.codelongandpros.repl.co You should have recieved a copy of the three-clause BSD license. If you did not, it is located at: https://opensource.org/licenses/BSD-3-Clause Made by Scott Little, with help from StackOverflow Retrieve HTTP meta-data or img[:] = 255 | 288 | en | 0.903333 |
import numpy as np
def non_max_suppression_fast(boxes, overlapThresh):
# if there are no boxes, return an empty list
if len(boxes) == 0:
return []
# if the boxes are integers, convert them to floats (due to divisions)
if boxes.dtype.kind == "i":
boxes = boxes.astype("float")
# initial... | coffee-maturation/src/models/non_maximum.py | 1,713 | if there are no boxes, return an empty list if the boxes are integers, convert them to floats (due to divisions) initialize the list of picked indexes grab the coordinates of the bounding boxes compute the area of the boxes and sort the boxes by their score keep looking while some indexes still remain in the indexes li... | 699 | en | 0.937786 |
import time
import pyperclip
import csv
import subprocess
import serial
ser = serial.Serial('/dev/cu.usbmodemFD131', baudrate=9600, timeout=None)
clipboard_old = pyperclip.paste()
musicFile = "music/yes_1.mp3"
musicFile_rick = "music/rickroll.mp3"
failText = "Fail. No, bubbles, for you."
rickText = "Fail. But don't wo... | qrcodetoclassification.py | 2,959 | local informationLoad data object for that classification Have lookup table of the form id, bar, bulge where bar&bulge are out of 1,0in the form [id,bar,bulge]classification=['1ds4',1,0] example of a barred galaxy withotu a bulgeser.write('1\n')ser.write('0\n') | 265 | en | 0.650204 |
import numpy as np
import pytest
from astropy.cosmology import default_cosmology
from skypy.linear.eisenstein_hu import power_spectrum
def test_eisenstein_hu():
""" Test Eisenstein & Hu Linear matter power spectrum with
and without wiggles using astropy default cosmology"""
cosmology = default_cosmology.g... | skypy/linear/tests/test_eisenstein_hu.py | 2,794 | Test Eisenstein & Hu Linear matter power spectrum with
and without wiggles using astropy default cosmology
Test that a scalar input gives a scalar output Test that an array input gives an array output Test pk against precomputed values for default_cosmology Test for failure when wavenumber <= 0 | 297 | en | 0.579481 |
"""Contains the CLI."""
import sys
import json
import logging
import oyaml as yaml
import click
# For the profiler
import pstats
from io import StringIO
# To enable colour cross platform
import colorama
from sqlfluff.cli.formatters import (
format_rules,
format_violation,
format_linting_result_header,... | src/sqlfluff/cli/commands.py | 23,233 | This filter makes all warnings or above red.
Sqlfluff is a modular sql linter for humans.
Add common options to commands via a decorator.
These are applied to all of the cli commands.
Add core operation options to commands via a decorator.
These are applied to the main (but not all) cli commands like
`parse`, `lint` ... | 4,719 | en | 0.799271 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
A1 = [1, 2, 4, 5, 6, 6, 8, 9]
A2 = [2, 5, 6, 7, 8, 8, 9]
def find_closest_num(A, target):
min_diff = float("inf")
low = 0
high = len(A) - 1
closest_num = None
# Edge cases for empty list of list
# with only one element:
if len(A) == 0:
... | dsa/closestnumber.py | 1,459 | !/usr/bin/env python coding: utf-8 In[1]: Edge cases for empty list of list with only one element: Ensure you do not read beyond the bounds of the list. Check if the absolute value between left and right elements are smaller than any seen prior. Move the mid-point appropriately as is done via binary search. If the elem... | 407 | en | 0.869023 |
from threading import Thread
from time import sleep
from pytezos import pytezos
import argparse
contract_dict = {}
def contract_origin_search(p, contract_hash, verbose = 0):
start = 0
end = p.shell.head.header()["level"]
contract = p.contract(contract_hash)
found = -1
data = None
while found =... | tezos-sandbox/watchtower/delphinet/passive_watchtower.py | 10,872 | TO REMOVE, added as test vector has too many updates TO REMOVE Instantiate the parser Set network and get head's level Set the scan lower and upper bounds Check contract exists Return first update's level if asked Return last update's level if asked Return origination's level if asked Return all updates' levels if aske... | 628 | en | 0.765149 |
from functools import partial
from dictknife.langhelpers import as_jsonpointer as _as_jsonpointer
from dictknife.langhelpers import as_path_node as _as_path_node
from dictknife import accessing
from dictknife import naming
def _make_key(k0, k1, *, sep="/"):
if k1 is None:
return _as_jsonpointer(str(k0))
... | dictknife/transform.py | 3,666 | list ? todo: as generator todo: peformance improvement side effect! todo: random select todo: cont suffix for list | 114 | en | 0.252054 |
# Copyright (C) 2019 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
import asyncio
import base64
from distutils.version import StrictVersion
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtWi... | electrum_dash/gui/qt/update_checker.py | 6,159 | Copyright (C) 2019 The Electrum developers Distributed under the MIT software license, see the accompanying file LICENCE or http://www.opensource.org/licenses/mit-license.php example signed_version_dict: { "version": "3.9.9", "signatures": { "1Lqm1HphuhxKZQEawzPse8gJtgjm9kUKT4": "IA+2QG3xPRn4HAIFdpu9eea... | 394 | en | 0.538937 |
# Copyright 2018-2021 Xanadu Quantum Technologies 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... | pennylane/devices/tests/test_gates.py | 21,321 | Test qubit-based devices' probability vector after application of gates.
Test the device's probability vector after application of inverse of gates.
Test that the device can implement all gates that it claims to support.
Test basis state initialization.
Test that the device can implement the inverse of all its supporte... | 2,478 | en | 0.788506 |
# Generated by Django 3.0.3 on 2020-08-03 15:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ecommerce_platform', '0010_userprofile_address'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
... | obsidian_traders/ecommerce_platform/migrations/0011_remove_userprofile_address.py | 363 | Generated by Django 3.0.3 on 2020-08-03 15:29 | 45 | en | 0.646847 |
import pandas as pd
import numpy as np
def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]):
""" Plot the correlation coefficient for various exponential scalings of input features
>>> np.random.seed(314159)
>>> df = pd.DataFrame()
>>> df['output'] = np.ra... | src/nlpia/features.py | 1,590 | Plot the correlation coefficient for various exponential scalings of input features
>>> np.random.seed(314159)
>>> df = pd.DataFrame()
>>> df['output'] = np.random.randn(1000)
>>> df['x10'] = df.output * 10
>>> df['sq'] = df.output ** 2
>>> df['sqrt'] = df.output ** .5
>>> optimize_feature_power(df, output_column_name... | 751 | en | 0.442601 |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | src/python/bot/tasks/regression_task.py | 14,930 | Save current regression range indices in case we die in middle of task.
Test to see if a test case reproduces in the specified revision.
Run regression task and handle potential errors.
Attempt to find when the testcase regressed.
Test to see if we regressed near either the min or max revision.
Saves the regression ran... | 3,495 | en | 0.919973 |
# -*- coding: utf-8 -*-
"""
@Remark: 自定义视图集
"""
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from utils.filters import DataLevelPermissionsFilter
from utils.jsonResponse import SuccessResponse,... | backend/utils/viewset.py | 6,746 | 自定义的ModelViewSet:
统一标准的返回格式;新增,查询,修改可使用不同序列化器
(1)ORM性能优化, 尽可能使用values_queryset形式
(2)create_serializer_class 新增时,使用的序列化器
(3)update_serializer_class 修改时,使用的序列化器
Same as Django's standard shortcut, but make sure to also raise 404
if the filter_kwargs don't match the required types.
@Remark: 自定义视图集
-*- coding: utf-8 -*- ... | 937 | zh | 0.35457 |
# -*- coding: utf-8 -*-
from base.log import *
import os
def get_url(trackId,trackPointId,type1,seq,imageType):
cmd = 'http://10.11.5.34:13100/krs/image/get?trackPointId=%s&type=%s&seq=%s&imageType=%s' %(trackPointId,type1,seq,imageType)
return cmd
def main():
url = get_url('123', '123', '00', '004', 'jpg')
p... | mesh_krs_imagequery.py | 365 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
enum = 0
enum1 = 0
enum2 = 0
prob = 0
p1 = 0
p2 = 0
parity = 0
for z1 in range(1, 6):
for y1 in range(z1+1, 7):
for z2 in range(1, z1+1):
for y2 in range(z2+1, y1+1):
""" for y2 in range(1, y1):
for z2 in range(y2, z1+1):
for z3 in ran... | src/compute_probs.py | 1,565 | print(y1, z1, y2, z2) | 21 | pt | 0.514697 |
import datetime
import logging
import multiprocessing
import os
import re
import subprocess
import sys
import tempfile
import time
from typing import Any, Dict, List, Optional
import dateutil.parser
import pytest
import requests
from determined import experimental
from determined.common import api, yaml
from determin... | e2e_tests/tests/experiment/experiment.py | 25,463 | Runs `det experiment describe` CLI command on a finished
experiment. Will raise an exception if `det experiment describe`
encounters a traceback failure.
Runs list-related CLI commands on a finished experiment. Will raise an
exception if the CLI command encounters a traceback failure.
TODO(DET-5678): refactor tests t... | 1,869 | en | 0.870579 |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=1>
# Reading outputs from E+
# <codecell>
# some initial set up
# if you have not installed epp, and only downloaded it
# you will need the following lines
import sys
# pathnameto_eppy = 'c:/eppy'
pathnameto_eppy = '../'
sys.path.append(pathnam... | docs/Outputs_Tutorial.py | 11,037 | -*- coding: utf-8 -*- <nbformat>3.0</nbformat> <headingcell level=1> Reading outputs from E+ <codecell> some initial set up if you have not installed epp, and only downloaded it you will need the following lines pathnameto_eppy = 'c:/eppy' <headingcell level=2> Using titletable() to get at the tables <markdowncell> So ... | 7,411 | en | 0.871186 |
# -*- coding: utf-8 -*-
#
# pysteps documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 31 01:11:37 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | pysteps/doc/conf.py | 6,134 | -*- coding: utf-8 -*- pysteps documentation build configuration file, created by sphinx-quickstart on Tue Jul 31 01:11:37 2018. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All configuration values ... | 3,738 | en | 0.720477 |
# Automatically generated from poetry/pyproject.toml
# flake8: noqa
# -*- coding: utf-8 -*-
from setuptools import setup
packages = \
['c7n_trailcreator']
package_data = \
{'': ['*']}
install_requires = \
['argcomplete (>=1.11.1,<2.0.0)',
'attrs (>=19.3.0,<20.0.0)',
'boto3 (>=1.12.20,<2.0.0)',
'botocore (>=1.15.2... | tools/c7n_trailcreator/setup.py | 6,106 | Automatically generated from poetry/pyproject.toml flake8: noqa -*- coding: utf-8 -*- | 85 | en | 0.662374 |
# 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... | superset/models/sql_lab.py | 6,622 | ORM model for SQL query
Now that SQL Lab support multi-statement execution, an entry in this
table may represent multiple SQL statements executed sequentially
ORM model for SQL query
Name property
A collection of ORM sqlalchemy models for SQL Lab
Licensed to the Apache Software Foundation (ASF) under one or more con... | 1,457 | en | 0.857409 |
import random
import time
def dead_state(width, height):
board = []
line = []
for i in range(width):
for j in range(height):
line.append(0)
board.append(line)
line = []
return board
def random_state(width, height):
state = dead_state(width, height)
for i in... | Projects/Game of Life/gol.py | 3,838 | check the inputs for the dead state how to get the length of the row and height from a list of lists Alive cell Dead cell break is not being utilized properly when the break hits it ends the innermost loop not just an iteration print('\t\talive',row,column) too wide too tall print('\talive',row,column) print('alive', a... | 814 | en | 0.60878 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 15:56:35 2019
@author: logancross
"""
from mvpa2.suite import *
from os import listdir
import time
def make_targets(subj, glm_ds_file, mask_name, runs2use, class_dict, homedir, ana_name):
start_time = time.time()
print 'Starting making ... | ANALYSIS/T0/MVPA/PYmvpa/cross_decoding/mvpa_utils_pav.py | 7,739 | !/usr/bin/env python2 -*- coding: utf-8 -*-get timing for all conditions and sort by this timingadd a list of trial category as a sample attributesort by trial timing and append to listsunroll lists of lists to one list load fmri dataset with these values as targetsreturn fds_subset, trial_categ_allruns[:runs2use*60... | 1,209 | en | 0.879435 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from profiles_api import views
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset')
router.register('profile', views.UserProfileViewSet) #No base_name needed for we have a queryse... | profiles_api/urls.py | 552 | No base_name needed for we have a queryset in the view | 54 | en | 0.9253 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""User profiles module for Invenio."""
from __future__ import absolute_import, prin... | invenio_userprofiles/ext.py | 2,123 | Invenio-UserProfiles extension.
Extension initialization.
Flask application initialization.
Initialize configuration.
User profiles module for Invenio.
-*- coding: utf-8 -*- This file is part of Invenio. Copyright (C) 2015-2018 CERN. Invenio is free software; you can redistribute it and/or modify it under the terms o... | 398 | en | 0.684374 |
from flask import Flask
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import config_options
bootstrap = Bootstrap()
db = SQLAlchemy()
migrate = Migrate()
login_manager = Logi... | app/__init__.py | 1,007 | Creating the app configurations Initializing flask extensions Registering the blueprint | 87 | en | 0.606771 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | sdk/python/pulumi_azure_native/netapp/v20190601/_inputs.py | 10,826 | Active Directory
:param pulumi.Input[str] active_directory_id: Id of the Active Directory
:param pulumi.Input[str] dns: Comma separated list of DNS server IP addresses for the Active Directory domain
:param pulumi.Input[str] domain: Name of the Active Directory domain
:param pulumi.Input[str] organizational_unit: The O... | 2,428 | en | 0.669402 |
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# Copyright 2020 VMware, Inc. All rights reserved.
# AUTO GENERATED FILE -- DO NOT MODIFY!
#
# vAPI stub file for package com.vmware.vmc.orgs.sddcs.networks.edges.firewall.
#-------------------------------------------... | com/vmware/vmc/orgs/sddcs/networks/edges/firewall_client.py | 15,013 | :type config: :class:`vmware.vapi.bindings.stub.StubConfiguration`
:param config: Configuration to be used for creating the stub.
:type config: :class:`vmware.vapi.bindings.stub.StubConfiguration`
:param config: Configuration to be used for creating the stub.
Delete firewall configuration for a management or compute ... | 3,665 | en | 0.416006 |
# coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | core/domain/subtopic_page_domain.py | 15,893 | Domain object for a Subtopic page.
Domain object for changes made to subtopic_page object.
The allowed commands, together with the attributes:
- 'create_new' (with topic_id, subtopic_id)
- 'update_subtopic_page_property' (
with property_name, new_value, old_value, subtopic_id).
Domain object for the co... | 5,905 | en | 0.691989 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/python/eager/benchmarks_test.py | 31,277 | Benchmark overheads of creating a Tensor object.
Benchmarks for low-level eager execution primitives.
To run CPU benchmarks:
bazel run -c opt benchmarks_test -- --benchmarks=.
To run GPU benchmarks:
bazel run --config=cuda -c opt --copt="-mavx" benchmarks_test -- \
--benchmarks=.
Copyright 2017 The TensorFl... | 1,924 | en | 0.810139 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# =============================================================================
# title : magicblueshell.py
# description : Python tool to control Magic Blue bulbs over Bluetooth
# author : Benjamin Piouffle
# date : 23/11/2015
# usage ... | magicblue/magicblueshell.py | 12,254 | !/usr/bin/env python -*- coding: UTF-8 -*- ============================================================================= title : magicblueshell.py description : Python tool to control Magic Blue bulbs over Bluetooth author : Benjamin Piouffle date : 23/11/2015 usage : python ... | 662 | en | 0.558969 |
from pyopenproject.business.root_service import RootService
from pyopenproject.business.services.command.root.find import Find
class RootServiceImpl(RootService):
def __init__(self, connection):
"""Constructor for class RootServiceImpl, from RootService
:param connection: The connection data
... | pyopenproject/business/services/root_service_impl.py | 434 | Constructor for class RootServiceImpl, from RootService
:param connection: The connection data | 95 | en | 0.650209 |
import os
import shutil
from datetime import timedelta
from django.contrib.admin.sites import AdminSite
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth.models import User
from django.utils import timezone
from allauth.account.models import EmailAddress
from rest_framework.test ... | tests/unit/jobs/test_admin.py | 5,320 | Test case for re-running submissions from admin
make all submissions private before test make all submissions public before test | 130 | en | 0.895599 |
import geohash
import redis
from addok.config import config
from addok.db import DB
from addok.ds import get_document
from . import iter_pipe, keys, yielder
VALUE_SEPARATOR = '|~|'
def preprocess(s):
if s not in _CACHE:
_CACHE[s] = list(iter_pipe(s, config.PROCESSORS))
return _CACHE[s]
_CACHE = {}
... | addok/helpers/index.py | 6,537 | Do not index. A mandatory field is null. Special case for housenumber type, because it's not a real type We need to have the housenumbers tokenized in the document, to match from user query (see results.match_housenumber). Housenumber may have multiple tokens (eg.: "dix huit"). | 278 | en | 0.850044 |
import pandas as pd
import numpy as np
from pandas.util.testing import rands
groups = np.arange(10)
str_groups = np.array(list("0123456789"))
np.random.seed(1)
for size in [1e2, 1e3, 1e4, 1e5, 1e6]:
size = int(size)
g = np.random.choice(groups, size)
sg = np.random.choice(str_groups, size)
v = np.rand... | pandas_cmp/create_data.py | 1,212 | Join benchmark data https://wesmckinney.com/blog/high-performance-database-joins-with-pandas-dataframe-more-benchmarks/ https://github.com/wesm/pandas/blob/23669822819808bbaeb6ea36a6b2ef98026884db/bench/bench_merge_sqlite.py | 224 | en | 0.530329 |
# Config
NODE_ID = ${NODE_ID}
# hour,set 0 to disable
SPEEDTEST = ${SPEEDTEST}
CLOUDSAFE = ${CLOUDSAFE}
ANTISSATTACK = ${ANTISSATTACK}
AUTOEXEC = ${AUTOEXEC}
MU_SUFFIX = "${MU_SUFFIX}"
MU_REGEX = "${MU_REGEX}"
SERVER_PUB_ADDR = "127.0.0.1" # mujson_mgr need this to generate ssr link
API_INTERFACE = "${API_INTERFACE... | apiconfig.py | 984 | Config hour,set 0 to disable mujson_mgr need this to generate ssr link glzjinmod, modwebapi mudb Mysql API Manager (ignore this) if you want manage in other server you should set this value to global ip make sure this port is idle | 230 | en | 0.683155 |
# Copyright 2018 The Cornac 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 ... | cornac/experiment/experiment.py | 3,776 | Experiment Class
Parameters
----------
eval_method: :obj:`<cornac.eval_methods.BaseMethod>`, required
The evaluation method (e.g., RatioSplit).
models: array of :obj:`<cornac.models.Recommender>`, required
A collection of recommender models to evaluate, e.g., [C2PF, HPF, PMF].
metrics: array of :obj:{`<corna... | 1,653 | en | 0.725323 |
import connexion
from openapi_server.annotator.phi_types import PhiType
from openapi_server.get_annotations import get_annotations
from openapi_server.models.error import Error # noqa: E501
from openapi_server.models.text_id_annotation_request import TextIdAnnotationRequest # noqa: E501
from openapi_server.models.tex... | server/openapi_server/controllers/text_id_annotation_controller.py | 1,214 | Annotate IDs in a clinical note
Return the ID annotations found in a clinical note # noqa: E501
:param text_id_annotation_request:
:type text_id_annotation_request: dict | bytes
:rtype: TextIdAnnotationResponse
noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 | 270 | en | 0.457301 |
#!/usr/bin/env python3
self_description = """
gridradar2influx is a tiny daemon written to fetch data from the gridradar.net-API and
writes it to an InfluxDB instance.
"""
# import standard modules
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import configparser
import logging
import os
import sig... | gridradar2influx.py | 4,874 | !/usr/bin/env python3 import standard modules import 3rd party modulesimport functions from files default vars parse command line arguments set logging omit time stamp if run in daemon mode read config from ini file set up influxdb handler test more config options and see if they are present_ = config.get('influxdb', '... | 756 | en | 0.528271 |
import logging
import odoo.http
from odooku.request import WebRequestMixin
_logger = logging.getLogger(__name__)
class WebSocketRequest(WebRequestMixin, odoo.http.WebRequest):
def __init__(self, httprequest):
super(WebSocketRequest, self).__init__(httprequest)
def dispatch(self):
raise Not... | odooku/services/websocket/requests.py | 2,339 | Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response. | 142 | en | 0.952747 |
#!/usr/bin/env python3
from itertools import product
if __name__ == "__main__":
arr1 = list(map(int, input().strip().split(' ')))
arr2 = list(map(int, input().strip().split(' ')))
for el in product(arr1, arr2):
print("{} ".format(el), end='')
| python/itertools-product.py | 274 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
# URL pattern for the UserListView
url(
regex=r'^$',
view=views.UserListView.as_view(),
name='list'
),
# URL pattern for the ... | artinvestor_server/users/urls.py | 781 | -*- coding: utf-8 -*- URL pattern for the UserListView URL pattern for the UserRedirectView URL pattern for the UserDetailView URL pattern for the UserUpdateView | 161 | en | 0.549467 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/requests/messages/get_inventory_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _me... | pgoapi/protos/pogoprotos/networking/requests/messages/get_inventory_message_pb2.py | 2,365 | Generated by the protocol buffer compiler. DO NOT EDIT! source: pogoprotos/networking/requests/messages/get_inventory_message.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:pogoprotos.networking.requests.messages.GetInventoryMessage) @@protoc_insertion_point(module_scope) | 303 | en | 0.439898 |
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2020 Hnaynag University (Jae-Hong Lee)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import codecs
import json
import logging
import re
import random
from pathlib import Path
from tqdm import tqdm
from nltk import tokenize
from espn... | egs/linersum/asr1/local/data_prep.py | 6,110 | !/usr/bin/env python3 encoding: utf-8 Copyright 2020 Hnaynag University (Jae-Hong Lee) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) logging info Remove the duplicated keys and load the json to the dict Eliminate the error key with python readlines function FIXME(j-ppng): These lines is fixed by python read... | 1,061 | en | 0.835925 |
'''define the config file for voc and resnet101os16'''
from .base_cfg import *
# modify dataset config
DATASET_CFG = DATASET_CFG.copy()
DATASET_CFG['train'].update(
{
'type': 'voc',
'set': 'trainaug',
'rootdir': 'data/VOCdevkit/VOC2012',
}
)
DATASET_CFG['test'].update(
{
't... | ssseg/cfgs/annnet/cfgs_voc_resnet101os16.py | 1,505 | define the config file for voc and resnet101os16
modify dataset config modify dataloader config modify optimizer config modify losses config modify model config modify inference config modify common config | 207 | en | 0.330456 |
# Write a Python function to sum all the numbers in a list
# Sample List : [8, 2, 3, 0, 7]
# Expected Output : 20
def sum_list(list):
sum = 0
for i in list:
sum += i
return sum
list = [8, 2, 3, 0, 7]
print(sum_list(list)) | introduction/exercise/ex9.py | 245 | Write a Python function to sum all the numbers in a list Sample List : [8, 2, 3, 0, 7] Expected Output : 20 | 107 | en | 0.589005 |
from django.apps import AppConfig
class SignalsConfig(AppConfig):
name = 'signals.apps.signals'
verbose_name = 'Signals'
def ready(self):
# Import Django signals to connect receiver functions.
import signals.apps.signals.signal_receivers # noqa
| api/app/signals/apps/signals/config.py | 277 | Import Django signals to connect receiver functions. noqa | 57 | en | 0.836169 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
"""tf2onnx.onnx_opset module"""
from . import common, controlflow, generator, logical, math, misc, nn, quantize, reduction, rnn, tensor, traditionalml
| tf2onnx/onnx_opset/__init__.py | 246 | tf2onnx.onnx_opset module
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. | 117 | en | 0.425136 |
# -*- coding:utf-8 -*-
# Author: RubanSeven
# import cv2
import numpy as np
# from transform import get_perspective_transform, warp_perspective
from .warp_mls import WarpMLS
def distort(src, segment):
img_h, img_w = src.shape[:2]
cut = img_w // segment
thresh = cut // 3
# thresh = img_h // segment /... | data_loader/modules/Text_Image_Augmentation_python/augment.py | 5,110 | -*- coding:utf-8 -*- Author: RubanSeven import cv2 from transform import get_perspective_transform, warp_perspective thresh = img_h // segment // 3 thresh = img_h // 5 thresh = img_h // segment // 3 thresh = img_h // 5 def distort(src, segment): img_h, img_w = src.shape[:2] dst = np.zeros_like(src, dtype=np.uin... | 2,314 | en | 0.208871 |
"""
Examples of loading all information about an object or set of objects from the
database.
"""
from __future__ import absolute_import
from __future__ import print_function
from owmeta_core.context import Context
from owmeta_core.command import OWM
from owmeta.connection import Connection
from owmeta.neuron import N... | examples/test_bgp.py | 1,901 | Examples of loading all information about an object or set of objects from the
database.
sometimes a neuron object with the same name is returned more than once Wrap in a try-block in case there are no receptors listed | 220 | en | 0.89722 |
#!/usr/bin/env python3
# Copyright (c) 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.
from segwit import send_to_witness
from test_framework.test_framework import BitcoinTestFramework
from test_fr... | qa/rpc-tests/bumpfee.py | 14,594 | Get a wallet change address.
There is no wallet RPC to access unused change addresses, so this creates a
dummy transaction, calls fundrawtransaction to give add an input and change
output, then returns the change address.
!/usr/bin/env python3 Copyright (c) 2016 The Bitcoin Core developers Distributed under the MIT s... | 2,607 | en | 0.873345 |
#!/usr/bin/env python3
def main():
pattern = input().upper()
genome = input().upper()
mismatches = int(input())
occurrences = approximate_occurrences(genome, pattern, mismatches)
for o in occurrences:
print(o, end=' ')
print()
LIST_A = ['C', 'T', 'G']
LIST_C = ['A', 'T', 'G']
LIST_T... | hw1/approximate_occurrences.py | 2,572 | Generate immediate (different by one mismatch) neighbours of the given genome pattern
:param pattern: a pattern to examine
:return: neighbourhood, NOT including the given pattern
Generate neighbours for the given pattern (genome string)
:param pattern: genome pattern
:param mismatches: number of mismatches to generate ... | 433 | en | 0.809012 |
# -*- coding: utf-8 -*-
'''
Runs MultiprocessTest with all warnings including traceback...
'''
#
# https://stackoverflow.com/questions/22373927/get-traceback-of-warnings
import traceback
import warnings
import sys
from . import multiprocess
def warn_with_traceback(message, category, filename, lineno, file=None, line... | dh_testers/warningMultiprocess.py | 688 | Runs MultiprocessTest with all warnings including traceback...
-*- coding: utf-8 -*- https://stackoverflow.com/questions/22373927/get-traceback-of-warnings | 157 | en | 0.760746 |
version = '0.1.1'
title = 'Cloud::Auth'
api_version = 'v1'
api_prefix = '/api/' + api_version
# $ echo -n 'Once upon a time...' | openssl.exe dgst -sha256
# (stdin)= 7cc6caf901b894033626981cd102021727aa59c2548d79e59382649b2c6f50f2
ADMIN_TOKEN = 'd7981fb00d6f071e1a8b454c47b378d815b53541621e22dc4b3dbf5a6b9c8b1d'
USER_... | src/app/conf.py | 395 | $ echo -n 'Once upon a time...' | openssl.exe dgst -sha256 (stdin)= 7cc6caf901b894033626981cd102021727aa59c2548d79e59382649b2c6f50f2 | 132 | en | 0.188881 |
from __future__ import division
from __future__ import print_function
from __future__ import with_statement
from replacers import *
import pandas as pd
import nltk
import subprocess
def findFreqWord(fuzzyDF):
f1 = fuzzyDF # pd.read_csv("SubmittedCSV/fuzzy.csv")
f2 = pd.DataFrame(columns=['Tweets', 'Classifi... | freqWordSelection.py | 5,767 | pd.read_csv("SubmittedCSV/fuzzy.csv") ---------------------------------- SUBMITTED LOGIC - TEST CASE ---------------------------------- 01 UNIT TESTING FAILED 10, 11, 27, 30 ---------------------------------- 02 LOGICAL GLITCH ---------------------------------- 03 COMPLIANCE MISUSE -------... | 2,500 | en | 0.692841 |
# -*- coding: utf8 -*-
# Copyright 2019 JSALT2019 Distant Supervision Team
#
# 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
#
# U... | distsup/configuration/__init__.py | 5,245 | Class responsible for instantiating object that are defined in config file.
The class tries to be smart about the following modules:
- Trainer will by default instantiate an 'distsup.trainer.Trainer'
- all items on the Data key will instantiate a 'distsup.data.Data'
- It will configure the Model key according to Datas... | 1,368 | en | 0.791199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.