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 |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Competition.url_redirect'
db.alter_column(u'web_compet... | codalab/apps/web/migrations/0082_auto__chg_field_competition_url_redirect.py | 46,314 | -*- coding: utf-8 -*- Changing field 'Competition.url_redirect' Changing field 'Competition.url_redirect' | 105 | en | 0.660215 |
# Python program for implementation of Quicksort Sort
# This function takes last element as pivot, places
# the pivot element at its correct position in sorted
# array, and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot
def partition(arr, low, high):
i = (... | quicksort/quicksort.py | 1,449 | Python program for implementation of Quicksort Sort This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot index of smaller element pivot If current element is sm... | 674 | en | 0.766202 |
'''
Inter-coder agreement statistic Fleiss' Pi.
.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
from __future__ import absolute_import, division
from decimal import Decimal
from segeval.agreement import __fnc_metric__, __actual_agreement_linear__
def __fleiss_pi_linear__(dataset, **kwargs):
'''... | segeval/agreement/pi.py | 2,078 | Calculates Fleiss' :math:`\pi` (or multi-:math:`\pi`), originally proposed in
[Fleiss1971]_, and is equivalent to Siegel and Castellan's :math:`K`
[SiegelCastellan1988]_. For 2 coders, this is equivalent to Scott's :math:`\pi`
[Scott1955]_.
Calculates Fleiss' :math:`\pi` (or multi-:math:`\pi`), originally proposed in
... | 745 | en | 0.729463 |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import models
import torch.nn.functional as F
import math
import torch.utils.model_zoo as model_zoo
nonlinearity = nn.ReLU
class EncoderBlock(nn.Module):
def __init__(self, inchannel, outchannel, stride):
super().__init... | model/model.py | 24,163 | B, C, H, W -> B, C/4, H, W B, C/4, H, W -> B, C/4, H, W B, C/4, H, W -> B, C, H, W B, C, H, W -> B, C/4, H, W B, C/4, H, W -> B, C/4, H, W B, C/4, H, W -> B, C, H, W_,c,h,w=x.sizeprint(c)print(h)print(w)torch.matmul(m,x)_,c,h,w=x.sizeprint(c)print(h)print(w)torch.matmul(m,x) B, C, H, W -> B, C/4, H, W B, C/4, H, W -> B... | 3,748 | en | 0.285232 |
# Generated by Django 2.2 on 2021-12-05 14:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
... | profiles_api/migrations/0001_initial.py | 1,708 | Generated by Django 2.2 on 2021-12-05 14:55 | 43 | en | 0.826184 |
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
'''
MapReduce Job Metrics
---------------------
mapreduce.job.elapsed_ime The elapsed time since the application started (in ms)
mapreduce.job.maps_total The total number of maps
map... | checks.d/mapreduce.py | 21,254 | Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications
Return the base of a URL
Join a URL with multiple directories
Get custom metrics specified for each counter
Get metrics for each MapReduce job.
Return a dictionary for each MapReduce job
{
job_id: {
'job_name': job_na... | 4,239 | en | 0.696038 |
"""
Create Sine function without using third-party plugins or expressions.
@Guilherme Trevisan - github.com/TrevisanGMW - 2021-01-25
1.0 - 2021-01-25
Initial Release
"""
try:
from shiboken2 import wrapInstance
except ImportError:
from shiboken import wrapInstance
try:
from PySide2.Q... | python-scripts/gt_add_sine_attributes.py | 15,593 | Create Sine function without using third-party plugins or expressions
Parameters:
obj (string): Name of the object
sine (string): Prefix given to the name of the attributes (default is "sine")
tick_source_attr (string): Name of the attribute used as the source for time. It u... | 2,236 | en | 0.563443 |
#!/usr/bin/python
# -*- coding: UTF-8, tab-width: 4 -*-
from sys import argv, stdin, stdout, stderr
from codecs import open as cfopen
import json
def main(invocation, *cli_args):
json_src = stdin
if len(cli_args) > 0:
json_src = cfopen(cli_args[0], 'r', 'utf-8')
data = json.load(json_src, 'utf... | rqpol-sort.py | 3,045 | !/usr/bin/python -*- coding: UTF-8, tab-width: 4 -*- <-- some magic here ^-- because the default had space after comma even at end of line. | 142 | en | 0.867762 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
from typing import Optional
from fastapi import APIRouter, Depends, Request
from epicteller.core.controller import campaign as campaign_ctl
from epicteller.core.controller import room as room_ctl
from epicteller.core.error.base import NotFoundError
from epi... | epicteller/web/handler/room.py | 1,988 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('parsing')
PARSER_TYPES = ['movie', 'series']
# Mapping of parser type to (m... | flexget/plugins/parsers/plugin_parsing.py | 3,589 | Provides parsing framework
Prepare our list of parsing plugins and default parsers.
Use the selected movie parser to parse movie information from `data`
:param data: The raw string to parse information from
:returns: An object containing the parsed information. The `valid` attribute will be set depending on success.
... | 1,249 | en | 0.716676 |
# Generated by Django 3.2.5 on 2021-07-20 12:31
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_article'),
]
operations = [
migrations.AlterField(
model_name='article',
name='detail',
... | blog/migrations/0004_alter_article_detail.py | 388 | Generated by Django 3.2.5 on 2021-07-20 12:31 | 45 | en | 0.64772 |
import flask
from flask import request, jsonify
import sqlite3
app = flask.Flask(__name__)
app.config["DEBUG"] = True
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
@app.route('/', methods=['GET'])
def home():
return '''<h1>... | tools/test_flask.py | 1,822 | print("columns" in query_parameters) query = "SELECT * FROM books WHERE" to_filter = [] if id: query += ' id=? AND' to_filter.append(id) if published: query += ' published=? AND' to_filter.append(published) if author: query += ' author=? AND' to_filter.append(author) if not (id or published or a... | 521 | en | 0.515909 |
#!/usr/bin/python3
# apt install libnetfilter-queue-dev
import os
import random
import string
import time
from multiprocessing import Pool
from netfilterqueue import NetfilterQueue
from scapy.all import *
SINGLE_QUEUE = False
if SINGLE_QUEUE:
nfqueue_number = 1
else:
nfqueue_number = 4
def setup():
k_m... | traffic_modifier.py | 3,978 | !/usr/bin/python3 apt install libnetfilter-queue-devpython2return packet.__class__(packet)python3 | 97 | en | 0.402363 |
# Copyright 2018 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... | tensorflow/contrib/metrics/python/ops/metric_ops_large_test.py | 2,653 | Large tests for metric_ops.
Copyright 2018 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 require... | 1,065 | en | 0.861848 |
# -*- coding: utf-8 -*-
import types
import copy
import inspect
import pprint
import re
import sys
import os
import pdb
import warnings
import logging
try:
import cProfile
import pstats
has_debug = True
except ImportError:
has_debug = False
import urlparse
import cgi
from wsgiref.simple_server import... | simpleapi/server/route.py | 23,912 | -*- coding: utf-8 -*- 16 megabytes make shortcut make sure we ignore too large requests for security and stability reasons make sure we only support methods we care respect the first value only XXX TODO GET + POST Make request Make call - recalculate default namespace version - if map has no default version, determin... | 1,520 | en | 0.573967 |
"""
Carbon Scraper Plugin for Userbot. //text in creative way.
usage: .carbon //as a reply to any text message
Thanks to @AvinashReddy3108 for a Base Plugin.
Go and Do a star on his repo: https://github.com/AvinashReddy3108/PaperplaneExtended/
"""
from selenium.webdriver.support.ui import Select
from selenium.webdriv... | stdplugins/carbon.py | 2,805 | Carbon Scraper Plugin for Userbot. //text in creative way.
usage: .carbon //as a reply to any text message
Thanks to @AvinashReddy3108 for a Base Plugin.
Go and Do a star on his repo: https://github.com/AvinashReddy3108/PaperplaneExtended/
Importing message to module Converting to urlencoded this might take a bit.Wa... | 390 | en | 0.77879 |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 31 20:29:57 2014
@author: garrett
"""
from user import User
def save_users(users, filename='output.csv'):
'''Save users out to a .csv file
Each row will represent a user UID, following by all the user's students
(if the user has any)
INPUT:
> ... | save_load.py | 2,145 | Load users from a .csv file
Each row will represent a user uid, following by all the user's student
(if the user has any). Note: the uid is not assumed to be an integer,
so it read in as a string, which shouldn't matter anyway.
TODO: we could probably speed this up by loading multiple lines at a time.
INPUT:
> ... | 769 | en | 0.945442 |
import torch
from torchvision.transforms import functional as TFF
import matplotlib.pyplot as plt
from theseus.base.trainer.supervised_trainer import SupervisedTrainer
from theseus.utilities.loading import load_state_dict
from theseus.classification.utilities.gradcam import CAMWrapper, show_cam_on_image
from theseus.ut... | theseus/classification/trainer/trainer.py | 9,024 | Trainer for classification tasks
Perform simple data analysis
Hook function, called after metrics are calculated
Load all information the current iteration from checkpoint
Sanity check before training
Save all information of the current iteration
Visualize dataloader for sanity check
Visualize mode... | 660 | en | 0.786268 |
#!/usr/bin/env python3
# Copyright (c) 2015-2020 The Beans Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test invalid p2p messages for nodes with bloom filters disabled.
Test that, when bloom filters are not e... | test/functional/p2p_nobloomfilter_messages.py | 1,993 | Add a p2p connection that sends a message and check that it disconnects.
Test invalid p2p messages for nodes with bloom filters disabled.
Test that, when bloom filters are not enabled, peers are disconnected if:
1. They send a p2p mempool message
2. They send a p2p filterload message
3. They send a p2p filteradd messa... | 567 | en | 0.616439 |
# Copyright 2020 The SQLFlow 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 o... | python/runtime/step/xgboost/evaluate.py | 6,618 | Save the evaluation result in the table.
Args:
preds: the prediction result.
feature_file_name (str): the file path where the feature dumps.
label_desc (FieldDesc): the label FieldDesc object.
result_table (str): the result table name.
result_column_names (list[str]): the result column names.
v... | 1,149 | en | 0.745191 |
import datetime
import random
import csv
import sys
book_titles = [
'Advanced Deep Learning with Keras',
'Hands-On Machine Learning for Algorithmic Trading',
'Architects of Intelligence',
'Deep Reinforcement Learning Hands-On',
'Natural Language Processing with TensorFlow',
'Hands-On Reinforcement Learning with Python... | Old Code Backup/chapters9,10,11/_newChapter10/Exercise01/bookr/reviews/management/commands/DjangoWorkshopReviewsData.py | 2,318 | , delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) | 58 | ja | 0.084509 |
from rate_limiter.Limit import Limit
from rate_limiter.Parser import Parser
from rate_limiter.LimitProcessor import LimitProcessor
from rate_limiter.LogLine import LogLine
from typing import Dict, List
from datetime import datetime
class IpRateLimiter:
# used to store unban time. Also used to maintain what is cur... | rate-limiter/rate_limiter/IPRateLimiter.py | 3,274 | used to store unban time. Also used to maintain what is currently banned new ban. Need to print print("{0},UNBAN,{1}".format(self.ipToUnbanTimeMap[ip].timestamp(), ip)) evict expired entries from each processor window check all banned ips if they need to be unbanned process new request in limit processors | 306 | en | 0.868471 |
import numpy as np
import tensorflow as tf
from pyuvdata import UVData, UVCal, UVFlag
from . import utils
import copy
import argparse
import itertools
import datetime
from pyuvdata import utils as uvutils
from .utils import echo
from .utils import PBARS
from . import cal_utils
from . import modeling
import re
OPTIMIZ... | calamity/calibration.py | 77,018 | Simultaneously solve for gains and model foregrounds with DPSS vectors.
Parameters
----------
uvdata: UVData object.
dataset to calibrate and filter.
horizon: float, optional
fraction of baseline delay length to model with dpss modes
unitless.
default is 1.
min_dly: float, optional
minimum delay to... | 29,102 | en | 0.743655 |
"""
Script for processing image (Pre OCR)
"""
import cv2
import numpy as np
import sys
import os.path
if len(sys.argv) != 3:
print "%s input_file output_file" % (sys.argv[0])
sys.exit()
else:
input_file = sys.argv[1]
output_file = sys.argv[2]
if not os.path.isfile(input_file):
print "No such file... | panverification/panapp/process_image.py | 8,320 | Determine pixel intensity Apparently human eyes register colors differently. TVs use this formula to determine pixel intensity = 0.30R + 0.59G + 0.11Bprint "pixel out of bounds ("+str(y)+","+str(x)+")" A quick test to check whether the contour is a connected shape Helper function to return a given contour Count the num... | 1,958 | en | 0.869339 |
from django.forms import (
CheckboxSelectMultiple,
EmailInput,
FileInput,
HiddenInput,
NumberInput,
PasswordInput,
Textarea,
TextInput,
URLInput,
)
from django.utils.safestring import mark_safe
from .bootstrap import get_bootstrap_setting, get_field_renderer, get_form_renderer, get_... | src/bootstrap4/forms.py | 4,809 | Return whether this widget should have a placeholder.
Only text, text area, number, e-mail, url, password, number and derived inputs have placeholders.
Render a button with content.
Render a field to a Bootstrap layout.
Render a field with its label.
Render a form to a Bootstrap layout.
Render form errors to a Bootstr... | 522 | en | 0.729781 |
"""
Revision ID: 0304a_merge
Revises: 0304_remove_org_to_service, 0303a_merge
Create Date: 2019-07-29 16:18:27.467361
"""
# revision identifiers, used by Alembic.
revision = "0304a_merge"
down_revision = ("0304_remove_org_to_service", "0303a_merge")
branch_labels = None
import sqlalchemy as sa
from alembic import o... | migrations/versions/0304a_merge.py | 376 | Revision ID: 0304a_merge
Revises: 0304_remove_org_to_service, 0303a_merge
Create Date: 2019-07-29 16:18:27.467361
revision identifiers, used by Alembic. | 154 | en | 0.427913 |
# Copyright (c) 2019, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions an... | host/synth_bench_power.py | 5,372 | Copyright (c) 2019, Xilinx All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following d... | 2,491 | en | 0.895363 |
def get_workout(day):
if day == 'Monday':
return 'Chest+biceps'
elif day == 'Tuesday':
return 'Back+triceps'
elif day == 'Wednesday':
return 'Core'
elif day == 'Thursday':
return 'Legs'
elif day == 'Friday':
return 'Shoulders'
elif day in ('Saturday', 'Su... | days/34-36-refactoring/refactoring_yo.py | 1,000 | use a dict to sort it out one other way | 39 | en | 0.780382 |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... | src/anf-preview/setup.py | 1,715 | !/usr/bin/env python -------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -------------------------------------------------------... | 357 | en | 0.366555 |
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2015 Tom Barron. All rights reserved.
# Copyright (c) 2016 Mike Rooney. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this... | cinder/volume/drivers/netapp/dataontap/client/client_base.py | 17,722 | Checks whether any LUNs are mapped to the given initiator.
Set up the repository of available Data ONTAP features.
Adds initiators to the specified igroup.
Checks if object is instance of NaElement.
Returns True if initiator exists.
Creates a consistency group snapshot out of one or more flexvols.
ONTAP requires an in... | 2,833 | en | 0.834717 |
#/*
# * Player - One Hell of a Robot Server
# * Copyright (C) 2004
# * Andrew Howard
# *
# *
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation; either
# ... | physicalrobots/player/client_libs/libplayerc/bindings/python/test/test_camera.py | 2,182 | /* * Player - One Hell of a Robot Server * Copyright (C) 2004 * Andrew Howard * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of t... | 1,023 | en | 0.840193 |
from cwltool.main import main
from .util import get_data
def test_missing_cwl_version():
"""No cwlVersion in the workflow."""
assert main([get_data('tests/wf/missing_cwlVersion.cwl')]) == 1
def test_incorrect_cwl_version():
"""Using cwlVersion: v0.1 in the workflow."""
assert main([get_data('tests/w... | tests/test_cwl_version.py | 352 | Using cwlVersion: v0.1 in the workflow.
No cwlVersion in the workflow. | 70 | en | 0.852823 |
# 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... | airflow/providers/cncf/kubernetes/utils/pod_launcher.py | 11,826 | Launches PODS
Status of the PODs
Creates the launcher.
:param kube_client: kubernetes client
:param in_cluster: whether we are in cluster
:param cluster_context: context of the cluster
:param extract_xcom: whether we should extract xcom
Tests if base container is running
Deletes POD
Monitors a pod and returns the fina... | 1,907 | en | 0.829237 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2019-08-25 10:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cre... | meiduo_mall/meiduo_mall/apps/goods/migrations/0001_initial.py | 11,722 | -*- coding: utf-8 -*- Generated by Django 1.11.11 on 2019-08-25 10:18 | 69 | en | 0.508148 |
"""
Low-level wrapper for PortMidi library
Copied straight from Grant Yoshida's portmidizero, with slight
modifications.
"""
import sys
from ctypes import (CDLL, CFUNCTYPE, POINTER, Structure, c_char_p,
c_int, c_long, c_uint, c_void_p, cast,
create_string_buffer, byref)
import c... | mido/backends/portmidi_init.py | 4,277 | Return host error message.
Low-level wrapper for PortMidi library
Copied straight from Grant Yoshida's portmidizero, with slight
modifications.
portmidi.h From portmidi.h PmError enum PmBefore is not defined porttime.h PtError enum | 234 | en | 0.553339 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from niftynet.layer.base_layer import TrainableLayer
from niftynet.layer.convolution import ConvolutionalLayer as Conv
from niftynet.layer.downsample import DownSampleLayer as Down
from niftynet.layer.residual_unit import ResidualUnit as Re... | niftynet/layer/downsample_res_block.py | 2,300 | Consists of::
(inputs)--conv_0-o-conv_1--conv_2-+-(conv_res)--down_sample--
| |
o----------------o
conv_0, conv_res is also returned for feature forwarding purpose
-*- coding: utf-8 -*- | 250 | en | 0.830055 |
#!/usr/bin/env python3
# -*- encoding=utf-8 -*-
# description:
# author:jack
# create_time: 2018/9/17
"""
desc:pass
"""
class __init__:
pass
if __name__ == '__main__':
pass | dueros/directive/Base/__init__.py | 190 | desc:pass
!/usr/bin/env python3 -*- encoding=utf-8 -*- description: author:jack create_time: 2018/9/17 | 103 | en | 0.456587 |
# IDLSave - a python module to read IDL 'save' files
# Copyright (c) 2010 Thomas P. Robitaille
# Many thanks to Craig Markwardt for publishing the Unofficial Format
# Specification for IDL .sav files, without which this Python module would not
# exist (http://cow.physics.wisc.edu/~craigm/idl/savefmt).
# This code was... | scipy/io/idl.py | 26,479 | A case-insensitive dictionary with access via item, attribute, and call
notations:
>>> d = AttrDict()
>>> d['Variable'] = 123
>>> d['Variable']
123
>>> d.Variable
123
>>> d.variable
123
>>> d('VARIABLE')
123
Class used to define object pointers
Class used to define pointers
Alig... | 6,387 | en | 0.806035 |
#!/usr/bin/env python
""" These tests only check whether plots are created,
not that they look correct!
"""
import unittest
import os
import sys
from glob import glob
import numpy as np
import matador.cli.dispersion
from matador.scrapers import res2dict, magres2dict
from matador.hull import QueryConvexHull
from mata... | tests/test_plotting.py | 15,567 | Test the ability to read convergence data and make plots.
Test ability to plot PDF and PXRDs.
Tests for plotting phase diagrams.
Test ability to plot magres data.
Test Dispersion script.
Test plotting BEEF hull.
Test plotting binary hull.
Test plotting binary hull.
Test combined spectral plots.
Test plotting t... | 629 | en | 0.777037 |
# -*- coding: utf-8 -*- #
# Copyright 2015 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 requir... | lib/googlecloudsdk/third_party/apis/cloudbilling/v1/resources.py | 1,429 | Collections for all supported apis.
Resource definitions for cloud platform apis.
-*- coding: utf-8 -*- Copyright 2015 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... | 675 | en | 0.838321 |
# coding: utf-8
"""
Laserfiche API
Welcome to the Laserfiche API Swagger Playground. You can try out any of our API calls against your live Laserfiche Cloud account. Visit the developer center for more details: <a href=\"https://developer.laserfiche.com\">https://developer.laserfiche.com</a><p><strong>Build# ... | laserfiche_api/models/get_edoc_with_audit_reason_request.py | 4,503 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
GetEdocWithAuditReasonRequest - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the audit_reason_id of this GetEdocWithAud... | 1,681 | en | 0.641859 |
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from allauth.socialaccount.helpers import render_authentication_error
from allauth.socialaccount.providers.oauth.client import (OAuthClient,
OAuthError)
from allauth.socia... | allauth/socialaccount/providers/oauth/views.py | 4,176 | Returns a SocialLogin instance
View to handle final steps of OAuth based authentication where the user
gets redirected back to from the service provider
TODO: Can't this be moved as query param into callback? Tried but failed somehow, needs further study... | 259 | en | 0.941127 |
# 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
from ... import _utilities, _tables
from... | sdk/python/pulumi_azure_nextgen/machinelearningservices/v20200901preview/get_machine_learning_compute.py | 5,102 | Machine Learning compute object wrapped into ARM resource envelope.
Use this data source to access information about an existing resource.
:param str compute_name: Name of the Azure Machine Learning compute.
:param str resource_group_name: Name of the resource group in which workspace is located.
:param str workspace_... | 805 | en | 0.847987 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
import os, json, hashlib
from torch.autograd import Function
from http import client as http_client
import antares_custom_op
def generate_antares_expression(antares_ir, inputs):
input_dict, kwargs = {}, {}
for i in range(len(in... | frameworks/antares/pytorch/custom_op.py | 2,541 | Copyright (c) Microsoft Corporation. Licensed under the MIT license. Compile Kernel object | 90 | en | 0.440966 |
# 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... | aliyun-python-sdk-live/aliyunsdklive/request/v20161101/ApplyRecordTokenRequest.py | 1,569 | 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... | 754 | en | 0.883564 |
"""
A simple class to help with paging result sets
"""
import logging
from flask import request, url_for, Markup
__author__ = 'Stephen Brown (Little Fish Solutions LTD)'
log = logging.getLogger(__name__)
class Pager(object):
"""
Standard Pager used on back end of website.
When viewing page 234 of 100... | build/lib/littlefish/pager.py | 8,137 | Use this when you absolutely have to load everything and page in memory. You can access
all of the items through the all_items attribute after initialising this object
Standard Pager used on back end of website.
When viewing page 234 of 1000, the following page links will be displayed:
1, 134, 184, 232, 233, 234, 23... | 1,539 | en | 0.794065 |
"""Support for TPLink HS100/HS110/HS200 smart switch."""
import logging
import time
from pyHS100 import SmartDeviceException, SmartPlug
from homeassistant.components.switch import (
ATTR_CURRENT_POWER_W,
ATTR_TODAY_ENERGY_KWH,
SwitchDevice,
)
from homeassistant.const import ATTR_VOLTAGE
import homeassista... | homeassistant/components/tplink/switch.py | 5,607 | Representation of a TPLink Smart Plug switch.
Initialize the switch.
Check if device is online and add the entity.
Return if switch is available.
Return information about the device.
Return the state attributes of the device.
Return true if switch is on.
Return the name of the Smart Plug.
Turn the switch off.
Turn the ... | 630 | en | 0.807851 |
import cpboard
import periphery
import pytest
import smbus
import sys
def pytest_addoption(parser):
group = parser.getgroup('i2cslave')
group.addoption("--bus", dest='i2cbus', type=int, help='I2C bus number')
group.addoption("--serial-wait", default=20, dest='serial_wait', type=int, help='Number of millise... | tests/i2cslave/conftest.py | 1,708 | __tracebackhide__ = True Hide this from pytest traceback | 57 | en | 0.527233 |
from typing import Dict
# TODO consolidate some of these imports
from vyper.semantics.types.user.struct import StructDefinition
from vyper.semantics.types.value.address import AddressDefinition
from vyper.semantics.types.value.array_value import BytesArrayDefinition
from vyper.semantics.types.value.bytes_fixed import ... | vyper/semantics/environment.py | 1,722 | Get a dictionary of constant environment variables.
Get a dictionary of mutable environment variables (those that are
modified during the course of contract execution, such as `self`).
TODO consolidate some of these imports | 225 | en | 0.935693 |
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
import datetime # for checking renewal date range.
from django import forms
class RenewBookForm(forms.Form):
"""Form for a librarian to renew books."""
renewal_date = forms.DateField(
help_... | catalog/forms.py | 1,477 | Form for a librarian to renew books.
Form for a librarian to renew books.
for checking renewal date range. Check date is not in past. Check date is in range librarian allowed to change (+4 weeks) Remember to always return the cleaned data. Check date is not in future. | 270 | en | 0.900693 |
#!/usr/bin/env python
# Import modules
import numpy as np
import sklearn
from sklearn.preprocessing import LabelEncoder
import pickle
from sensor_stick.srv import GetNormals
from sensor_stick.features import compute_color_histograms
from sensor_stick.features import compute_normal_histograms
from visualization_msgs.ms... | pr2_robot/scripts/project_run.py | 12,299 | !/usr/bin/env python Import modules Helper function to get surface normals Helper function to create a yaml friendly dictionary from ROS messages Helper function to output to yaml file Callback function for your Point Cloud Subscriber Exercise-2 TODOs: TODO: Convert ROS msg to PCL data TODO: Statistical Outlier Filteri... | 3,856 | en | 0.717369 |
#!/usr/bin/env python3
#
# Copyright 2016 WebAssembly Community Group participants
#
# 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
#
# Unles... | test/utils.py | 5,314 | !/usr/bin/env python3 Copyright 2016 WebAssembly Community Group participants 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... | 695 | en | 0.836951 |
import pandas as pd
import os
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, auc
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
import time
#Criteo's CTR Prediction Ch... | AlgPerformComparison.py | 22,555 | Criteo's CTR Prediction ChallengeCreating a list of the numerical and categorical variablesLoad Data (500,000 rows) and name columnsBasic info of datasetNumber of categories per each category variableDelete variables with more than 100 categoriesCreate dummy variables:Creating train and test datasetsTrain, test and Val... | 1,680 | en | 0.73536 |
"""
Train LearnedPDReconstructor on 'lodopab'.
"""
import numpy as np
from dival import get_standard_dataset
from dival.measure import PSNR
from dival.reconstructors.learnedpd_reconstructor import LearnedPDReconstructor
from dival.reference_reconstructors import (
check_for_params, download_params, get_hyper_params... | dival/examples/ct_train_learnedpd.py | 1,633 | Train LearnedPDReconstructor on 'lodopab'.
%% obtain reference hyper parameters%% train%% evaluate | 99 | en | 0.410444 |
import numpy as np
import pytest
from agents.common import BoardPiece, NO_PLAYER, PLAYER1, PLAYER2, pretty_print_board, initialize_game_state, \
string_to_board, apply_player_action, connected_four, check_connect_topleft_bottomright
def test_initialize_game_state():
ret = initialize_game_state()
assert... | tests/test_common.py | 10,743 | str = "|==============|\n|O |\n|X O |\n|O X O |\n|X X O O X |\n|O X O X X |\n|X O X X O |\n|==============|\n|0 1 2 3 4 5 6 |"board = string_to_board(str) | 196 | en | 0.187529 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | docs/samples/specification/multiapi/generated/azure/multiapi/sample/v3/aio/_configuration.py | 3,196 | Configuration for MultiapiServiceClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:keyword api_version: Api Version. The default ... | 954 | en | 0.599426 |
"""
Support for TopoJSON was added in OGR 1.11 to the `GeoJSON` driver.
Starting at GDAL 2.3 support was moved to the `TopoJSON` driver.
"""
import fiona
from fiona.env import GDALVersion
import os
import pytest
from collections import OrderedDict
gdal_version = GDALVersion.runtime()
driver = "TopoJSON" if gdal_vers... | tests/test_topojson.py | 1,362 | Test reading a TopoJSON file
The TopoJSON support in GDAL is a little unpredictable. In some versions
the geometries or properties aren't parsed correctly. Here we just check
that we can open the file, get the right number of features out, and
that they have a geometry and some properties. See GH#722.
Support for Topo... | 436 | en | 0.951312 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Youssef Restom and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.desk.doctype.notification_log.notification_log import (
enqueue_create_notific... | erpnext_telegram_integration/extra_notifications/doctype/extra_notification_log/extra_notification_log.py | 1,206 | -*- coding: utf-8 -*- Copyright (c) 2020, Youssef Restom and contributors For license information, please see license.txt | 121 | en | 0.776156 |
import os
import sys
import logging
from typing import Optional, List
from datetime import datetime
from pythonjsonlogger import jsonlogger
from . import dirs
from .decorators import deprecated
# NOTE: Will be removed in a future version since it's not compatible with running a multi-service process
# TODO: prefix w... | aw_core/log.py | 4,153 | Returns a list with the paths of all available logfiles for `name` sorted by latest first.
Returns the filename of the last logfile with `name`.
Useful when you want to read the logfile of another TimeBench service.
DEPRECATED: Use get_latest_log_file instead.
Used to give JsonFormatter proper parameter format
NOTE: ... | 876 | en | 0.658912 |
# -----------------------------------------------------------------------------
# Task 002
print('''
Задача 002:
===========
Каждый следующий элемент ряда Фибоначчи получается при сложении двух
предыдущих. Начиная с 1 и 2, первые 10 элементов будут:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
\x1b[33m
Найдите сумму... | t002-fibanatchi.py | 1,383 | Считает сумму положительных чисел Фибаначи, которые меньше указанного значения
----------------------------------------------------------------------------- Task 002 Способ 1. Механический. Перебор. пока Единственный сгенерированный ряд >>> [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, ... | 441 | ru | 0.771374 |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
import requests.exceptions
from urlparse import urlsplit
from collections import deque
import re
def crawl(url):
new_urls = deque(["http://{}".format(url)])
processed_urls = set()
emails = []
while ... | autocapstone/email_crawl.py | 1,491 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
##########################################################################
#
# Copyright (c) 2012, Image Engine Design 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:
#
# * Redistrib... | python/GafferUI/PathFilterWidget.py | 4,592 | Copyright (c) 2012, Image Engine Design 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... | 1,990 | en | 0.867643 |
from sympy.core.backend import sin, cos, tan, pi, symbols, Matrix, zeros, S
from sympy.physics.mechanics import (Particle, Point, ReferenceFrame,
RigidBody, Vector)
from sympy.physics.mechanics import (angular_momentum, dynamicsymbols,
inertia, i... | sympy/physics/mechanics/tests/test_functions.py | 9,117 | A rod with length 2l, centroidal inertia I, and mass M along with a
particle of mass m fixed to the end of the rod rotate with an angular rate
of omega about point O which is fixed to the non-particle end of the rod.
The rod's reference frame is A and the inertial frame is N.
Test simple substitution Test smart subst... | 668 | en | 0.878891 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
def Canny(img):
# Gray scale
def BGR2GRAY(img):
b = img[:, :, 0].copy()
g = img[:, :, 1].copy()
r = img[:, :, 2].copy()
# Gray scale
out = 0.2126 * r + 0.7152 * g + 0.0722 * b
out = out.astype(np.uint8)
return out
# Gaussian filter for... | Question_41_50/answers_py/answer_44.py | 5,829 | Gray scale Gray scale Gaussian filter for grayscale Zero padding prepare KernelK /= (sigma * np.sqrt(2 * np.pi)) filtering sobel filter Zero padding Sobel vertical Sobel horizontal filtering get edge strengthfx[np.abs(fx) <= 1e-5] = 1e-5 get edge angle Histeresis threshold 8 - Nearest neighbor grayscale gaussian filter... | 601 | en | 0.469623 |
"""
timedelta support tools
"""
import numpy as np
from pandas._libs.tslibs import NaT
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
from pandas.core.dtypes.common import is_list_like
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.arrays.timedeltas impo... | pandas/core/tools/timedeltas.py | 6,261 | Convert string 'r' to a timedelta object.
Convert a list of objects to a timedelta index object.
Convert argument to timedelta.
Timedeltas are absolute differences in times, expressed in difference
units (e.g. days, hours, minutes, seconds). This method converts
an argument from a recognized timedelta format / value i... | 3,352 | en | 0.511646 |
from functools import reduce
from itertools import chain
from typing import Optional, Set
import pandas as pd
from sqlalchemy import (
func,
or_,
orm,
sql,
)
import fiber
from fiber.condition.base import _BaseCondition
from fiber.database import (
compile_sqla,
read_with_progress,
)
from fiber... | fiber/condition/database.py | 10,518 | The DatabaseCondition adds functionality to the BaseCondition which
is needed to run queries against a database. It also allows to combine
SQL Statements into one to optimize performance. It should only be used by
developers and not by end-users. It builds the basis for specific
conditions like Diagnosis, VitalSign, ..... | 3,448 | en | 0.860749 |
#
# PySNMP MIB module PAN-ENTITY-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///mnt/d/data/MIBS/text_mibs/paloalto/PAN-ENTITY-EXT-MIB
# Produced by pysmi-0.3.4 at Wed Feb 10 13:07:35 2021
# On host QS-IL-COSTAY platform Linux version 5.4.72-microsoft-standard-WSL2 by user coye
# Using Python version 3.8.5 (... | cloudshell/firewall/paloalto/panos/mibs/PAN-ENTITY-EXT-MIB.py | 8,294 | PySNMP MIB module PAN-ENTITY-EXT-MIB (http://snmplabs.com/pysmi) ASN.1 source file:///mnt/d/data/MIBS/text_mibs/paloalto/PAN-ENTITY-EXT-MIB Produced by pysmi-0.3.4 at Wed Feb 10 13:07:35 2021 On host QS-IL-COSTAY platform Linux version 5.4.72-microsoft-standard-WSL2 by user coye Using Python version 3.8.5 (default, Jul... | 339 | en | 0.485229 |
from setuptools import setup, find_packages
# declare these here since we use them in multiple places
_tests_require = [
'pytest',
'pytest-cov',
'flake8',
]
setup(
# package info
name='cheapskate_bal',
description='Cheapskate labs single/dual plane balancer',
version='0.0.2',
url='htt... | cheapskate_bal/setup.py | 1,269 | declare these here since we use them in multiple places package info scripts to install to usr/bin run time requirements exact versions are in the requirements.txt file need this for setup.py test needs this if using setuptools_scm use_scm_version=True, test dependencies this allows us to pip install .[test] for all te... | 335 | en | 0.772972 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Run this script to train a QR-DQN agent in the selected environment
"""
from cnn_deepmind import CNNDeepmind_Multihead
from eqrdqn import QRDQN
from atari_wrappers import make_atari, wrap_deepmind
import pickle
import numpy as np
import matplotlib.pyplot as plt
env ... | Archive/main/Atari/train_atari.py | 1,133 | Run this script to train a QR-DQN agent in the selected environment
!/usr/bin/env python3 -*- coding: utf-8 -*- | 112 | en | 0.682615 |
from ..commands.help import HelpCommand
from ..commands.exit import ExitCommand
from ..commands.purchase import PurchaseCommand
class CommandState:
"""
The __state value should not be accessed directly,
instead the get() method should be used.
"""
__state = {
'commands': {
... | src/state/CommandState.py | 536 | The __state value should not be accessed directly,
instead the get() method should be used. | 91 | en | 0.673408 |
#from sql_gen.sql_gen.filters import *
class Prompter(object):
def __init__(self, template_source):
self.template_source = template_source
def get_prompts(self):
result=[]
for undeclared_var in self.template_source.find_undeclared_variables():
result.append(Prompt(undeclare... | build/lib.linux-x86_64-2.7/sql_gen/sql_gen/prompter.py | 1,121 | from sql_gen.sql_gen.filters import * | 37 | en | 0.232083 |
import logging
import os
import select
import socket
from typing import Union, List
log = logging.getLogger(__name__)
class Receiver:
def __init__(self, irc_socket: socket.socket, socket_timeout: int) -> None:
self._irc_socket = irc_socket
self._socket_timeout = socket_timeout
try:
... | src/receiver/receiver.py | 1,553 | Timeout when connection is lost | 31 | en | 0.894885 |
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | nova/network/model.py | 19,642 | Represents a Fixed IP address in Nova.
Represents an IP address in Nova.
Defines some necessary structures for most of the network models.
Represents a Network in Nova.
Stores and manipulates network information for a Nova instance.
Wrapper around NetworkInfo that allows retrieving NetworkInfo
in an async manner.
This... | 5,285 | en | 0.784527 |
# -*- coding: utf-8 -*-
"""
"""
from ill import api
tn = api.request_document('8236596')
print(tn)
#api.download_papers()
#NOT YET IMPLEMENTED
#Not downloaded
#api.delete_online_papers(api.downloaded_paper_ids)
#main.fill_form('610035')
print('Done with the request') | ill_filler_quick_testing.py | 290 | -*- coding: utf-8 -*-api.download_papers()NOT YET IMPLEMENTEDNot downloadedapi.delete_online_papers(api.downloaded_paper_ids)main.fill_form('610035') | 149 | en | 0.472363 |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import pytest
from flexget.event import fire_event
from flexget.manager import Session
from flexget.plugins.modify.variables import Variables
@pytest.mark.usefixtures('t... | flexget/tests/test_variables.py | 2,813 | noqa pylint: disable=unused-import, redefined-builtin | 53 | en | 0.603729 |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 15:00:26 2018
@author: Alex
# reads and parses local html
"""
#%% Import libraries
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import codecs
import os
import re
import pickle
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
impo... | src/scraping/read_and_parse.py | 6,288 | doc_sents is a list where each element is a list with elements corresponding to individual sentences of a document
Created on Mon Jun 11 15:00:26 2018
@author: Alex
# reads and parses local html
-*- coding: utf-8 -*-%% Import libraries%% Read in saved html read in saved html back in make filename read in file ... | 1,358 | en | 0.742855 |
"""
.. module: lemur.domains.models
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from sqlalchemy import Column, Integer, String, Boolean, Index
from lemur.database impo... | lemur/domains/models.py | 799 | .. module: lemur.domains.models
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com> | 222 | en | 0.432468 |
import cv2
import os
import numpy as np
from image_processor import process_image
from processor_properties import ProcessorProperties
import time
class Camera:
def __init__(self):
self.cap = cv2.VideoCapture(0)
def snapshot(self):
ret, frame = self.cap.read()
return frame
if __nam... | camera_skeleton.py | 973 | props.brightness_factor.update(1.5) props.contrast_factor.update(1.5) props.scaling_factor.update(3.0) | 102 | en | 0.146492 |
# encoding: utf-8
"""Placeholder-related objects.
Specific to shapes having a `p:ph` element. A placeholder has distinct behaviors
depending on whether it appears on a slide, layout, or master. Hence there is a
non-trivial class inheritance structure.
"""
from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER
f... | pptx/shapes/placeholder.py | 14,539 | NOTE: This class is deprecated and will be removed from a future release
along with the properties *idx*, *orient*, *ph_type*, and *sz*. The *idx*
property will be available via the .placeholder_format property. The
others will be accessed directly from the oxml layer as they are only
used for internal purposes.
Base ... | 6,617 | en | 0.837379 |
# #########################################################################
# Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
# #
# See LICENSE file. #
# ##############... | scripts/alien_tools.py | 16,598 | Analyzes clusters and returns characteristics in arrays.
Parameters
----------
arr : ndarray
the analyzed array
labels: arr
cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1.
nz : tuple
tuple of arrays, each array containing indices of elements in arr that ar... | 7,438 | en | 0.672048 |
#!/usr/bin/env python2
import rospy
from gnss_status_viewer import Status
from nmea_msgs.msg import Sentence
import sys
import copy
# Previous and current Status
prev = None
curr = None
def print_current_status(status):
"""
Prints the current status
:param status:
:return:
"""
print(status)... | nodes/gnss_status_viewer_node.py | 1,045 | Prints the current status
:param status:
:return:
!/usr/bin/env python2 Previous and current Status Move to the beginning of the previous line | 143 | en | 0.683492 |
'''
Generate uv position map of 300W_LP.
'''
import os, sys
import numpy as np
import scipy.io as sio
import random as ran
from skimage.transform import SimilarityTransform
from skimage import io, util
import skimage.transform
from time import time
import cv2
import matplotlib.pyplot as plt
sys.path.append('..')
impor... | get_300WLP_maps.py | 6,029 | Generate uv position map of 300W_LP.
add z 1. load image and fitted parameters 2. generate mesh; generate shape transform mesh using stantard camera & orth projection as in 3DDFA 3. crop image with key points random pertube. you can change the numbers crop and record the transform parameters transform face position(i... | 878 | en | 0.442137 |
# Generated by Django 3.1.1 on 2022-01-06 23:38
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '00... | pokedex/accounts/migrations/0001_initial.py | 3,324 | Generated by Django 3.1.1 on 2022-01-06 23:38 | 45 | en | 0.689532 |
# coding=utf-8
# Copyright 2020 The Edward2 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... | baselines/imagenet/ensemble.py | 10,015 | Negative log-likelihood for ensemble.
For each datapoint (x,y), the ensemble's negative log-likelihood is:
```
-log p(y|x) = -log sum_{m=1}^{ensemble_size} exp(log p(y|x,theta_m)) +
log ensemble_size.
```
Args:
labels: tf.Tensor of shape [...].
logits: tf.Tensor of shape [ensemble_size, ..., num_cl... | 1,892 | en | 0.744296 |
from collections import defaultdict
from .tree import Tree
from .visitors import Transformer_InPlace
from .common import ParserConf
from .lexer import Token, PatternStr
from .parsers import earley
from .grammar import Rule, Terminal, NonTerminal
def is_discarded_terminal(t):
return t.is_term and t.filter_out
d... | lark/reconstruct.py | 4,424 | if not isinstance(t, MatchTree): return t XXX TODO calling compile twice returns different results! Skip self-recursive constructs TODO: ambiguity? TODO pass callbacks through dict, instead of alias? find a full derivation | 223 | en | 0.653066 |
"""py.test fixtures for Pyramid.
http://pyramid.readthedocs.org/en/latest/narr/testing.html
"""
import datetime as datetime_module
import logging
import os
import pkg_resources
import pytest
import webtest
from dcicutils.qa_utils import notice_pytest_fixtures, MockFileSystem
from pyramid.request import apply_reques... | src/encoded/tests/conftest.py | 11,909 | Caches whether or not we have already provisioned the workbook.
TestApp simulating a bare Request entering the application (with ES enabled)
TestApp with ES + Postgres for anonymous (not logged in) user, accepting text/html content.
TestApp for anonymous (not logged in) user, accepting text/html content.
TestApp for ... | 3,804 | en | 0.509594 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | test/azure/legacy/Expected/AcceptanceTests/AzureSpecials/azurespecialproperties/operations/_api_version_local_operations.py | 12,174 | ApiVersionLocalOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azurespecialproperties.models
:param client... | 3,148 | en | 0.587271 |
import os
from glob import glob
from tqdm import tqdm
from pathlib import Path
# from kaggle_isic_2020.lib import dirs # Doesn't work on unix, why?
# Test
source_dir = "/home/common/datasets/SIIM-ISIC_2020_Melanoma/jpeg/test/"
dest_dir = "/home/common/datasets/SIIM-ISIC_2020_Melanoma/jpeg/test_compact/"
# dirs.crea... | dataset_stats/convert_dataset_test_set.py | 606 | from kaggle_isic_2020.lib import dirs Doesn't work on unix, why? Test dirs.create_folder(dest_dir) | 99 | en | 0.564324 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import pdb
import numpy as np
from os.path import join
from ops import l2_dist_360
from MeanOverlap import MeanOverlap
def catData(totalData, newData):
""" Concat data from scratch """
if totalData is None:
totalData = newData[np.newaxis].copy(... | Deep360Pilot-CVPR17-tf1.2/util.py | 6,855 | !/usr/bin/env python -*- coding: utf-8 -*-(n_frames*batch_size)[0:Agent.batch_size,0:Agent.n_frames,0:Agent.n_detection,0:Agent.n_input][0:Agent.batch_size,0:Agent.n_frames,0:Agent.n_classes+1][0:Agent.batch_size,0:Agent.n_frames,0:Agent.n_detection][0:Agent.batch_size,0:Agent.n_frames,0:Agent.n_detection,0:Agent.n_bin... | 514 | en | 0.47767 |
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2015, Code for America
# This is open source software, released under a standard 3-clause
# BSD-style license; see the file LICENSE for details.
import os
import datetime
import re
from flask import Flask, render_template, request, abort, redirect, url_for, make_response, ... | app.py | 18,492 | Fix up an SR to try and ensure some basic info.
(In Chicago's API, any field can be missing, even if it's required.)
Returns string representing "time since"
or "time until" e.g.
3 days ago, 5 hours from now etc.
Add some goodies to all templates.
Slightly improved title() method for address strings
Makes sure state ab... | 3,949 | en | 0.77852 |
# Copyright 2015 moco_beta
#
# 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, softwa... | tests/test_dic.py | 11,845 | Copyright 2015 moco_beta 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 und... | 1,522 | en | 0.776556 |
# -*- coding: utf-8 -*-
"""Top-level package for PrecisionMapper."""
import requests
from requests import ConnectionError
from datetime import datetime
from bs4 import BeautifulSoup
__author__ = """Thibault Ducret"""
__email__ = 'hello@tducret.com'
__version__ = '0.0.2'
_DEFAULT_BEAUTIFULSOUP_PARSER = "html.parser"... | precisionmapper/__init__.py | 9,394 | Do the requests with the servers
Class for the communications with precisionmapper.com
Class for a drone survey (mission)
Returns the content of the element pointed by the CSS selector,
or an empty string if not found
Returns a date string to the RFC 3339 standard
Returns a short date string
Returns a date string... | 617 | en | 0.719309 |
from __future__ import absolute_import, unicode_literals
import sys
from subprocess import CalledProcessError
import pytest
from virtualenv.info import PY2
from virtualenv.seed.wheels.acquire import download_wheel, pip_wheel_env_run
from virtualenv.seed.wheels.embed import BUNDLE_FOLDER, get_embed_wheel
from virtual... | tests/unit/seed/wheels/test_acquire.py | 2,397 | if the download contains no match for what wheel was downloaded, pick one that matches from target | 98 | en | 0.967487 |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Mario Lassnig, <mar... | lib/rucio/core/identity.py | 7,040 | Adds a membership association between identity and account.
:param identity: The identity key name. For example x509 DN, or a username.
:param type: The type of the authentication (x509, gss, userpass, ssh, saml).
:param account: The account name.
:param email: The Email address associated with the identity.
:param de... | 2,682 | en | 0.658794 |
import pygame
import os
from pygame.locals import *
import config
import game
import engine
import menu
from random import randint
import _fighter
from pygame_functions import *
class Scenario:
def __init__(self, game, scenario):
self.game = game
self.scenario = scenario
pygame.mixer... | .history/src/fightScene_20190422211023.py | 11,465 | self.scene = pygame.image.load('../res/Background/Scenario'+str(scenario)+'.png')self.game.getDisplay().blit(self.scene, (0, 0))pygame.display.update()screenSize(800, 500,"pyKombat",None,None,True) FullScreen Minimizedprint(x1, x2, x2-x1) caso encostem na tela caso só encostem caso houve soco fraco: caso houve soco fo... | 773 | pt | 0.793027 |
try:
from django.utils.unittest import TestCase
except ImportError:
from django.test import TestCase
try:
from django.utils import unittest
except ImportError:
import unittest
from mock import Mock
import string
from evennia.server.portal import irc
from twisted.conch.telnet import IAC, WILL, DONT, S... | evennia/server/portal/tests.py | 6,017 | Test that the composition of the function and
its inverse gives the correct string.
Test that printable characters do not get mangled.
test suppress_ga test naws test ttype test mccp test mssp test oob test mxp clean up to prevent Unclean reactor | 248 | en | 0.7908 |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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... | Wrapping/WrapITK/Languages/Python/itkExtras/__init__.py | 33,093 | ========================================================================== Copyright Insight Software Consortium 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... | 5,612 | en | 0.786697 |
from mwb_help import deck_is_available, create_deck,\
model_is_available, add_model, add_note
from scraper_lxml import get_note_default, get_note_simple
class AnkiDutchDeck():
def __init__(self, deck_name=None):
if deck_name is None:
deck_name = 'tidbits'
if not deck_is_available(... | add_cards.py | 3,887 | word_list = ['hhhsss', 'duits', 'alsjeblieft', 'waterpokken'] | 61 | nl | 0.418032 |
#!/usr/bin/env python
from distutils.core import setup
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='pyzkaccess',
description='Python interface to ZKTeco ZKAccess C3-100/200/400 controllers',
version='0.2',
author='Igor Derkach',
author_email=... | setup.py | 1,166 | !/usr/bin/env python Also tox.ini | 33 | en | 0.547123 |
from genomics_demo.dna import DNA
import pytest
def test_bad_sequence_raises_error():
with pytest.raises(ValueError):
DNA('ATB')
def test_complimentary_sequence_works():
assert DNA('GTC').complimentary_sequence == DNA('CAG')
assert DNA('ATC').complimentary_sequence == DNA('TAG')
assert DNA('... | tests/test_dna.py | 1,751 | New test to test the function to find start codons
def test_gc_content_sequence_works(): assert DNA('GC').gc_content > 0.5 length = len(sequence) c_count = sequence.upper().count('C') g_count = sequence.upp | 212 | en | 0.560475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.