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 |
|---|---|---|---|---|---|---|
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Extended thread dispatching support.
For basic support see reactor threading API docs.
"""
from twisted.python.compat import _PY3
if not _PY3:
import Queue
else:
import queue as Queue
from twisted.python import failure
from twisted... | src/twisted/internet/threads.py | 3,904 | Run a list of functions.
Run a function in the reactor from a thread, and wait for the result
synchronously. If the function returns a L{Deferred}, wait for its
result and return that.
@param reactor: The L{IReactorThreads} provider which will be used to
schedule the function call.
@param f: the callable to run i... | 2,235 | en | 0.742232 |
from datetime import datetime
from astropy.time import Time
def read_tle_file(tlefile, **kwargs):
"""
Read in a TLE file and return the TLE that is closest to the date you want to
propagate the orbit to.
"""
times = []
line1 = []
line2 = []
from os import path
... | nustar_lunar_pointing/tracking.py | 4,544 | Converts MET seconds to a datetime object.
Default is to subtract off 5 leap seconds.
Convert Earth-Centered Inertial (ECI) cartesian coordinates to ITRS for astropy EarthLocation object.
Inputs :
x = ECI X-coordinate
y = ECI Y-coordinate
z = ECI Z-coordinate
dt = UTC time (datetime object)
Find the TLE that is cl... | 1,232 | en | 0.8301 |
from __future__ import unicode_literals
from future.builtins import int, range, str
from datetime import date, datetime
from os.path import join, split
from uuid import uuid4
from django import forms
from django.forms.extras import SelectDateWidget
from django.core.files.storage import FileSystemStorage
from django.c... | zhiliao/forms/forms.py | 18,302 | Form with a set of fields dynamically assigned that can be used to
filter entries for the given ``forms.models.Form`` instance.
Form with a set of fields dynamically assigned, directly based on the
given ``forms.models.Form`` instance.
Dynamically add each of the form fields for the given form model
instance and its re... | 2,787 | en | 0.872793 |
# -*- coding: utf-8 -*-
import json
import datetime
class JobHeader:
"""Represents a row from the callout."""
def __init__(self, raw_data):
self.attributes = {
"contractor": json.dumps(raw_data[0]),
"job_name": json.dumps(raw_data[1]),
"is_dayshift": js... | DataObjects.py | 5,796 | Represents a row from the callout.
Find lines matching stripped from lineMatchKeys and set value to immediately following row
-*- coding: utf-8 -*- 2 spaces typo print("Element {0} is not bold enough for my needs.".format(row)) parse checkboxes inputs = row.find_all("input") if inputs: self.attrDic["Shift:"] = "... | 456 | en | 0.527906 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
----------------------
Asynchronous SqlHelper
----------------------
TODO:
#. Transaction
Examples:
Simple Usage:
::
from kipp.aio import SqlHelper, run_until_complete, coroutine2
@coroutine2
def main():
db = SqlHel... | kipp/aio/sqlhelper.py | 2,080 | ----------------------
Asynchronous SqlHelper
----------------------
TODO:
#. Transaction
Examples:
Simple Usage:
::
from kipp.aio import SqlHelper, run_until_complete, coroutine2
@coroutine2
def main():
db = SqlHelper('movoto')
r = yield db.getOneBySql(... | 457 | en | 0.37188 |
#!/usr/bin/env python3
import argparse
import collections
import hashlib
import itertools
import os
import re
import sys
import statistics
import subprocess
import tempfile
import time
import pprint
import json
from collections import namedtuple
# Argument parser
parser = argparse.ArgumentParser(description="""
C... | etc/compare.py | 12,544 | !/usr/bin/env python3 Argument parser Ensure that the input files are readable Check that valgrind is available for memory measurement Program execution definition args is required Compressor Pair definition Define suite Evaluate suite as Python sanity checks default tudocomp examples Tudocomp(name='lfs_st', ... | 679 | en | 0.512554 |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class StopAppResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and... | huaweicloud-sdk-cloudrtc/huaweicloudsdkcloudrtc/v2/model/stop_app_response.py | 4,312 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
StopAppResponse - a model defined in huaweiclou... | 1,142 | en | 0.668513 |
'''
Description:
Play music on Spotify with python.
Author: AlejandroV
Version: 1.0
Video: https://youtu.be/Vj64pkXtz28
'''
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import webbrowser as web
import pyautogui
from time import sleep
# your credentials
client_id = 'YOUR_CLIEN... | playmusic_spoty.py | 1,219 | Description:
Play music on Spotify with python.
Author: AlejandroV
Version: 1.0
Video: https://youtu.be/Vj64pkXtz28
your credentials artist and name of the song authenticate songs by artist if song by artist not found | 220 | en | 0.88465 |
# Copyright 2018 The Texar 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 ... | texar/tf/utils/utils.py | 34,576 | Replaces common shorthands with respective full names.
"tf.xxx" --> "tensorflow.xxx"
"tx.xxx" --> "texar.tf.xxx"
Returns `inspect.getargspec(fn)` for Py2 and `inspect.getfullargspec(fn)`
for Py3
Splits (possibly nested list of) strings recursively.
Calls a function and returns the results.
Only those keyword arg... | 19,876 | en | 0.693667 |
#!/usr/bin/env python3
from helper import lemniscate, saveImage, getImageName
from math import pi
from random import uniform
IMAGE_WIDTH_IN = 5
IMAGE_HEIGHT_IN = 2
DPI = 400
def makeImage(height, width, imageName):
k = 1.9
numSamples = 100000000
imageWidth = width
imageHeight = height
data = [... | presentation/presentation_images/genImage_07.py | 1,282 | !/usr/bin/env python3 need to increase range for complete curve pick a random point on the line segment [pA, pB] | 112 | en | 0.764042 |
import magma as m
from magma import *
def test_pair():
# types
A2 = Tuple[Bit, Bit]
print(A2)
assert isinstance(A2, TupleMeta)
print(str(A2))
assert A2 == A2
B2 = Tuple[In(Bit), In(Bit)]
assert isinstance(B2, TupleMeta)
assert B2 == B2
C2 = Tuple[Out(Bit), Out(Bit)]
asse... | tests/test_type/test_tuple.py | 7,648 | typesassert str(C2) == 'Tuple(x=Out(Bit),y=Out(Bit))' typesassert str(A2) == 'Tuple(x=Bit,y=Bit)'assert str(B2) == 'Tuple(x=In(Bit),y=In(Bit))'assert str(C2) == 'Tuple(x=Out(Bit),y=Out(Bit))'T = Flip(Tout)assert T == Tin print(T)T = Flip(Tin)assert T == Tout print(T) constructor selectors Test for https://github.com/ph... | 344 | en | 0.30658 |
# -*- coding: utf-8 -*-
{
'name': 'Payment - Account',
'category': 'Accounting/Accounting',
'summary': 'Account and Payment Link and Portal',
'version': '1.0',
'description': """Link Account and Payment and add Portal Payment
Provide tools for account-related payment as well as portal options to
e... | odoo-13.0 - Copy/addons/account_payment/__manifest__.py | 503 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
ximport tulip
def reader(s):
res = yield from s.read(1)
while res:
print ('got data:', res)
res = yield from s.read(1)
def main(stream):
stream2 = tulip.StreamReader()
# start separate task
t = tulip.async(reader(stream2))
while 1:
data = yield from... | lib/asyncio-0.4.1/sched_test.py | 747 | start separate taskyield from t | 31 | en | 0.726265 |
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import ClockCycles, ReadWrite, NextTimeStep, RisingEdge, FallingEdge
from cocotb.binary import BinaryValue
import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import butter, filtfilt
from fixedpoint import FixedPoint
@cocotb.test(... | fpga/test/featurize/actigraphy_counts/actigraphy_counts_tb.py | 1,770 | count_feature = np.loadtxt('46343_cleaned_counts.out', delimiter=' ') cf_low = 3 cf_hi = 11 order = 5 w1 = cf_low / (fs / 2) w2 = cf_hi / (fs / 2) pass_band = [w1, w2] b, a = butter(order, pass_band, 'bandpass') z_filt = filtfilt(b, a, z_accel)count_feature = count_feature[::num_epochs] Reset logic | 299 | en | 0.762771 |
import getpass
import logging
import os
from urlparse import urlparse
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from readthedocs.builds.constants import LATEST
from readthedocs.builds.constants import LATEST_VERBOSE_NAME
from ... | readthedocs/core/utils/__init__.py | 3,304 | A helper to copy a single file across app servers
Send multipart email
recipient
Email recipient address
subject
Email subject header
template
Plain text template to send
template_html
HTML template to send as new message part
context
A dictionary to pass into the template calls
request
Re... | 427 | en | 0.681242 |
# -*- coding: utf-8 -*-
from music21.test.dedent import dedent
__all__ = [
'dedent',
'testDocumentation',
'testExternal',
'testPerformance',
'timeGraphs',
'testStream',
'helpers',
]
import sys
if sys.version > '3':
from music21.test import testStream
from music21.test imp... | lib/music21/test/__init__.py | 549 | -*- coding: utf-8 -*- @Reimport @Reimport------------------------------------------------------------------------------ eof | 123 | en | 0.188308 |
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 it manually
# noinspection PyPep8Naming
class MedicationKnowledge_AdministrationGuidelinesSchema:
"""
Information abo... | spark_fhir_schemas/r4/complex_types/medicationknowledge_administrationguidelines.py | 13,340 | Information about a medication that is used to support knowledge.
Information about a medication that is used to support knowledge.
id: Unique id for the element within a resource (for internal references). This
may be any string value that does not contain spaces.
extension: May be used to represent additional ... | 3,833 | en | 0.879913 |
"""
LoSetup - command ``/usr/sbin/losetup -l``
==========================================
This parser reads the output of ``/usr/sbin/losetup -l`` into a list of entries.
Each entry is a dictionary of headers:
* ``NAME`` - the path name of the loop back device (strings)
* ``SIZELIMIT`` - the data end position of back... | insights/parsers/losetup.py | 2,193 | Parses the output of the ``/usr/sbin/losetup -l`` command.
LoSetup - command ``/usr/sbin/losetup -l``
==========================================
This parser reads the output of ``/usr/sbin/losetup -l`` into a list of entries.
Each entry is a dictionary of headers:
* ``NAME`` - the path name of the loop back device (s... | 1,474 | en | 0.553204 |
import asyncio
import concurrent
from concurrent.futures import ThreadPoolExecutor
from unittest import TestCase
import os
import cv2
from apscheduler.schedulers.background import BackgroundScheduler
import bot
from bot.providers import trainer_matches as tm
from bot.duel_links_runtime import DuelLinkRunTime
from bo... | tests/providers/test_steam_.py | 6,900 | t.show_area_bounded(self.provider.predefined.main_area, img) t._debug = True t.compare() t.show_area_bounded(self.provider.predefined.main_area, img) t._debug = True t.compare() t.show_area_bounded(self.provider.predefined.main_area, img) t._debug = True t.show_area_bounded(self.provider.predefined.main_area, img) t._d... | 425 | fa | 0.042188 |
from ..errors import MalformedResponseError
from ..properties import FailedMailbox, SearchableMailbox
from ..util import MNS, add_xml_child, create_element
from ..version import EXCHANGE_2013
from .common import EWSService
class GetSearchableMailboxes(EWSService):
"""MSDN:
https://docs.microsoft.com/en-us/exc... | exchangelib/services/get_searchable_mailboxes.py | 2,114 | MSDN:
https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/getsearchablemailboxes-operation
Responses may contain no mailboxes of either kind. _get_element_container() does not accept this. | 219 | en | 0.601767 |
#!/usr/bin/env python2
# coding=utf-8
# ^^^^^^^^^^^^ TODO remove when supporting only Python3
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework... | qa/rpc-tests/wallet.py | 15,632 | !/usr/bin/env python2 coding=utf-8 ^^^^^^^^^^^^ TODO remove when supporting only Python3 Copyright (c) 2014-2015 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. allow the node's estimation to be at most 2 by... | 3,012 | en | 0.823305 |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... | correct_batch_effects_wdn/transform_test.py | 7,074 | Tests for Transform library.
coding=utf-8 Copyright 2020 The Google Research 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 ... | 959 | en | 0.89004 |
# -*- coding=utf-8 -*-
"""
# library: jionlp
# author: dongrixinyu
# license: Apache License 2.0
# Email: dongrixinyu.89@163.com
# github: https://github.com/dongrixinyu/JioNLP
# description: Preprocessing tool for Chinese NLP
"""
__version__ = '1.3.49'
import os
from jionlp.util.logger import set_logger
from jionl... | jionlp/__init__.py | 5,700 | # library: jionlp
# author: dongrixinyu
# license: Apache License 2.0
# Email: dongrixinyu.89@163.com
# github: https://github.com/dongrixinyu/JioNLP
# description: Preprocessing tool for Chinese NLP
-*- coding=utf-8 -*- unzip dictionary files from jionlp.util.fast_loader import FastLoader rule = FastLoader('rule', g... | 344 | en | 0.408435 |
"""
This module contains the lambda function code for put-storage-tags API.
This file uses environment variables in place of config; thus
sddcapi_boot_dir is not required.
"""
# pylint: disable=import-error,logging-format-interpolation,broad-except,too-many-statements,C0413,W1203,R1703,R0914
import boto3
import botoc... | boto3_proxy/index.py | 7,752 | Boto3 Proxy API Handler
This module contains the lambda function code for put-storage-tags API.
This file uses environment variables in place of config; thus
sddcapi_boot_dir is not required.
pylint: disable=import-error,logging-format-interpolation,broad-except,too-many-statements,C0413,W1203,R1703,R0914 boto3-prox... | 931 | en | 0.60733 |
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
"""Test waiting for db when db is available"""
with patch('django.db.utils... | app/core/tests/test_commands.py | 1,228 | Test waiting for db
Test waiting for db when db is available
Checking is mock object gi was called only once The patch as a decorator will pass the argument to the test below it When the ConnectionHandler raised OperationalError, then it waits for 1 sec and tries again. Delay here can be removed in the unit test by u... | 406 | en | 0.909335 |
#coding=utf-8
#
# Copyright (C) 2015 Feigr TECH Co., Ltd. All rights reserved.
# Created on 2013-8-13, by Junn
#
#
#import settings
from django.middleware.csrf import get_token
from django.http.response import Http404
from django.core.exceptions import PermissionDenied
from rest_framework.generics import GenericAPIVi... | apps/core/views.py | 4,016 | customize the APIView for customize exception response
customize the response for csrf_token invalid
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
coding=utf-8 Copyright (C) 2015 Feigr TECH Co., Ltd. All rights reserved. Created on 2013-8-13, by Junnimport settings if... | 477 | en | 0.631501 |
import os
from pathlib import Path
from dataclasses import field
from typing import Dict, Tuple, Sequence
from pydantic.dataclasses import dataclass
from pydantic import StrictStr
@dataclass
class StreetViewConfig:
SIZE: str = "600x300"
HEADING: str = "151.78"
PITCH: str = "-0.76"
KEY = os.environ.ge... | open_geo_engine/config/model_settings.py | 25,430 | NAME = "Iraqi Kurdistan" ADMIN_LEVEL = 3 | 40 | en | 0.770703 |
"""
Django settings for profiles project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
... | profiles/settings.py | 3,213 | Django settings for profiles project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
Build paths inside... | 989 | en | 0.673419 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
# Though the following import is not directly being used, it is required
# for 3D projection to work
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn import ... | k-means.py | 2,301 | Though the following import is not directly being used, it is required for 3D projection to work Plot the ground truth Reorder the labels to have colors matching the cluster results | 181 | en | 0.923802 |
# -*- coding: utf-8 -*-
import time
import mock
import pytest
import requests
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from anacode import codes
from anacode.api import client
from anacode.api import writers
def empty_response(*args, **kwargs):
resp = reques... | tests/test_api_client.py | 5,532 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# coding: utf-8
# AUTOGENERATED BY gen_script.sh from kp1.py
# Copyright (C) Nyimbi Odero, Thu Aug 3 20:34:20 EAT 2017
import calendar
from flask import redirect, flash, url_for, Markup
from flask import render_template
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.views i... | zarc/views_2017-08-03-21:28:54.py | 81,025 | coding: utf-8 AUTOGENERATED BY gen_script.sh from kp1.py Copyright (C) Nyimbi Odero, Thu Aug 3 20:34:20 EAT 2017 Basic Lists To pretty Print from PersonMixin MasterDetailView, MultipleViewadd_title =list_title =edit_title =show_title =add_widget = (FormVerticalWidget|FormInlineWidget)show_widget = ShowBlockWidgetlist... | 40,109 | en | 0.232496 |
import importlib.util
import logging
import re
import time
from collections import defaultdict
from inspect import getsource
from pathlib import Path
from types import ModuleType
from typing import Dict, List, Set, Type
import click
from flask_appbuilder import Model
from flask_migrate import downgrade, upgrade
from g... | scripts/benchmark_migration.py | 6,911 | 提取由迁移脚本修改的表。
此函数使用一种简单的方法来查看迁移脚本的源代码以查找模式。它可以通过实际遍历AST来改进。
在迁移脚本中查找所有模型。
:param module:
:return:
像导入模块一样导入迁移脚本。
:param filepath: 文件路径对象。
:return:
pylint: disable=wrong-import-order 添加在迁移脚本中显式定义的模型 添加隐式模型 按拓扑排序,这样我们可以按顺序创建实体并维护关系(例如,在创建切片之前创建数据库) delete in reverse order of creation to handle relationships | 310 | zh | 0.928709 |
# coding: utf-8
"""
Flat API
The Flat API allows you to easily extend the abilities of the [Flat Platform](https://flat.io), with a wide range of use cases including the following: * Creating and importing new music scores using MusicXML, MIDI, Guitar Pro (GP3, GP4, GP5, GPX, GP), PowerTab, TuxGuitar and Mus... | test/test_collection.py | 2,446 | Collection unit test stubs
Test Collection
Flat API
The Flat API allows you to easily extend the abilities of the [Flat Platform](https://flat.io), with a wide range of use cases including the following: * Creating and importing new music scores using MusicXML, MIDI, Guitar Pro (GP3, GP4, GP5, GPX, GP), PowerTab, Tux... | 1,995 | en | 0.720016 |
# Copyright (C) 2020 Red Hat, 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 writ... | examples/group_membership_watch.py | 1,042 | Copyright (C) 2020 Red Hat, 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, software dist... | 628 | en | 0.856543 |
# -*- coding: utf-8 -*-
# @Time: 2020/4/17 12:40
# @Author: GraceKoo
# @File: 241_different-ways-to-add-parentheses.py
# @Desc: https://leetcode-cn.com/problems/different-ways-to-add-parentheses/
from typing import List
class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
if input.isdigit... | Codes/gracekoo/241_different-ways-to-add-parentheses.py | 1,027 | -*- coding: utf-8 -*- @Time: 2020/4/17 12:40 @Author: GraceKoo @File: 241_different-ways-to-add-parentheses.py @Desc: https://leetcode-cn.com/problems/different-ways-to-add-parentheses/ 合并结果 | 190 | en | 0.387455 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projeto_curso_2.settings')
try:
from django.core.management import execute_from_command_line
exc... | Python/Django/projeto_curso_2/manage.py | 671 | Run administrative tasks.
Django's command-line utility for administrative tasks.
!/usr/bin/env python | 103 | en | 0.725633 |
# Generated by Django 3.1.7 on 2021-03-07 11:27
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('app', '0005_auto_20210303_1338'),
]
operations = [
migrations.Create... | app/migrations/0006_house.py | 669 | Generated by Django 3.1.7 on 2021-03-07 11:27 | 45 | en | 0.705565 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import select
import socket
import queue
import time
import os
class emsc_select_server:
def __init__(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setblocking(False)
self.server.setsockopt(socket.SOL_SOCKET... | run/server_select.py | 3,253 | !/usr/bin/env python -*- coding: utf-8 -*- timeout是超时,当前连接要是超过这个时间的话,就会kill 通过inputs查看是否有客户端来 添加通道 清除队列信息 stop listening for input on the connection 清除队列信息 | 155 | zh | 0.662174 |
# File: __init__.py
#
# Copyright (c) 2018-2019 Splunk 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 applicabl... | __init__.py | 604 | File: __init__.py Copyright (c) 2018-2019 Splunk 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 ... | 575 | en | 0.844312 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import os... | sdk/communication/azure-communication-sms/tests/test_sms_client_e2e_async.py | 1,824 | ------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -------------------------------------------------------------------------- calling send() with ... | 348 | en | 0.395208 |
"""
Ex 012 - make an algorithm that reads the price of a product and shows it with 5% discount
"""
print('Discover how much is a product with 5% off discount')
print('-' * 50)
pp = float(input('Enter the product price: '))
pd = pp - (pp / 100) * 5
print('-' * 50)
print(f"The product price was {pp:.2f}, on promotion ... | Ex12.py | 371 | Ex 012 - make an algorithm that reads the price of a product and shows it with 5% discount | 90 | en | 0.957279 |
# 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
from... | sdk/python/pulumi_aws_native/sagemaker/feature_group.py | 15,772 | The set of arguments for constructing a FeatureGroup resource.
:param pulumi.Input[str] event_time_feature_name: The Event Time Feature Name.
:param pulumi.Input[Sequence[pulumi.Input['FeatureGroupFeatureDefinitionArgs']]] feature_definitions: An Array of Feature Definition
:param pulumi.Input[str] record_identifier_fe... | 2,739 | en | 0.625668 |
from django.contrib import admin
from django.urls import path
from django.contrib.auth.views import LoginView
from . import views
app_name = 'users'
urlpatterns = [
# ex /users/
path('', views.index, name='index'),
# ex /users/login/
path('login/', LoginView.as_view(template_name='users/login.html'),... | users/urls.py | 517 | ex /users/ ex /users/login/ ex /users/logout/ ex /users/register/ | 65 | en | 0.192976 |
import mido
import json
import time
from math import floor
import board
import busio
import digitalio
import adafruit_tlc5947
def playMidi(song_name):
mid = mido.MidiFile('midifiles/' + song_name)
notesDict = {'songName': 'testname', 'bpm': 999, 'notes': []}
tempo = 0
length = 0
notesArray = [[]... | play_midi_curtis.py | 3,453 | Initialize SPI bus. Initialize TLC5947print(msg) send array to PWM IC time.sleep(tickLength)playMidi('twinkle_twinkle.mid')playMidi('for_elise_by_beethoven.mid') playMidi('debussy_clair_de_lune.mid') playMidi('chopin_minute.mid') playMidi('jules_mad_world.mid') | 261 | en | 0.346804 |
# -*- coding: utf-8 -*-
# vim: ts=2 sw=2 et ai
###############################################################################
# Copyright (c) 2012,2013-2021 Andreas Vogel andreas@wellenvogel.net
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documen... | server/handler/avnuserapps.py | 11,533 | handle the files in the user directory
called by the user handler when a user file is deleted
@param url:
@return:
-*- coding: utf-8 -*- vim: ts=2 sw=2 et ai Copyright (c) 2012,2013-2021 Andreas Vogel andreas@wellenvogel.net Permission is hereby granted, free of charge, to any person obtaining a copy of this softwa... | 1,714 | en | 0.851534 |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "styx"
PROJECT_SPACE_DIR = "/home/zche... | ros/build/styx/catkin_generated/pkg.develspace.context.pc.py | 381 | generated from catkin/cmake/template/pkg.context.pc.in | 54 | en | 0.406568 |
"""empty message
Revision ID: 4a83f309f411
Revises:
Create Date: 2019-06-20 23:47:24.513383
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '4a83f309f411'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | migrations/versions/4a83f309f411_.py | 2,154 | empty message
Revision ID: 4a83f309f411
Revises:
Create Date: 2019-06-20 23:47:24.513383
revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands | 284 | en | 0.617482 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: views.py
:Synopsis:
:Author:
costa
servilla
ide
:Created:
7/23/18
"""
import daiquiri
from datetime import date, datetime
import html
import json
import math
import os.path
import pandas as pd
from pathlib import Path
import pickle
import reques... | webapp/home/views.py | 91,546 | The edit page allows for direct editing of a top-level element such as
title, abstract, creators, etc. This function simply redirects to the
specified page, passing the packageid as the only parameter.
:Mod: views.py
:Synopsis:
:Author:
costa
servilla
ide
:Created:
7/23/18
!/usr/bin/env python -*- c... | 5,800 | en | 0.794373 |
#!/usr/bin/python3
import argparse
import os
import shutil
import sys
import traceback
from multiprocessing import Pool, cpu_count
from os.path import expanduser
import time
from typing import Tuple
from colorama import Fore
from atcodertools.client.atcoder import AtCoderClient, Contest, LoginError, PageNotFoundError... | atcodertools/tools/envgen.py | 12,407 | !/usr/bin/python3 for readability Return if a directory for the problem already exists Fetch problem data from the statement Store examples to the directory path If there is an existing code, just create backup Save metadata Prevent the script from stopping Deleted functionality noqa | 284 | en | 0.763652 |
import os
import torch
import torch.nn.functional as F
import torch.nn as nn
import math
from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
import torch.utils.model_zoo as model_zoo
def conv_bn(inp, oup, stride, BatchNorm):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=Fal... | modeling/backbone/mobilenet.py | 5,418 | dw pw-linear pw dw pw-linear t, c, n, s building first layer building inverted residual blocks n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) | 195 | en | 0.529931 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=43
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for... | benchmark/startCirq3134.py | 3,320 | !/usr/bin/env python -*- coding: utf-8 -*- @Time : 5/15/20 4:49 PM @File : grover.py qubit number=4 total number=43thatsNoCode Symbols for the rotation angles in the QAOA circuit. circuit begin number=9 number=2 number=3 number=4 number=5 number=18 number=28 number=6 number=7 number=8 number=20 number=21 number=2... | 553 | en | 0.270454 |
# -*- coding: utf-8 -*-
"""DBO MSSQL driver
.. module:: lib.database.dbo.drivers.mssql.driver
:platform: Unix
:synopsis: DBO MSSQL driver
.. moduleauthor:: Petr Rašek <bowman@hydratk.org>
"""
try:
import pymssql
except ImportError:
raise NotImplementedError('MSSQL client is not supported for PyPy')
fr... | src/hydratk/lib/database/dbo/drivers/mssql/driver.py | 6,099 | Class DBODriver
Method gets attribute
Args:
name (str): attribute name
Returns:
obj: attribute value
Method gets item
Args:
name (str): item name
Returns:
obj: item value
Method sets driver options
Args:
driver_option (dict): driver options
Returns:
void
Method parses dsn
Args: ... | 1,396 | en | 0.379277 |
import json
import pickle
import numpy as np
import pytest
import fsspec
from fsspec.implementations.ftp import FTPFileSystem
from fsspec.spec import AbstractFileSystem, AbstractBufferedFile
class DummyTestFS(AbstractFileSystem):
protocol = "mock"
_fs_contents = (
{"name": "top_level", "type": "dire... | fsspec/tests/test_spec.py | 7,805 | FIXME: py35 back-compat FIXME: py35 back-compat TODO: dummy buffered file is valid JSON | 87 | en | 0.481185 |
#!/usr/bin/python3
from datetime import datetime
import calendar
import sqlite3
import os
months = ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December']
calendar_db = 'PythonicTeamsCalendarTest/calendar.db'
def initi... | PythonicTeamsCalendarTest/helpers.py | 3,749 | !/usr/bin/python3 month_calendar[0].pop(0)function to retrieve all events in a given month.if not month return empty dictelse return a dict with key "date": value "Event"dictfunction to return events on a specific date | 218 | en | 0.457312 |
# 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... | st2common/tests/unit/test_pack_management.py | 1,760 | 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 sys
import cv2
import os
from ast import literal_eval
from pathlib import Path
import shutil
import logging
import random
import pickle
import yaml
import subprocess
from PIL import Image
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import animatio... | src/util.py | 31,574 | gt_bboxes_list: list of (N, 4) np.array in xywh format
pred_bboxes_list: list of (N, 5) np.array in conf+xywh format
gt_bboxes: (N, 4) np.array in xywh format
pred_bboxes: (N, 5) np.array in conf+xywh format
coco => [xmin, ymin, w, h]
yolo => [xmid, ymid, w, h] (normalized)
decode annotations in string to list of dict
... | 2,138 | en | 0.605542 |
#!/usr/bin/env python3
#
# # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved
#
#
from uimnet import utils
from uimnet import algorithms
from uimnet import workers
from omegaconf import OmegaConf
from pathlib import Path
import torch
import torch.distributed as dist
import torch.multiprocessi... | scripts/run_trainer.py | 3,843 | !/usr/bin/env python3 Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved | 96 | en | 0.824134 |
"""Configuration for SSDP tests."""
from typing import Optional, Sequence
from unittest.mock import AsyncMock, MagicMock, patch
from urllib.parse import urlparse
from async_upnp_client.client import UpnpDevice
from async_upnp_client.event_handler import UpnpEventHandler
from async_upnp_client.profiles.igd import Statu... | tests/components/upnp/conftest.py | 8,633 | Mock async_upnp_client IgdDevice.
Mock async_upnp_client UpnpDevice.
Initialize.
Initialize mock device.
Get the device type.
Get the device type of this device.
Get manufacturer.
Get the manufacturer of this device.
Mock async_setup_entry.
Mock homeassistant.components.upnp.Device.
Get the model name.
Get the model na... | 581 | en | 0.76489 |
# Copyright The PyTorch Lightning 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
#
# Unless required by applicable law or agreed to i... | flash/text/seq2seq/summarization/data.py | 1,424 | Copyright The PyTorch Lightning 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 Unless required by applicable law or agreed to in writing, softwar... | 615 | en | 0.850169 |
"""Testing utilities.
"""
import os.path
import pytest
def test():
"""Initiate poliastro testing
"""
pytest.main([os.path.dirname(os.path.abspath(__file__))])
| src/poliastro/testing.py | 176 | Initiate poliastro testing
Testing utilities. | 51 | en | 0.622834 |
# -*- coding: utf-8 -*-
"""Plot to demonstrate the qualitative1 colormap.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import (figsize, cmap2rgba)
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=figsize(10))
ax.set_prop_cycle(color=cmap2rgba('qualitative1', 7))
for c in np.a... | doc/pyplots/plot_qualitative1.py | 436 | Plot to demonstrate the qualitative1 colormap.
-*- coding: utf-8 -*- | 70 | en | 0.760589 |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
from common import network_metrics
from telemetry.page import page_test
from telemetry.value import scalar
CHROME_PROXY_VIA_HEA... | third_party/webrtc/src/chromium/src/tools/chrome_proxy/common/chrome_proxy_metrics.py | 3,854 | Represents an HTTP response from a timeline event.
Get the client type directive from the Chrome-Proxy request header.
Returns:
The client type directive from the Chrome-Proxy request header for the
request that lead to this response. For example, if the request header
"Chrome-Proxy: c=android" is present,... | 1,029 | en | 0.785076 |
import importlib
import logging
import os
import sys
from pathlib import Path
logger = logging.getLogger('second.utils.loader')
CUSTOM_LOADED_MODULES = {}
def _get_possible_module_path(paths):
ret = []
for p in paths:
p = Path(p)
for path in p.glob("*"):
if path.suffix in ["py", ... | second/utils/loader.py | 2,605 | this will enable find objects defined in a file. avoid replace system modules. | 78 | en | 0.477358 |
"""
This module defines the policies that will be used in order to sample the information flow
patterns to compare with.
The general approach is a function that takes in any eventual parameters and outputs a list of
pairs of DB_Ids for which the flow will be calculated.
"""
import random
import hashlib
import json
imp... | bioflow/algorithms_bank/sampling_policies.py | 9,578 | None-robust helper function to characterize a sample set by its length, nature of items in
teh sample and eventual distribution of weights within the sample.
:param sample: sample to characterize
:return: set length (0 if None), 1 if items are ids, 2 if ids and weights (0 if
None), rounded distribution ([] if None or ... | 3,297 | en | 0.877645 |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... | Advanced-Data-Engineering-with-Databricks/Solutions/04 - Databricks in Production/ADE 4.02 - Error Prone.py | 2,715 | Databricks notebook source MAGIC %md-sandbox MAGIC MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;"> MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px"> MAGIC </div> COMMAND ---------- MAGIC %md MAGIC P... | 2,221 | en | 0.638572 |
# 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/network/v20190901/private_endpoint.py | 19,487 | The set of arguments for constructing a PrivateEndpoint resource.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[str] id: Resource ID.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[Sequence[pulumi.Input['PrivateLinkServiceConnectionArgs']]] ... | 3,825 | en | 0.704867 |
"""
Time complexity: O(n^2)
This sorting algorithm puts the smallest element in the first
place after the first iteration. Similarly, after the second
iteration, the second smallest value becomes the second value
of the list. The process continues and eventually the list
becomes sorted.
"""
for i in range(n):
for ... | sorting-algorithms/selection_sort.py | 402 | Time complexity: O(n^2)
This sorting algorithm puts the smallest element in the first
place after the first iteration. Similarly, after the second
iteration, the second smallest value becomes the second value
of the list. The process continues and eventually the list
becomes sorted. | 284 | en | 0.910559 |
# -*- coding: utf-8 -*-
from django.conf import settings
VAPID_PUBLIC_KEY = getattr(settings, 'DJANGO_INFOPUSH_VAPID_PUBLIC_KEY', '')
VAPID_PRIVATE_KEY = getattr(settings, 'DJANGO_INFOPUSH_VAPID_PRIVATE_KEY', '')
VAPID_ADMIN_EMAIL = getattr(settings, 'DJANGO_INFOPUSH_VAPID_ADMIN_EMAIL', '')
FCM_SERVER_KEY = getattr(s... | push/settings.py | 2,607 | -*- coding: utf-8 -*- how many processes to use in a pushsend management command for parallel push 1 disables multiprocessing default push icon kb, max filesize of push icon big push image for push in Chrome best aspect ration is 3:2 for desktop Chrome mobile Chrome will crop it vertically a little https://web-push-boo... | 962 | en | 0.743293 |
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class Concat(function.Function):
"""Concatenate multiple tensors towards specified axis."""
# concat along the channel dimension by default
def __init__(self, axis=1):
self.axis = axis
d... | chainer/functions/concat.py | 1,589 | Concatenate multiple tensors towards specified axis.
Concatenates given variables along an axis.
Args:
xs (tuple of Variables): Variables to be concatenated.
axis (int): Axis that the input arrays are concatenated along.
Returns:
~chainer.Variable: Output variable.
concat along the channel dimension by ... | 327 | en | 0.743019 |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... | covid_epidemiology/src/models/encoders/variable_encoder_builder.py | 4,752 | Returns a `FeatureEncoder` built as specified in the `encoder_spec`.
Constructs a variable encoder based on an encoder spec.
coding=utf-8 Copyright 2021 The Google Research 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... | 722 | en | 0.843892 |
#! /usr/bin/env python
# -*- coding: utf8 -*-
'''
Copyright 2018 University of Liège
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... | tests/SU2_RBM/PitchPlungeAirfoil_BGS_parallel_fsi.py | 2,508 | ! /usr/bin/env python -*- coding: utf8 -*- Read results from file Check convergence and results rel. tol. of 10% rel. tol. of 10% Solvers and config files FSI objects FSI parameters get parameters create fsi driver run fsi process check the results eof --- This is only accessed if running from command prompt --- | 313 | en | 0.705293 |
import functools
import jinja2
import json
import threading
from hashlib import sha256
from ..caserunconfiguration import CaseRunConfiguration, ConfigurationsList, CaseRunConfigurationsList
#from ..exceptions import UnknownEventSubTypeExpression
from .functions import dotted_startswith
from .structures.factory import ... | libpermian/events/base.py | 5,583 | Base class of event which stores its type, event structures (automatically
provides converted event structures) and decides which testplans and
caserunconfigurations will be executed based on the event.
This base class can be directly used just by providing settings, event type
and optionally definitions of event_stru... | 2,077 | en | 0.85771 |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from .... | pypureclient/flasharray/FA_2_1/models/retention_policy.py | 3,707 | Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
Keyword args:
all_for_sec (int): The length... | 1,000 | en | 0.783965 |
# 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 ... | src/datamigration/azext_datamigration/vendored_sdks/datamigration/aio/operations/_tasks_operations.py | 28,243 | TasksOperations async 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: ~azure.mgmt.datamigration.models
:param client: ... | 3,008 | en | 0.55762 |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 29 16:02:11 2019
@author: Christian Zwinkels-Valero
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
# Activation functions
def sigmoid(z):
return 1 / (1 + np.exp(z))
def d_sigmoid(z):
return sigmoid(z)*(1 - sigmoid(z))
def relu(... | Supervised_Learning/Neural_Network/NN.py | 2,817 | Created on Sun Dec 29 16:02:11 2019
@author: Christian Zwinkels-Valero
-*- coding: utf-8 -*- Activation functions Data processing Initialization Foward propagation First activation layer is the inputs Hidden layer computation Ouput layer computation Calculating the costs Loss computation Final layer derivatives Delt... | 352 | en | 0.545429 |
"""Get example scripts, notebooks, and data files."""
import argparse
from datetime import datetime, timedelta
from glob import glob
import json
import os
import pkg_resources
from progressbar import ProgressBar
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall b... | parcels/scripts/get_examples.py | 5,035 | Create directory (and parents) if they don't exist.
Only return the files that are not yet present on disk.
Copy example data from Parcels directory.
Return thos parths of the list `file_names` that were not found in the
package.
Mirror file_names from source_url to target_path.
Get example scripts, example notebooks,... | 816 | en | 0.827698 |
# -*- coding: utf-8 -*-
# Copyright 2013 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 require... | gslib/commands/notification.py | 32,907 | Implementation of gsutil notification command.
Command entry point for the notification command.
Assures that a topic exists, creating it if necessary.
Also adds GCS as a publisher on that bucket, if necessary.
Args:
pubsub_topic: name of the Cloud Pub/Sub topic to use/create.
service_account: the GCS service acc... | 3,272 | en | 0.858069 |
import tensorflow as tf
from google.protobuf import json_format, text_format
from tensorflow.contrib import graph_editor as ge
def save():
with tf.Graph().as_default() as g:
x = tf.placeholder(tf.float32, name="input")
a = tf.Variable(5.0)
res: tf.Tensor = tf.multiply(a, x, name="mul")
... | mincall/_experiments/load_save_modify.py | 2,418 | save() print(y_out) for op in tf.get_default_graph().get_operations(): print(op.name) | 89 | en | 0.151019 |
from __future__ import print_function
import sys
from operator import add
from pyspark import SparkContext
from pyspark import SparkConf,SparkContext
from pyspark.streaming import StreamingContext
import sys
import requests
from operator import add
from pyspark.sql.types import *
from pyspark.sql import functions as... | Spark-Example-TPCH/TPCH-Example_Solution_Dataframe.py | 10,633 | if __name__ == "__main__": create spark configuration conf = SparkConf(appName="TPCH-Example") create spark context with the above configuration sc = SparkContext(conf=conf) lineitems = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep ="|").load(sys.arg[1]) path is where you have the... | 5,204 | en | 0.631243 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the ... | packages/fetchai/skills/gym/__init__.py | 955 | This module contains an example of skill for an AEA.
-*- coding: utf-8 -*- ------------------------------------------------------------------------------ Copyright 2018-2019 Fetch.AI Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the L... | 813 | en | 0.729122 |
from vyxal.parse import parse
from vyxal.transpile import transpile
def test_if():
# TODO(user/cgccuser) try with more branches
vy = """[ 1 | 2 ]"""
py = transpile(vy)
expected = """condition = pop(stack, 1, ctx=ctx)
if boolify(condition, ctx):
stack.append(1)
else:
stack.append(2)
"""
ass... | tests/test_transpiler.py | 339 | TODO(user/cgccuser) try with more branches | 42 | en | 0.854445 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | keystone/tests/unit/credential/test_backend_sql.py | 4,550 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is di... | 774 | en | 0.869768 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Twinboundary plot
This module provide various kinds of plot related to twin boudnary.
"""
import numpy as np
from copy import deepcopy
from twinpy.plot.base import line_chart
def plot_plane(ax,
distances:list,
z_coords:list,
... | twinpy/plot/twinboundary.py | 4,934 | Plot angle.
Args:
ax: matplotlib ax.
z_coords (list): List of z coordinate of each plane.
label (str): Plot label.
decorate (bool): If True, ax is decorated.
Plot angle.
Args:
ax: matplotlib ax.
pair_distances (list): List of A-B pair distances, which is originally
p... | 938 | en | 0.679806 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tools
import db
import time
import re
import json
from plugins import base
# from plugins import lista
from plugins import listb
from plugins import dotpy
class Iptv (object):
def __init__ (self) :
self.T = tools.Tools()
self.DB = db.DataBase()... | main.py | 2,991 | !/usr/bin/env python -*- coding: utf-8 -*- from plugins import lista listA = lista.Source() urlList = listA.getSource() for item in urlList : self.addData(item) | 168 | en | 0.215678 |
"""
##################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : test.py
# Abstract : The common testing api for video text recognition, track, quality ... | davarocr/davarocr/davar_videotext/apis/test.py | 1,827 | Test model with single GPU, used for visualization.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
Returns:
dict: test results
##################################################################################################
# Copyright Info : Copyright ... | 671 | de | 0.297824 |
# -*- coding: utf-8 -*-
"""
pyQode is a source code editor widget for PyQt5
pyQode is a **namespace package**.
"""
import pkg_resources
pkg_resources.declare_namespace(__name__)
| pyqode/__init__.py | 179 | pyQode is a source code editor widget for PyQt5
pyQode is a **namespace package**.
-*- coding: utf-8 -*- | 107 | en | 0.707883 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*- #
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
# If your site is available via HTTPS, make sure SITEURL begins with https://
SITEURL = ''
RELA... | publishconf.py | 541 | !/usr/bin/env python3 -*- coding: utf-8 -*- This file is only used if you use `make publish` or explicitly specify it as your config file. If your site is available via HTTPS, make sure SITEURL begins with https://CATEGORY_FEED_ATOM = 'feeds/{slug}.atom.xml' Following items are often useful when publishingDISQUS_SITEN... | 349 | en | 0.794865 |
from pyspedas import tnames
from pytplot import get_data, store_data, options
def mms_load_fpi_calc_pad(probe='1', level='sitl', datatype='', data_rate='', suffix='', autoscale=True):
"""
Calculates the omni-directional pitch angle distribution (summed and averaged)
from the individual tplot variables
... | pyspedas/mms/fpi/mms_load_fpi_calc_pad.py | 4,346 | Calculates the omni-directional pitch angle distribution (summed and averaged)
from the individual tplot variables
Parameters:
probe: str
probe, valid values for MMS probes are ['1','2','3','4'].
level: str
indicates level of data processing. the default if no level is specified is 'sitl'
... | 954 | en | 0.547641 |
# -*- coding: utf-8 -*-
# Copyright 2021 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 agr... | docs/conf.py | 12,391 | -*- coding: utf-8 -*- Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, s... | 8,964 | en | 0.683118 |
#!/usr/bin/env python
# Copyright (c) 2019 The Zcash developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://www.opensource.org/licenses/mit-license.php.
import sys; assert sys.version_info < (3,), ur"This script does not run under Python 3. Please use Python 2.7.x."
fr... | qa/rpc-tests/wallet_persistence.py | 5,547 | !/usr/bin/env python Copyright (c) 2019 The Zcash developers Distributed under the MIT software license, see the accompanying file COPYING or https://www.opensource.org/licenses/mit-license.php. Overwinter Sapling Sanity-check the test harness Verify Sapling address is persisted in wallet (even when Sapling is not yet ... | 1,104 | en | 0.803138 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as f
from torch.autograd import Variable
import os
import numpy as np
from tqdm import tqdm
def reparameterize(mu, logvar):
eps = Variable(torch.randn(mu.size(0), mu.size(1))).cuda()
z = mu + eps * torch.exp(... | VAE_MLP/VAE_MLP_cat_model.py | 8,489 | 1, 124, 32 32, 62, 16 64, 15, 15 128, 20, 5 batch_s, 8, 7, 7 batch_s, latent batch_s, latent batch_s, latent batch_s, 8, 7, 7 batch_s, latent batch_s, latent batch_s, latent batch_s, 8, 7, 7 batch_s, 8, 7, 7 batch_s, latent | 223 | en | 0.773715 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Corrfunc is a set of high-performance routines for
computing clustering statistics on a distribution of
points.
"""
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import os
__version__ = "0.0.5"
__author__ ... | Corrfunc/__init__.py | 3,074 | Reads a file under python3 with encoding (default UTF-8).
Also works under python2, without encoding.
Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp)
principle.
Mimics the Unix utility which.
For python3.3+, shutil.which provides all of the required functionality.
An implementation is provided in case... | 1,211 | en | 0.82737 |
"""The token kinds currently recognized."""
from shivyc.tokens import TokenKind
keyword_kinds = []
symbol_kinds = []
bool_kw = TokenKind("_Bool", keyword_kinds)
char_kw = TokenKind("char", keyword_kinds)
short_kw = TokenKind("short", keyword_kinds)
int_kw = TokenKind("int", keyword_kinds)
long_kw = TokenKind("long",... | shivyc/token_kinds.py | 2,819 | The token kinds currently recognized. | 37 | en | 0.965192 |
# -*- coding:utf-8 -*-
from os import system
from re import search, findall
from time import sleep
from requests import Session, get, post
from PIL import Image
from cfscrape import get_cookie_string
# from traceback import format_exc
# 功能:请求各大jav网站和arzon的网页
# 参数:网址url,请求头部header/cookies,代理proxy
# 返回:网页html... | functions_requests.py | 16,888 | -*- coding:utf-8 -*- from traceback import format_exc 功能:请求各大jav网站和arzon的网页 参数:网址url,请求头部header/cookies,代理proxy 返回:网页html,请求头部 arzon 获取一个arzon_cookie,返回cookie 当初费尽心机,想办法如何通过页面上的成人验证,结果在一个C开发的jav爬虫项目,看到它请求以下网址,再跳转到arzon主页,所得到的的cookie即是合法的cookie print(format_exc()) 搜索arzon,或请求arzon上jav所在网页,返回html print('代理:', proxy) 得到a... | 1,595 | zh | 0.872267 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test multiple RPC users."""
from test_framework.test_framework import BitcoinTestFramework
from test_f... | qa/rpc-tests/multi_rpc.py | 4,550 | Test multiple RPC users.
!/usr/bin/env python3 Copyright (c) 2015-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.Append rpcauth to polis.conf before initialization Check correctness of the rpcauth conf... | 556 | en | 0.608306 |
from __future__ import unicode_literals
import unittest
from django.conf.urls import url
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.test import override_settings
from django.utils.decorators import method_decorator
... | tests/test_requests_client.py | 8,825 | Confirm session is not authenticated Perform a login Confirm session is authenticated | 85 | en | 0.870872 |
from tkinter import *
from tkinter import messagebox
import tkinter.ttk as ttk
import datetime
def init(top, gui):
global w, top_level, root
w = gui
top_level = top
root = top
def start_gui():
global w, root
root = Tk()
root.iconbitmap("index.ico")
top = main_level(roo... | Bus Ticketing system MAIN final.py | 19,492 | self.select()pass for sql table-------------------------------------Total Ticket Cost-----------------------------------------------------------------------------------------Defining all the specifications for the TKinter Frontend ---------------------------------------------------------------------SQL PART ----------... | 413 | en | 0.225111 |
import jinja2
class SPMObject(object):
""" Abstract Base Class for all SPM objects.
Even though SPM objects are not Spire tasks (as some of them will modify
in-place their file_dep, which is not compatible with doit's task
semantics), they nonetheless include task-related properti... | spire/spm/spm_object.py | 1,480 | Abstract Base Class for all SPM objects.
Even though SPM objects are not Spire tasks (as some of them will modify
in-place their file_dep, which is not compatible with doit's task
semantics), they nonetheless include task-related properties: file_dep
and targets. Subclasses will have to override the _get_file_dep and... | 373 | en | 0.921671 |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
while head:
if... | src/main/python/leetcode-python/easy/203.Remove Linked List Elements.py | 702 | :type head: ListNode
:type val: int
:rtype: ListNode
Definition for singly-linked list. | 89 | en | 0.325991 |
# author : Sam Rapier
from deploy_django_to_azure.settings.base import *
DEBUG = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = 'https://exeblobstorage.blob.core.windows.net/static-files/'
# Database
# https://docs.djangoproject.com/en/1.11/... | deploy_django_to_azure/settings/production.py | 744 | author : Sam Rapier Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/1.11/howto/static-files/ Database https://docs.djangoproject.com/en/1.11/ref/settings/databases | 188 | en | 0.417629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.