repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
JoeGermuska/worblehat
reference/pyarchive/pyarchive/mp3.py
Python
mit
7,381
0.022897
# PyMM - Python MP3 Manager # Copyright (C) 2000 Pierre Hjalm <pierre.hjalm@dis.uu.se> # # Modified by Alexander Kanavin <ak@sensi.org> # Removed ID tags support and added VBR support # Used http://home.swipnet.se/grd/mp3info/ for information # # This program is free software; you can redistribute it and/or # modify it...
17) & 3) == 3 and ((head >> 16) & 1) == 1): return 0 if ((head & 0xffff0000L) == 0xfffe0000L): return 0 return 1 def filesize(file): """ Returns the size of file sans any ID3 tag """ f=open(file) f.seek(0,2) size=f.tell() try: f.seek(-128,2) except:...
e<0: return 0 else: return size table=[[ [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448], [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384], [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]], [ [0, 32, 48,...
ellisonleao/pyshorteners
pyshorteners/shorteners/tinyurl.py
Python
gpl-3.0
1,019
0
from ..base import BaseShortener from ..exceptions import ShorteningErrorException class Shortener(BaseShortener): """ TinyURL.com shortener implementation Example: >>> import pyshorteners >>> s = pyshorteners.Shortener() >>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/TEST' >>> s.tinyurl.expand('http://tinyurl.com/test') 'http://www.google.com' """ api_url = "http://tinyurl.com/api-create.php" def short(self, url): """Short implementation for TinyURL.com Args: url: the URL you want to shorten Re...
shortened URL Raises: ShorteningErrorException: If the API returns an error as response """ url = self.clean_url(url) response = self._get(self.api_url, params=dict(url=url)) if response.ok: return response.text.strip() raise ShorteningErrorExcep...
dsanders11/django-autocomplete-light
autocomplete_light/example_apps/basic/forms.py
Python
mit
1,043
0.000959
import a
utocomplete_light.shortcuts as autocomplete_light from django import VERSION from .models import * try: import genericm2m except ImportError: genericm2m = None try: import taggit except Import
Error: taggit = None class DjangoCompatMeta: if VERSION >= (1, 6): fields = '__all__' class FkModelForm(autocomplete_light.ModelForm): class Meta(DjangoCompatMeta): model = FkModel class OtoModelForm(autocomplete_light.ModelForm): class Meta(DjangoCompatMeta): model = Oto...
HellTech/NAG_IoE_2016
30_HellTech_1602_1/08_Meteostanice_GUI_v2/Meteo2/base64function.py
Python
gpl-3.0
119
0.05042
import ba
se64 def toBase64(s): return base64.b64encode(str(s)) de
f fromBase64(s): return base64.b64decode(str(s))
vasconcelosfer/odoo-odisea
odisea/models/representative.py
Python
lgpl-3.0
4,870
0.015606
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
ized image", store= False, help="Small-sized image of this contact. It is automatically "\ "resized as a 64x64px image, with aspect ratio preserved. "\ "Use this field anywhere a small image is required.")
has_image = fields.Boolean(compute=_has_image) color = fields.Integer('Color Index') @api.multi def onchange_state(self, state_id): if state_id: state = self.env['res.country.state'].browse(state_id) return {'value': {'country_id': state.country_id.id}} return {} @api.multi def onch...
madhavsuresh/chimerascan
chimerascan/deprecated/chimerascan_index_v1.py
Python
gpl-3.0
5,779
0.003634
#!/usr/bin/env python ''' Created on Jan 5, 2011 @author: mkiyer chimerascan: chimeric transcript discovery using RNA-seq Copyright (C) 2011 Matthew Iyer This program is free software: you can redistribute it and
/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program...
stefanw/froide
froide/georegion/migrations/0002_auto_20180409_1007.py
Python
mit
617
0.001621
# -*- coding: utf-8 -*- # Gene
rated by Django 1.11.9 on 2018-04-09 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('georegion', '0001_initial_squashed_0004_auto_20180307_2026'), ] operations = [ ...
null=True, on_delete=django.db.models.deletion.SET_NULL, to='georegion.GeoRegion', verbose_name='Part of'), ), ]
blorenz/btce-api
btceapi/common.py
Python
mit
5,264
0.00057
# Copyright (c) 2013 Alan McIntyre import httplib import json import decimal import re decimal.getcontext().rounding = decimal.ROUND_DOWN exps = [decimal.Decimal("1e-%d" % i) for i in range(16)] btce_domain = "btc-e.com" all_currencies = ("btc", "usd", "rur", "ltc", "nmc", "eur", "nvc", "trc", "pp...
l_pairs: if "_" in pair: a, b = pair.split("_") swapped_pair = "%s_%s" % (b, a) if swapped_pair in all_pairs: msg = "Unrecognized pair: %r (did you mean %s?)" msg = msg % (pair, swapped_pair) raise Exception(msg) raise E...
on("Unrecognized trade type: %r" % trade_type) minimum_amount = min_orders[pair] formatted_min_amount = formatCurrency(minimum_amount, pair) if amount < minimum_amount: msg = "Trade amount too small; should be >= %s" % formatted_min_amount raise Exception(msg) def truncateAmountDigits(val...
meatcomputer/opencog
opencog/python/examples/test.py
Python
agpl-3.0
121
0.041322
class a(object): pass cla
ss b(a): pass print a.__subclasses__() class c(a): pass print a.__subcl
asses__()
jeromecc/doctoctocbot
src/conversation/migrations/0033_twitterusertimeline_last_api_call.py
Python
mpl-2.0
423
0
# Generated by Django 2.2.17 on 2021-01-31 06:11 from django.db import mi
grations, models class Migration(migrations.Migration): dependencies = [ ('conversation', '0032_
twitterusertimeline'), ] operations = [ migrations.AddField( model_name='twitterusertimeline', name='last_api_call', field=models.DateTimeField(blank=True, null=True), ), ]
dawncold/expenditure-application
expenditure_application/__init__.py
Python
apache-2.0
90
0
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print
_function, division
schansge/pyfdtd-gui
src/dialogs/__init__.py
Python
gpl-3.0
797
0
# GUI for pyfdtd using PySide # Copyright (C) 2012 Patrik Gebhardt # Contact: grosser.knuff@googlemail.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou
ndation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more de...
* from newSimulation import *
neilhan/tensorflow
tensorflow/python/kernel_tests/rnn_test.py
Python
apache-2.0
95,137
0.00987
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
nn_cell.RNNCell): """RNN Cell generating (output, new_state) = (input + 1, state + 1).""" @property def output_size(self): return 5 @property def state_size(self): return 5 def __call__(self, input_, state, scope=None): return (input_ + 1, state + 1) class DummyMultiDimensionalLSTM(tf.nn.rn...
"""LSTM Cell generating (output, new_state) = (input + 1, state + 1). The input to this cell may have an arbitrary number of dimensions that follow the preceding 'Time' and 'Batch' dimensions. """ def __init__(self, dims): """Initialize the Multi-dimensional LSTM cell. Args: dims: tuple that ...
stonebig/numba
numba/roc/hsadrv/driver.py
Python
bsd-2-clause
51,876
0.001292
""" HSA driver bridge implementation """ from collections.abc import Sequence import sys import atexit import os import ctypes import struct import traceback import weakref import logging from contextlib import contextmanager from collections import defaultdict, deque from functools import total_ordering from numba ...
agent.release() except AttributeError: # this is because no agents initialised # so self.agents i
sn't present pass else: self._recycler.drain() def _initialize_agents(self): if self._agent_map is not None: return self._initialize_api() agent_ids = [] def on_agent(agent_id, ctxt): agent_ids.append...
markashleybell/ExpandTabsOnLoad
ExpandTabsOnLoad.py
Python
mit
630
0
import os import re import sublime import sublime_plugin class ExpandTabsOnLoad(sublime_plugin.EventListener): # Run ST's 'expand_tabs' command when opening a file, # only if there are any tab characters in the file
def on_load(self, view): expand_tabs = view.settings().get("expand_tabs_on_load", False) if expand_tabs and view.find("\t", 0): view.run_command("expand_tabs", {"set_translate_tabs": True}) tab_size = view.se
ttings().get("tab_size", 0) message = "Converted tab characters to {0} spaces".format(tab_size) sublime.status_message(message)
ARMmbed/yotta_osx_installer
workspace/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py
Python
apache-2.0
798
0
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repos
itory # for complete details. from __future__ import absolute_import, division, print_function import hmac from cryptography.hazmat.bindings._constant_time import lib if hasattr(hmac, "compare_digest"): def bytes_eq(a, b): if not isinstance(a, bytes) or not isinstance(b,
bytes): raise TypeError("a and b must be bytes.") return hmac.compare_digest(a, b) else: def bytes_eq(a, b): if not isinstance(a, bytes) or not isinstance(b, bytes): raise TypeError("a and b must be bytes.") return lib.Cryptography_constant_time_bytes_eq( ...
bnaul/scikit-learn
sklearn/utils/tests/test_extmath.py
Python
bsd-3-clause
26,768
0
# Authors: Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Denis Engemann <denis-alexander.engemann@inria.fr> # # License: BSD 3 clause import numpy as np from scipy import sparse from scipy import linalg from scipy import stats from scipy.special import expit im...
using the slow exact method _, s, _ = linalg.svd(X, full_matrices=False) for normalizer in ['auto', 'none', 'LU', 'QR']: # compute the singular values of X using the fast approximate # method without the iterated power method _, sa,
_ = randomized_svd(X, k, n_iter=0, power_iteration_normalizer=normalizer, random_state=0) # the approximation does not tolerate the noise: assert np.abs(s[:k] - sa).max() > 0.01 # compute the singular values of X using the fas...
cmtcoin/wallet
contrib/pyminer/pyminer.py
Python
mit
6,434
0.034815
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
erate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() i
f __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue ...
anandology/pyjamas
pyjs/src/pyjs/translator_dict.py
Python
apache-2.0
117,085
0.001196
#!/usr/bin/env python import sys import os import re from lib2to3.pgen2.driver import Driver from lib2to3 import pygram, pytree from lib2to3.pytree import Node, Leaf, type_repr from lib2to3.pygram import python_symbols def sym_type(name): return getattr(python_symbols, name) def new_node(name): return Node(...
E'), ('<', r'\x3C'), ('&', r'\x26'), (';', r'\x3B') ) + tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]) def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" for bad, good in JS_ESCAPES: value = value.replace(bad, good) return value re_js_string_esc...
compile("[%s]" % re_js_string_escape) re_int = re.compile('^[-+]?[0-9]+$') re_long = re.compile('^[-+]?[0-9]+[lL]$') re_hex_int = re.compile('^[-+]?0x[0-9a-fA-F]+$') re_hex_long = re.compile('^[-+]?0x[0-9a-fA-F]+[lL]$') re_oct_int = re.compile('^[-+]?0[0-8]+$') re_oct_long = re.compile('^[-+]?0[0-8]+[lL]$') builtin_n...
marcel-goldschen-ohm/ModelViewPyQt
FileDialogDelegateQt.py
Python
mit
2,023
0.001483
""" FileDialogDelegateQt.py: Delegate that pops up a file dialog when double clicked. Sets the model data to the selected file name. """ import os.path try: from PyQt5.QtCore import Qt, QT_VERSION_STR from PyQt5.QtWidgets import QStyledItemDelegate, QFileDialog except ImportError: try: from PyQt4...
nit__(self, parent=None): QStyledItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): """ Instead of creating an editor, just popup a modal file dialog and set the model data to the selected file name, if any. """ pathToFileName = "" if ...
"Open") elif QT_VERSION_STR[0] == '5': pathToFileName, temp = QFileDialog.getOpenFileName(None, "Open") pathToFileName = str(pathToFileName) # QString ==> str if len(pathToFileName): index.model().setData(index, pathToFileName, Qt.EditRole) index.model().data...
pmlrsg/PySpectra
PySpectra/dart.py
Python
mit
2,368
0.000845
#! /usr/bin/env python # -*- coding: utf-8 -*- # This file has been created by ARSF Data Analysis Node and # is licensed under the MI
T Licence. A copy of this # licence is available to download with this file. # # Author: Robin Wilson # Created: 2015-11-16 import sys import numpy as np
import pandas as pd # Python 2/3 imports try: from StringIO import StringIO except ImportError: if sys.version_info[0] >= 3: from io import StringIO else: raise from . import spectra_reader class DARTFormat(spectra_reader.SpectraReader): """ Class to read spectra from DART format...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/aio/operations/_nat_gateways_operations.py
Python
mit
26,918
0.004681
# 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 ...
rom a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod ...
r that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: C...
TheBraveWarrior/pyload
module/plugins/crypter/Movie2KTo.py
Python
gpl-3.0
472
0
# -*- coding: utf-8 -*- from ..internal.DeadC
rypter import DeadCrypter class Movie2KTo(DeadCrypter): __name__ = "Movie2KTo" __type__ = "crypter" __version__ = "0.56" __status__ = "stable" __pattern__ = r'http://(?:www\.)?movie2k\.to/(.+)\.html' __config__ = [("activated", "bool", "Activated", True)] __description__ = """Movie2k.to ...
hors__ = [("4Christopher", "4Christopher@gmx.de")]
jonparrott/google-cloud-python
error_reporting/google/cloud/errorreporting_v1beta1/gapic/report_errors_service_client_config.py
Python
apache-2.0
987
0
config = { "interfaces": { "google.devtools.clouderrorreporting.v1beta1.ReportErrorsService": { "retry_codes": { "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], "non_idempotent": [] }, "retry_params": { "default": { ...
_millis": 20000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 20000, "total_timeout_millis": 600000
} }, "methods": { "ReportErrorEvent": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" } } } } }
Fitzgibbons/Cryptograpy
rabinmiller.py
Python
mit
526
0.001901
import random rand = random.SystemRandom() def rabinMiller(num): if num % 2 == 0: return False s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for trials in range(64): a = rand.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0...
= t - 1: return False else: i = i + 1 v = (v ** 2) % num return True
johnnoone/salt-targeting
src/salt/targeting/__init__.py
Python
mit
816
0.006127
''' salt.targeting ~~~~~~~~~~~~~~ ''' import logging log = logging.getLogger(__name__) from .parser import * from .query import * from .rules import * from .subjects import * #: defines minion targeting minion_targeting = Query(default_rule=GlobRule
) minion_targeting.register(GlobRule, None, 'glob') minion_targeting.register(GrainRule, 'G', 'grain') minion_targeting.register(PillarRule, 'I', 'pillar') minion_targeting.register(PCR
ERule, 'E', 'pcre') minion_targeting.register(GrainPCRERule, 'P', 'grain_pcre') minion_targeting.register(SubnetIPRule, 'S') minion_targeting.register(ExselRule, 'X', 'exsel') minion_targeting.register(LocalStoreRule, 'D') minion_targeting.register(YahooRangeRule, 'R') minion_targeting.register(ListEvaluator, 'L', 'lis...
citrix-openstack-build/oslo.messaging
oslo/messaging/notify/_impl_noop.py
Python
apache-2.0
811
0
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # Copyright 2013 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/licens...
NSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permission
s and limitations # under the License. from oslo.messaging.notify import notifier class NoOpDriver(notifier._Driver): def notify(self, ctxt, message, priority): pass
uingei/mm
merklemaker.py
Python
agpl-3.0
19,767
0.034704
# Eloipool - Python Bitcoin pool server # Copyright (C) 2011-2012 Luke Dashjr <luke-jr+eloipool@utopios.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # L...
k, height, bits) if lastHeight != height: # TODO: Perhaps reuse clear merkle trees more intelligently if lastHeight == height - 1: self.curClearMerkleTree = self.nextMerkleTree self.clearMerkleRoots = self.nextMerkleRoots self.logger.debug('Adopting next-height clear merkleroots :)') else: ...
; no longpoll merkleroots available!' % (lastHeight, height)) self.curClearMerkleTree = self.createClearMerkleTree(height) self.clearMerkleRoots = Queue(self.WorkQueueSizeClear[1]) self.nextMerkleTree = self.createClearMerkleTree(height + 1) self.nextMerkleRoots = Queue(self._MaxClearSize) else: self...
IntelligentVisibility/ztpserver
ztpserver/__init__.py
Python
bsd-3-clause
1,638
0.000611
# # Copyright (c) 2014, Arista Networks, 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 condit...
FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, D
ATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # vim: tabstop=4 expandtab shiftwidt...
Lightning3105/Legend-Of-Aiopa-RPG
Updater.py
Python
gpl-2.0
9,598
0.007293
import urllib.request import pickle import sys try: import Variables as v except: class var(): def __init__(self): self.screen = None v = var() import pygame as py class textLabel(py.sprite.Sprite): def __init__(self, text, pos, colour, font, size, variable = False, cen...
(255, 255, 255), theFont, "S", centred=True))
labels = py.sprite.Group() labels.add(textLabel("An Update Is Available:", (320, 150), (255, 255, 255), theFont, 50, False, True)) labels.add(textLabel(str(str(current) + " ==> " + str(latest)), (320, 180), (255, 255, 255), theFont, 20, False, True)) while True: py.ev...
icucinema/madcow
madcow/modules/election.py
Python
gpl-3.0
1,577
0.001902
"""Predicted Electoral Vote Count""" import re from madcow.util.http import getsoup from madcow.util.color import ColorLib from madcow.util import Module, strip_html class Main(Module): pattern = re.compile(r'^\s*(election|ev)\s*$', re.I) help = u'ev - current election 2008 vote prediction' baseurl = u'h...
eplace(u'\xa0', u'').strip() if key == 'name': if val == u'Obama': color = '
blue' elif val == 'Romney': color = 'red' else: color = None if color: val = self.colorlib.get_color(color, text=val) if val: score.append(val) ...
simonwydooghe/ansible
lib/ansible/modules/network/fortios/fortios_firewall_ssl_server.py
Python
gpl-3.0
15,241
0.001706
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
he top-level 'state' parameter. - HORIZONTALLINE - Indicates whether to create or remove the object. type: str required: false choices: - present - absent add_header_x_
forwarded_proto: description: - Enable/disable adding an X-Forwarded-Proto header to forwarded requests. type: str choices: - enable - disable ip: description: - IP...
akhilaananthram/nupic.fluent
fluent/encoders/language_encoder.py
Python
agpl-3.0
7,974
0.005769
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditions apply: # # This pro...
sults): """ Return a pretty print string representing the return value from decode(). """ (fieldsDict, fieldsOrder) = decodeResults desc = '' for fieldName in fieldsOrder: (ranges, rangesStr) = fieldsDict[fieldName] if len(desc) > 0: desc += ", %s:" % (fieldName) else...
sc += "%s:" % (fieldName) desc += "[%s]" % (rangesStr) return desc
rahulunair/nova
nova/virt/libvirt/volume/quobyte.py
Python
apache-2.0
7,552
0
# Copyright (c) 2015 Quobyte Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
e, cfg_file=configfile) nova.privsep.libvirt.unprivileged_qb_mount(volume, mnt_base, cfg_file=configfile) LOG.info('Mounted volume: %s', vol
ume) def umount_volume(mnt_base): """Wraps execute calls for unmouting a Quobyte volume""" try: if is_systemd(): nova.privsep.libvirt.umount(mnt_base) else: nova.privsep.libvirt.unprivileged_umount(mnt_base) except processutils.ProcessExecutionError as exc: ...
flp9001/clevenus
clevenus/config/wsgi.py
Python
gpl-3.0
395
0.002532
""" WSGI config for astrology project. It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.prod") from django.core.wsgi import get_wsg
i_application application = get_wsgi_application()
DeastinY/srpdfcrawler
pdf_search.py
Python
gpl-3.0
2,775
0.000721
import os import sys import sqlite3 import logging from tqdm import tqdm from pathlib import Path from whoosh.index import create_in, open_dir from whoosh.fields import Schema, TEXT, NUMERIC from whoosh.qparser import QueryParser from whoosh.spelling import ListCorrector from whoosh.highlight import UppercaseFormatter ...
(t) query_res = self.searcher.search(query, limit=100) query_res.fragmenter.maxchars = 300 query_res.fragmenter.surround = 100 query_res.formatter = UppercaseFormatter() results.append((t, query_res)) return results def read(self): logging...
con = sqlite3.connect(str(FILE_DB)) cur = con.cursor() cur.execute(r"SELECT BOOKS.NAME, PAGE, CONTENT " r"FROM TEXT, BOOKS " r"WHERE BOOK = BOOKS.ID " r"ORDER BY BOOKS.NAME, PAGE") for row in tqdm(cur): book, page, conte...
jakobharlan/avango
examples/simple_example/main.py
Python
lgpl-3.0
3,625
0.000552
import avango import avango.script import avango.gua from examples_common.GuaVE import GuaVE class TimedRotate(avango.script.Script): TimeIn = avango.SFFloat() MatrixOut = avango.gua.SFMatrix4() def evaluate(self): self.MatrixOut.value = avango.gua.make_rot_mat( self.TimeIn.value * 2....
(-0.5, 0.0, 0.0), Children=[monkey2]) light = avango.gua.nodes.LightNode( Type=avango.gua.LightType.POINT, Name="light", Color=avango.gua.Color(1.0, 1.0, 1.0), Brightness=100.0,
Transform=(avango.gua.make_trans_mat(1, 1, 5) * avango.gua.make_scale_mat(30, 30, 30))) size = avango.gua.Vec2ui(1024, 768) window = avango.gua.nodes.GlfwWindow(Size=size, LeftResolution=size) avango.gua.register_window("window", window) cam = avango.gua.nodes.CameraNode( ...
lemonad/molnetbot
molnetbot/xep0012.py
Python
mit
2,344
0.000427
#!/usr/bin/python # -*- coding: utf-8 -*- """ The MIT license Copyright (c) 2010 Jonas Nockert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation th...
import datetime import time from twisted.words.protocols.jabber.xmlstream import toResponse from wokkel.subprotocols impor
t IQHandlerMixin, XMPPHandler NS_LAST_ACTIVITY = 'jabber:iq:last' LAST_ACTIVITY = '/iq[@type="get"]/query[@xmlns="' + NS_LAST_ACTIVITY +'"]' class LastActivityHandler(XMPPHandler, IQHandlerMixin): """ XMPP subprotocol handler for Last Activity extension. This protocol is described in U{XEP-0012<htt...
SebastianoF/LabelsManager
tests/tools/test_image_colors_manip_relabeller.py
Python
mit
6,757
0.00222
import numpy as np import pytest from nilabels.tools.image_colors_manipulations.relabeller import relabeller, permute_labels, erase_labels, \ assign_all_other_labels_the_same_value, keep_only_one_label, relabel_half_side_one_label def test_relabeller_basic(): data = np.array(range(10)).reshape(2, 5) rela...
3) # Z above new_data = relabel_half_side_one_label(data, label_old=1, label_new=100, side_to_modify='above', axis='z', plane_intercept=1) expected_data = data[:] expected_data[0, 0, 1] = 100 np.testing.assert_array_eq
ual(new_data, expected_data) # Z below new_data = relabel_half_side_one_label(data, label_old=3, label_new=300, side_to_modify='below', axis='z', plane_intercept=2) expected_data = data[:] expected_data[0, 1, 0] = 300 np.testing.assert_array_equal(new_dat...
RobCranfill/weewx
bin/weewx/drivers/ws1.py
Python
gpl-3.0
9,124
0.000986
#!/usr/bin/env python # # Copyright 2014 Matthew Wall # See the file LICENSE.txt for your rights. """Driver for ADS WS1 weather stations. Thanks to Steve (sesykes71) for the testing that made this driver possible. Thanks to Jay Nugent (WB8TKL) and KRK6 for weather-2.kr6k-V2.1 http://server1.nuge.com/~weather/ """ ...
port %s' % self.port) global DEBUG_READ DEBUG_READ = int(stn_dict.get('debug_read', DEBUG_READ)) self.station = Station(self.port) self.station.open() def closePort(self): if self.station is not None:
self.station.close() self.station = None @property def hardware_name(self): return "WS1" def genLoopPackets(self): while True: packet = {'dateTime': int(time.time() + 0.5), 'usUnits': weewx.US} readings = self.station.get...
aaronzhang1990/workshare
test/python/addClasses.py
Python
gpl-2.0
1,111
0.032403
#!/usr/bin/env python # -*- coding: utf-8 -*- import MySQLdb as mdb import uuid, pprint def generate(data): gdata = [] fo
r grade in range(1,4): for clazz in range(1,10): if grade != data['grade_number'] and clazz != data['class_number']: gdata.append("insert into classes(uuid, grade_number, class_number, school_uuid) values('%s', %d, %d, '%s');
" % (unicode(uuid.uuid4()), grade, clazz, data['school_uuid'])) return gdata def main(): config = {'user': 'root', 'passwd': 'oseasy_db', 'db': 'banbantong', 'use_unicode': True, 'charset': 'utf8'} conn = mdb.connect(**config) if not conn: return cursor = conn.cursor() cursor.execute('select grade_number, class_...
junneyang/simplepbrpc
homedir/items.py
Python
mit
8,104
0.006674
#!/usr/bin/env python # coding=utf-8 import errno import os import sys import fileinput import string import logging import traceback import hashlib import time import re from datetime import date, timedelta import datetime from subprocess import call import redis from datasource import DataSource class Items(Dat...
time.sleep(60) return True def checkAvailable(self): try: if self.action == "import": yesterday = date.today() - timedelta(1) self.datedir = yesterday.strftime('%Y%m%d') #self.datedir = "." if self.datedir == self...
if self.datedir == self.downloadedDir: return 2 self.download_url = self.config["url"].replace("${date}", self.datedir) donefile = self.config["checkfile"].replace("${date}", self.datedir) cmd = "hadoop fs -test -e " + donefile ...
EmreAtes/spack
var/spack/repos/builtin/packages/r-rngtools/package.py
Python
lgpl-2.1
2,067
0.000484
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
RRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more d
etails. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * ...
GenericStudent/home-assistant
tests/components/roon/test_config_flow.py
Python
apache-2.0
5,782
0.000346
"""Test the roon config flow.""" from homeassistant import config_entries, setup from homeassistant.components.roon.const import DOMAIN from homeassistant.const import CONF_HOST from tests.async_mock import patch from tests.common import MockConfigEntry class RoonApiMock: """Mock to handle returning tokens for t...
, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] ==
"form" assert result["errors"] == {} with patch("homeassistant.components.roon.config_flow.TIMEOUT", 0,), patch( "homeassistant.components.roon.const.AUTHENTICATE_TIMEOUT", 0, ), patch( "homeassistant.components.roon.config_flow.RoonApi", return_value=RoonApiMock("good_token...
engineer0x47/SCONS
engine/SCons/Tool/aixf77.py
Python
mit
2,681
0.001865
"""engine.SCons.Tool.aixf77 Tool-specific initialization for IBM Visual Age f77 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # Permiss...
env['SHF77'] = _shf77 def exists(env): path, _f77, _shf77, version = get_xlf77(env) if path and _f77: xlf77 = os.path.join(path, _f77) if os.path.exists(xlf7
7): return xlf77 return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
luzfcb/django_documentos
django_documentos/autocomplete_light_registry.py
Python
bsd-3-clause
1,391
0.000719
# -*- coding: utf-8 -*- from __future__ import unicode_literals import autocomplete_light from django.utils.encoding import force_text from .settings import USER_MODEL from .utils.module_loading import get_real_model_class class UserAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = [ ...
choice.get_full_name().title() def choices_for_request(self): return super(UserAutoc
omplete, self).choices_for_request() autocomplete_light.register(UserAutocomplete)
iMuduo/FastSync
setup.py
Python
apache-2.0
690
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Muduo ''' FastSync ''' from setuptools import setup, find_packages setup( name='FastSync', version='0.2.0.3', packages=find_packages(), install_requires=[ 'requests', 'watchdog
', 'pycrypto', 'future', 'web.py' ], entry_points={ 'console_scripts': [ 'fsnd = sync:sending', 'frcv = sync:receiving', ], }, license='Apache License', author='Muduo', au
thor_email='imuduo@163.com', url='https://github.com/iMuduo/FastSync', description='Event driven fast synchronization tool', keywords=['sync'], )
glemaitre/scikit-learn
sklearn/mixture/tests/test_gaussian_mixture.py
Python
bsd-3-clause
40,311
0
# Author: Wei Xue <xuewei4d@gmail.com> # Thierry Guillemot <thierry.guillemot.work@gmail.com> # License: BSD 3 clause import re import sys import copy import warnings import pytest import numpy as np from scipy import stats, linalg from sklearn.covariance import EmpiricalCovariance from sklearn.datasets impo...
rical': 1. / self.covariances['spherical'], 'diag': 1. / self.covariances['diag'], 'tied': linalg.inv(self.covariances['tied']), 'full': np.array([linalg.inv(
covariance) for covariance in self.covariances['full']])} self.X = dict(zip(COVARIANCE_TYPE, [generate_data( n_samples, n_features, self.weights, self.means, self.covariances, covar_type) for covar_type in COVARIANCE_TYPE])) self.Y = np.hstack([np.fu...
pupboss/xndian
deploy/site-packages/py2exe/samples/advanced/MyService.py
Python
mit
2,011
0.001989
# # A sample service to be 'compiled' into an exe-file with py2exe. # # See also # setup.py - the distutils' setup script # setup.cfg - the distutils' config file for this # README.txt - detailed usage notes # # A minimal service, doing nothing else than # - write 'start' and 'stop' entries into th...
service.SERVICE_STOP_PENDING) win32event.Set
Event(self.hWaitStop) def SvcDoRun(self): import servicemanager # Write a 'started' event to the event log... win32evtlogutil.ReportEvent(self._svc_name_, servicemanager.PYS_SERVICE_STARTED, 0, # category ...
jrbourbeau/cr-composition
processing/legacy/anisotropy/random_trials/process_kstest.py
Python
mit
7,627
0.002098
#!/usr/bin/env python import os import argparse import numpy as np import pandas as pd import pycondor import comptools as comp if __name__ == "__main__": p = argparse.ArgumentParser( description='Extracts and saves desired information from simulation/data .i3 files') p.add_argument('-c', '--config...
help='Number of lines used when reading in DataF
rame') p.add_argument('--n_batches', dest='n_batches', type=int, default=50, help='Number batches running in parallel for each ks-test trial') p.add_argument('--ks_trials', dest='ks_trials', type=int, default=100, help='Number of random...
adobe-research/spark-cluster-deployment
initial-deployment-puppet/modules/spark/files/spark/python/pyspark/mllib/classification.py
Python
apache-2.0
7,307
0.001505
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
t(self, x): _linear_predictor_typechec
k(x, self._coeff) margin = _dot(x, self._coeff) + self._intercept prob = 1/(1 + exp(-margin)) return 1 if prob > 0.5 else 0 class LogisticRegressionWithSGD(object): @classmethod def train(cls, data, iterations=100, step=1.0, miniBatchFraction=1.0, initialWeights=None): """Train...
xinbian/2dns
tests/test_python_2d_ns.py
Python
mit
2,191
0.043359
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_python_2d_ns ---------------------------------- Tests for `python_2d_ns` module. """ import sys import unittest from python_2d_ns.python_2d_ns import * class TestPython_2d_ns(unittest.TestCase): #test x, y coordinates generated by function
IC_coor #assume use 2 threads and rank==1 #y coordinate should be the same as serial code def test_IC_coor_y_coor(self): x, y, kx, ky, k2, k2_exp=IC_coor(64, 64, 32, 1, 1, 1, 2) self.assert
True(y[3,0]==-32) self.assertTrue(y[3,5]==-27) #x coordinate for rank 2 should start from 0 def test_IC_coor_x_coor(self): x, y, kx, ky, k2, k2_exp=IC_coor(64, 64, 32, 1, 1, 1, 2) #this coordinate should be 0 self.assertTrue(x[0,2]==0) #test initial condition, Taylor green fo...
Drvanon/Game
venv/lib/python3.3/site-packages/tornado/iostream.py
Python
apache-2.0
41,823
0.000287
#!/usr/bin/env python # # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
cific langua
ge governing permissions and limitations # under the License. """Utility classes to write to and read from non-blocking files and sockets. Contents: * `BaseIOStream`: Generic interface for reading and writing. * `IOStream`: Implementation of BaseIOStream using non-blocking sockets. * `SSLIOStream`: SSL-aware version...
LLNL/spack
var/spack/repos/builtin/packages/py-ytopt/package.py
Python
lgpl-2.1
1,360
0.003676
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyYtopt(PythonPackage): """Ytopt package implements search using Random Forest (SuRF), an ...
e=('build', 'run')) depends_on('py-ytopt-autotune@1.1:', type=('build', 'run')) depends_on('py-joblib', type=('build', 'run')) depends_on('py-deap', type=('bu
ild', 'run')) depends_on('py-tqdm', type=('build', 'run')) depends_on('py-ray', type=('build', 'run')) depends_on('py-mpi4py@3.0.0:', type=('build', 'run'))
plotly/plotly.py
packages/python/plotly/plotly/validators/scatter3d/marker/colorbar/_tickvalssrc.py
Python
mit
461
0
import _plotly_utils.basevalidators class TickvalssrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="tickvalssrc", parent_name="scatter3d.marker.colorbar", **kwargs ): super(TickvalssrcValidator, self).__init__( plotly_...
dit_type", "none"), **kwarg
s )
magnusax/ml-meta-wrapper
gazer/visualize.py
Python
mit
1,824
0.01261
import sys import pandas as pd import seaborn as sns import matplotlib.pyplot as plt class Visualizer():
def __init__(self, *args): pass def show_performance(self, list_of_tuples, fig_size=(9,9), font_scale=1.1, file=''): """ Parameters: list_of_tuples: - list containing (clf_name, clf_performance) tuples for each classi...
cale: - text scale in seaborn plots (default: 1.1) file: - string containing a valid filename (default: '') Output: f: (matplotlib.pyplot.figure object) """ if not (isinstance(list_of_tuples, list) and isin...
mrjmad/robotswars
maingame/urls.py
Python
mit
868
0.009217
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from .views import (AvailableMapListview, AvailableMapsDetailview,
index_view, MyArmiesListView, ArmyCreateView, ArmyDetailView, RobotCreateView) urlpatterns = patterns('', url(r'maingame/maps$', AvailableMapListview.as_view(), name='list_available_maps'), url(r'maingame/map/(?P<pk>\d+)$', AvailableMapsDetailview.as_view(), name="available_...
ngame/army/(?P<pk>\d+)$', ArmyDetailView.as_view(), name="army_detail" ), url(r'maingame/create_armies$', ArmyCreateView.as_view(), name='add_army'), url(r'maingame/create_robot$', RobotCreateView.as_view(), name='add_robot_to_army'), url(r'^$', index_view, name="index"), )
DIRACGrid/DIRAC
src/DIRAC/Core/scripts/dirac_version.py
Python
gpl-3.0
662
0
#!/usr/bin/env python ######################################################################## # File : dirac-version # Author : Ricardo Graciani ######################################################################## """ Print version of current DIRAC installation Usage: dirac-version
[option] Example: $ dirac-version """ import argparse import DIRAC from DIRAC.Core.Base.Script import Script @Script() def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.parse_known_args()
print(DIRAC.version) if __name__ == "__main__": main()
pepincho/Python101-and-Algo1-Courses
Algo-1/Application/1-Palindromes.py
Python
mit
937
0
def is_palindrome(obj): obj = str(obj) obj_list = list(obj) obj_list_reversed = obj_list[::-1] return obj_list == obj_list_reversed def generate_rotations(word): letters = list(word) string_rotations = [] counter = len(letters) temp = letters while counter != 0: current_l...
if is_empty is True: print("NONE")
def main(): user_input = input("Enter a string: ") string_rotations = generate_rotations(user_input) get_rotated_palindromes(string_rotations) if __name__ == '__main__': main()
wangjun/flask-paginate
example/app.py
Python
bsd-3-clause
2,185
0.001373
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals import sqlite3 from flask import Flask, render_template, g, current_app, request from flask.ext.paginate import Pagination app = Flask(__name__) app.config.from_pyfile('app.cfg') @app.before_request def before_request(): g.conn...
= (page - 1) * per_page return page, per_page, offset def get_pagination(**kwargs): kwargs.setdefault('record_n
ame', 'records') return Pagination(css_framework=get_css_framework(), link_size=get_link_size(), show_single_page=show_single_page_or_not(), **kwargs ) if __name__ == '__main__': app.run(debug=True)
gunnery/gunnery
gunnery/core/views.py
Python
apache-2.0
7,964
0.001758
from django.contrib.contenttypes.models import ContentType import json from django.http import Http404, H
ttpResponse from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required, user_passes_test from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect, render from guardian.decorators import p...
TestConnectionTask from event.models import NotificationPreferences from .models import Application, Department, Environment, Server, ServerRole from task.models import Execution @login_required def index(request): data = {} executions = Execution.objects.filter(task__application__department_id=reque...
mezz64/home-assistant
homeassistant/components/acmeda/sensor.py
Python
apache-2.0
1,666
0
"""Support for Acmeda Roller Blind Batteries.""" from __future__ import annotations from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE from homeassistant.core import HomeAssistant, callback from hom...
hass, ACMEDA_HUB_UPDATE.format(config_entry.entry_id), async_add_acmeda_sensors, ) ) class AcmedaBattery(AcmedaBase, SensorEntity): """Representation of a Acmeda cover device.""" device_class = SensorDeviceClass.BATTERY _attr_native_unit_of_measurement = PERCENTAGE...
"""Return the name of roller.""" return f"{super().name} Battery" @property def native_value(self): """Return the state of the device.""" return self.roller.battery
ashcrow/etcdobj
setup.py
Python
bsd-3-clause
2,107
0.000475
#!/usr/bin/env python # # 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 disclaimer. # # ...
AY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Python setup script. """ from setuptools import setup, find_packages def extract_requirements(filename): with open(filename, 'r') as requirements_file: return [x[:-1] for x in requirements_file.readlines()] inst...
description='Basic ORM for etcd', author='Steve Milner', url='https://github.com/ashcrow/etcdobj', license="MBSD", install_requires=install_requires, tests_require=test_require, package_dir={'': 'src'}, packages=find_packages('src'), )
subramani95/neutron
neutron/plugins/plumgrid/plumgrid_plugin/plumgrid_plugin.py
Python
apache-2.0
24,717
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 PLUMgrid, 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/lic...
p to be True port["port"]["admin_state_up"] = True with context.session.begin(subtransactions=True): # Plugin DB - Port
Create and Return port port_db = super(NeutronPluginPLUMgridV2, self).create_port(context, port) device_id = port_db["device_id"] if port_db["device_owner"] == constants.DEVICE_OWNER_ROUTER_GW: rou...
saltstack/salt
tests/pytests/unit/test_minion.py
Python
apache-2.0
35,098
0.001197
import copy import logging import os import pytest import salt.ext.tornado import salt.ext.tornado.gen import salt.ext.tornado.testing import salt.minion import salt.syspaths import salt.utils.crypt import salt.utils.event as event import salt.utils.platform import salt.utils.process from salt._compat import ipaddress...
et": [
{ "broadcast": "111.1.111.255", "netmask": "111.1.0.0", "label": "bond0", "address": "111.1.0.1", } ], } } opts = salt.config.DEFAULT_MINION_OPTS.copy() with patch.dict( opts, ...
andela-kanyanwu/food-bot-review
rtmbot.py
Python
mit
7,049
0.001844
#!/usr/bin/env python import sys # sys.dont_write_bytecode = True import glob import os import time import logging import os.path from argparse import ArgumentParser class RtmBot(object): def __init__(self, token): self.last_ping = 0 self.token = token self.bot_plugins = [] self...
self.slack_client.rtm_connect() def start(self): self.connect() self.load_plugins() while True: for reply in self.slack_client.rtm_re
ad(): self.input(reply) self.crons() self.output() self.autoping() time.sleep(.5) def autoping(self): # hardcode the interval to 3 seconds now = int(time.time()) if now > self.last_ping + 3: self.slack_client.server...
CERNDocumentServer/invenio
modules/miscutil/lib/mailutils.py
Python
gpl-2.0
22,698
0.001983
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2...
subject="", content="", header=None, footer=None, copy_to_admin=0, attempt_times=1, attempt_sleeptime=10,
user=None, other_bibtasklet_arguments=None, replytoaddr="", bccaddr="", ): """ Like send_email, but send an email via the bibsched infrastructure. @param fromaddr: sender @type fromaddr: string ...
Diyago/Machine-Learning-scripts
DEEP LEARNING/segmentation/Kaggle TGS Salt Identification Challenge/v2/modules/build.py
Python
apache-2.0
544
0
import os from torch.utils.ffi import create_extension sources = ["src/lib_cffi.cpp"] headers = ["src/lib_cffi.h"] extra_objects = ["src/bn.o"] with_cuda = True t
his_file = os.path.dirname(os.path.realpath(__file__)) extra_objects = [os.path.join(this_file, fname) for fname in extra_objects] ffi = create_extension( "_ext", headers=hea
ders, sources=sources, relative_to=__file__, with_cuda=with_cuda, extra_objects=extra_objects, extra_compile_args=["-std=c++11"], ) if __name__ == "__main__": ffi.build()
Programmica/pygtk-tutorial
examples/socket.py
Python
cc0-1.0
572
0.005245
#!/usr/bin/env python import gtk, sys, string class Socket: def __init__(self): window = gtk.Window() window.set_default_size(200, 200) socket = gtk.Socket() window.add(socket)
pr
int "Socket ID:", socket.get_id() if len(sys.argv) == 2: socket.add_id(long(sys.argv[1])) window.connect("destroy", gtk.main_quit) socket.connect("plug-added", self.plugged_event) window.show_all() def plugged_event(self, widget): print "A plug has been insert...
louyihua/edx-platform
common/test/acceptance/tests/video/test_video_events.py
Python
agpl-3.0
13,984
0.002932
"""Ensure videos emit proper events""" import datetime import json from nose.plugins.attrib import attr import ddt from common.test.acceptance.tests.helpers import EventsTestMixin from common.test.acceptance.tests.video.test_video_module import VideoBaseTest from common.test.acceptance.pages.lms.video.video import _p...
And I watch 5 seconds of it And I pause the video Then a "load_video" event is emitted And a "play_video" event is emitted And a "pause_video" event is emitted """ def is_video_event(event): """Filter out anything other than the video events of interest""" ...
') captured_events = [] with self.capture_events(is_video_event, number_of_matches=3, captured_events=captured_events): self.navigate_to_video() self.video.click_player_button('play') self.video.wait_for_position('0:05') self.video.click_player_button('pa...
EmanueleCannizzaro/scons
test/QT/up-to-date.py
Python
mit
4,303
0.002789
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
</property> </widget> <includes> <include location="local" impldecl="in implementation">migraform.h</include> </includes> </UI> """) test.write(['layer', 'aclock', 'qt_bug', 'migraform.ui'], """\ <!DOCTYPE UI><UI version="3.3" stdsetdef="1"> <class>MigrateForm</class> <widget class="QWizard"> <property name=...
<cstring>MigrateForm</cstring> </property> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>600</width> <height>385</height> </rect> </property> </widget> </UI> """) test.write(['layer', 'aclock', 'qt_bug', 'my.cc'], """\ #include ...
bcui6611/healthchecker
cluster_stats.py
Python
apache-2.0
19,273
0.01349
import stats_buffer import util_cli as util class BucketSummary: def run(self, accessor): return stats_buffer.bucket_info class DGMRatio: def run(self, accessor): result = [] hdd_total = 0 ram_total = 0 for node, nodeinfo in stats_buffer.nodes.iteritems(): ...
nfo in stats_buffer.buckets.iteritems(): values = stats_info[accessor["scale"]][accessor["counter"]] timestamps = values["timestamp"] timestamps = [x - timestamps[0] for x in timestamps] nodeStats = values["nodeStats"] samplesCount = values["samplesCount"] ...
, vals in nodeStats.iteritems(): #a, b = util.linreg(timestamps, vals) value = sum(vals) / samplesCount total += value if value > accessor["threshold"]: num_error.append({"node":node, "value":value}) trend.append((node, ...
i5on9i/echoserver
main.py
Python
apache-2.0
1,161
0
"""`main` is the top level module for your Flask application.""" # Import the Flask Framework import os import json from flask import Flask, request, send_from_directory, render_template app = Flask(__name__, static_url_path='') # Note: We don't need to call run() since our application is embedded within # the App E...
""Return a friendly HTTP greeting.""" return 'Hello World!' @app.errorhandler(404) def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, Nothing at this URL.', 404 @app.errorhandler(500) def application_error(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: ...
send_js(path): file, ext = os.path.splitext(path) if ext == "": ext = ".json" SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) json_url = os.path.join(SITE_ROOT, "static", "json", file + ext) s = '' with open(json_url) as f: for line in f: s += line ret...
mezz64/home-assistant
homeassistant/components/unifiprotect/select.py
Python
apache-2.0
13,007
0.001538
"""This component provides select entities for UniFi Protect.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta from enum import Enum import logging from typing import Any, Final from pyunifiprotect.data import ( Camera, DoorbellMessageType, IRLEDMode, ...
LIGHT_MODE_OFF = "Manual" LIGHT_MODES = [LIGHT_MODE_MOTION, LIGHT_MODE_DARK, LIGHT_MODE_OFF] LIGHT_MODE_TO_SETTINGS = { LIGHT_MODE_MOTION: (LightModeType.MOTION.value, LightModeEnableType.ALWAYS.value), LIGHT_MODE_MOTION_DARK: ( LightModeType.MOT
ION.value, LightModeEnableType.DARK.value, ), LIGHT_MODE_DARK: (LightModeType.WHEN_DARK.value, LightModeEnableType.DARK.value), LIGHT_MODE_OFF: (LightModeType.MANUAL.value, None), } MOTION_MODE_TO_LIGHT_MODE = [ {"id": LightModeType.MOTION.value, "name": LIGHT_MODE_MOTION}, {"id": f"{LightM...
ringly/django-postgres-dbdefaults
postgresql_dbdefaults/creation.py
Python
mit
61
0
fr
om django.db.backe
nds.postgresql.creation import * # NOQA
wouteroostervld/snaps
setup.py
Python
mit
465
0.004301
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'My Project', 'author': 'Wouter Oosterveld', 'url': 'URL to get it at.', 'download_url': 'Where to download it.', 'author_email': 'wouter@fizzyflux.nl', 'version': '0.1', ...
ires': ['n
ose','what','boto'], 'packages': ['snaps'], 'scripts': ['scripts/snaps'], 'name': 'snaps' } setup(**config)
nop33/indico
indico/modules/events/agreements/base.py
Python
gpl-3.0
7,667
0.002739
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
identifier) @property def identifier(self): data_string = None if self.data: data_string = '-'.join('{}={}'.format(k, make_hashable(v)) for k, v in sorted(self.data.viewitems())) identifier = '{}:{}'.format(self.email, data_string or None) return sha1(id
entifier).hexdigest() class AgreementDefinitionBase(object): """Base class for agreement definitions""" #: unique name of the agreement definition name = None #: readable name of the agreement definition title = None #: optional and short description of the agreement definition descriptio...
followyourheart/cloudly
vms/views.py
Python
mit
39,971
0.014586
# -*- coding: utf-8 -*- import os import time import logging import string import requests import unicodedata import base64 try: import cPickle as pickle except: import pickle import datetime from django.utils import timezone import json from pprint import pprint from django.shortcuts import render_to_response fr...
"): ec2conn.reboot_instances([vm_name,]) if(action=="start"): ec2conn.start_instances([vm_name,]) if(action=="stop"): ec2conn.stop_instances([vm_name,]) if(action=="terminate"): ec2conn.terminate_instances([vm_name,]) return HttpResponseRedirect("/") @login_required() ...
file.objects.get(user=request.user) ip = request.META['REMOTE_ADDR'] _log_user_activity(profile,"click","/server/"+hwaddr,"server_view",ip=ip) hwaddr_orig = hwaddr hwaddr = hwaddr.replace('-',':') server = mongo.servers.find_one({'secret':profile.secret,'uuid':hwaddr,}) server_status = "Runni...
RevansChen/online-judge
Codewars/8kyu/century-from-year/Python/solution1.py
Python
mit
74
0.013514
# Pytho
n - 3.6.0 century
= lambda year: year // 100 + ((year % 100) > 0)
ellipticaldoor/dfiid
project/content/views.py
Python
gpl-2.0
5,667
0.02541
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import View, ListView, DetailView from django.views.generic.edit import CreateView, UpdateView from content.models import Sub, SubFollow, Post, Commit from content.forms import SubForm, PostForm, CommitF...
d_obj.sub.save() return HttpResponse(status=200) class SubFollowDelete(View): def post(self, request, *args, **kwargs): sub_unfollowed = self.kwargs['unfollowed'] sub_unfollowed_obj = SubFollow.objects.get(follower=self.request.user, sub_id=sub_unfollowed) sub_unfollowed_obj.follower.sub_following_number -...
j.delete() return HttpResponse(status=200)
sciCloud/OLiMS
report/olims_sample_received_vs_reported.py
Python
agpl-3.0
4,408
0.009301
# -*- coding: utf-8 -*- import time from openerp import api, models import datetime class ReportSampleReceivedvsReported(models.AbstractModel): _name = 'report.olims.report_sample_received_vs_reported' def _get_samples(self, samples): datalines = {} footlines = {} total_received_coun...
ateReceived, \ "%Y-%m-%d %
H:%M:%S") monthyear = datereceived.strftime("%B") + " " + datereceived.strftime( "%Y") received = 1 publishedcnt = published and 1 or 0 if (monthyear in datalines): received = datalines[monthyear]['ReceivedCount'] + 1 publis...
frankhale/nyana
nyana/plugins/SnippetViewPlugin.py
Python
gpl-3.0
18,007
0.038929
# SnippetViewPlugin - Provides a templated/abbreviation expansion mechanism for # the editor. # # Copyright (C) 2006-2010 Frank Hale <frankhale@gmail.com> # # ##sandbox - irc.freenode.net # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # a...
k.RESIZE_PARENT) ### Comment this out if you don't want Monospace and want the default ### system font. Or change to suit your needs. default_font = pango.FontDescription("Monospace 10") if default_font: self.editor.source_view.modify_font(default_font) ### -------------------------------
------------------------- ### self.editor.source_view.connect("key-press-event", self.key_event) self.editor.buff.connect("mark-set", self.mark_set) self.SL = SnippetLoader() self.SNIPPETS.extend(self.SL.get_common()) self.SNIPPETS.extend(BUILT_IN_SNIPPETS) # For testing purposes. #self.syntax_hig...
angr/angr
angr/flirt/build_sig.py
Python
bsd-2-clause
10,375
0.00241
# pylint:disable=consider-using-with from typing import List, Dict import json import subprocess import argparse import tempfile import os import itertools from collections import defaultdict import angr UNIQUE_STRING_COUNT = 20 # strings longer than MAX_UNIQUE_STRING_LEN will be truncated MAX_UNIQUE_STRING_LEN = 70...
for subs in s.split(".")): continue # C++ specific if "::" in s: continue if "_" in s: #
make sure it's not a substring of any symbol is_substring = False for symbol in symbols: if s in symbol: is_substring = True break if is_substring: ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.3.0/Lib/tkinter/ttk.py
Python
mit
56,245
0.002471
"""Ttk wrapper. This module provides classes to allow using Tk themed widget set. Ttk is based on a revised and enhanced version of TIP #48 (http://tip.tcl.tk/48) specified style engine. Its basic idea is to separate, to the extent possible, the code implementing a widget's behavior from the code implementing its ap...
if isinstance(value, (list, tuple)): v = [] for val in value: if isinstance(val, str): v.append(str(val) if val else '{}') else: v.append(str(val)) # format v according to the script option, but also check...
in val else '%s') % val for val in v) if script and value == '': value = '{}' # empty string in Python is equivalent to {} in Tcl opts.append(("-%s" % opt, value)) # Remember: _flatten skips over None return _flatten(opts) def _format_mapdict(mapdict, script=False): """Format...
machawk1/pywb
pywb/rewrite/test/test_rewrite_live.py
Python
gpl-3.0
9,395
0.007025
from pywb.rewrite.rewrite_live import LiveRewriter from pywb.rewrite.url_rewriter import UrlRewriter from pywb.rewrite.wburl import WbUrl from pywb import get_test_dir from io import BytesIO # This module has some rewriting tests against the 'live web' # As such, the content may change and the test may break urlrew...
get_test_dir() + 'text_content/sample.html',
urlrewriter, head_insert_func, 'example,example,test,loconly)/') # wombat insert added assert '<script src="/static/__pywb/wombat.js"> </script>' in buff # JS location rewritten, JS link NOT rewritten ...
jromang/retina-old
distinclude/spyderlib/plugins/onlinehelp.py
Python
gpl-3.0
3,199
0.00813
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """Online Help Plugin""" from spyderlib.qt.QtCore import Signal import os.path as osp # Local imports from spyderlib.baseconfig import get_conf_path, ...
cancelable=False): """Perform actions before
parent main window is closed""" self.save_history() self.set_option('zoom_factor', self.webview.get_zoom_factor()) return True def refresh_plugin(self): """Refresh widget""" pass def get_plugin_actions(self): """Return a list of actions re...
partofthething/home-assistant
homeassistant/components/hive/switch.py
Python
apache-2.0
2,449
0.000817
"""Support for the Hive switches.""" from datetime import timedelta from homeassistant.components.switch import SwitchEntity from . import ATTR_AVAILABLE, ATTR_MODE, DATA_HIVE, DOMAIN, HiveEntity, refresh_system PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) async def async
_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Hi
ve Switch.""" if discovery_info is None: return hive = hass.data[DOMAIN].get(DATA_HIVE) devices = hive.devices.get("switch") entities = [] if devices: for dev in devices: entities.append(HiveDevicePlug(hive, dev)) async_add_entities(entities, True) class HiveDevice...
sassoftware/rmake3
rmake/cmdline/monitor.py
Python
apache-2.0
26,810
0.001567
# # Copyright (c) SAS Institute 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 w...
hed(): self._serveLoopHook() self._msg('[%d] - State: %s' % (jobId, state)) if status: self._msg('[%d] - %s' % (jobId, status)) def _jobLogUpdated(self, jobId, state, status): self._msg('[%d] %s' % (jobId, status)) def _troveStateUpdated(self, (jobId, troveTuple...
rove.TroveState.BUILDING, buildtrove.TroveState.RESOLVING)) state = buildtrove.stateNames[state] self._msg('[%d] - %s - State: %s' % (jobId, troveTuple[0], state)) if status: self._msg('[%d] - %s - %s' % (jobId, troveTuple[0], status)) if isBui...
feixiao5566/Py_Rabbic
IO/自定义迭代器.py
Python
bsd-2-clause
402
0.00995
#!/usr/bin/env python # encoding: utf-8 class MyRange(object): def __init__(self, n): self.idx = 0
self.n = n def __iter__(self): return self def next(self): if self.idx < self.n: val = self.idx self.idx += 1 ret
urn val else: raise StopIteration() myRange = MyRange(3) for i in myRange: print i
hozn/keepassdb
setup.py
Python
gpl-3.0
2,399
0.013344
# -*- coding: utf-8 -*- import os.path import re import warnings try: from setuptools import setup, find_packages except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages version = '0.2.1' news = os.path.join(os.path.dirname(__file__...
llelid", author_email = "hans@xmpl.org", url = "http://github.com/hozn/keepassdb", license
= "GPLv3", description = "Python library for reading and writing KeePass 1.x databases.", long_description = long_description, packages = find_packages(), include_package_data=True, package_data={'keepassdb': ['tests/resources/*']}, install_requires=['pycrypto>=2.6,<3.0dev'], tests_require ...
harveybia/face-hack
venv/face/bin/player.py
Python
mit
2,210
0
#!/Users/harvey/Projects/face-hack/venv/face/bin/python # # The Python Imaging Library # $Id$ # from __future__ import print_function try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys # ----
---------------------------------------------------------------- # an image animation player class UI(Label): def __init__(self, master, im): if isinstance(im, list): # list of images self.im = im[
1:] im = self.im[0] else: # sequence self.im = im if im.mode == "1": self.image = ImageTk.BitmapImage(im, foreground="white") else: self.image = ImageTk.PhotoImage(im) Label.__init__(self, master, image=self.image, bg="black",...
kevin-intel/scikit-learn
sklearn/impute/_knn.py
Python
bsd-3-clause
11,682
0
# Authors: Ashim Bhattarai <ashimb9@gmail.com> # Thomas J Fan <thomasjpfan@gmail.com> # License: BSD 3 clause import numpy as np from ._base import _BaseImputer from ..utils.validation import FLOAT_DTYPES from ..metrics import pairwise_distances_chunked from ..metrics.pairwise import _NAN_METRICS from ..neig...
don
ors = fit_X_col.take(donors_idx) donors_mask = mask_fit_X_col.take(donors_idx) donors = np.ma.array(donors, mask=donors_mask) return np.ma.average(donors, axis=1, weights=weight_matrix).data def fit(self, X, y=None): """Fit the imputer on X. Parameters ---------- ...
johnkerl/scripts-math
pythonlib/bin/jac.py
Python
bsd-2-clause
5,698
0.044577
#!/usr/bin/python -Wall # ================================================================ # Copyright (c) John Kerl 2007 # kerl.john.r@gmail.com # ================================================================ from __future__ import division # 1/2 = 0.5, not 0. from math import * from sackmat_m import * import cop...
ranspose() rank = proj_e.rank()
#print "p0=[%7.4f,%7.4f,%7.4f] p1=[%7.4f,%7.4f,%7.4f]" % ( #proj_e[0][0], proj_e[0][1], proj_e[0][2], proj_e[1][0], proj_e[1][1], proj_e[1][2]), #print "rank=", proj_e.rank_rr(), #print "d=%11.3e" % (d), # xxx hack if (rank == 1): d = 0.7 #print "%11.3e" % (d), print "%8.4f" % (d), ...
Azure/azure-sdk-for-python
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2020_06_01/aio/_web_site_management_client.py
Python
mit
8,647
0.004857
# 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 ...
._client, self._config, self._serialize, self._deserialize) self.domain_registration_provider = DomainRegistrationProviderOperations(self._client, self._config, self._serialize, self._deserialize) self.certificates = CertificatesOperations(self._client, self._config, self._serialize, self._deserialize
) self.deleted_web_apps = DeletedWebAppsOperations(self._client, self._config, self._serialize, self._deserialize) self.diagnostics = DiagnosticsOperations(self._client, self._config, self._serialize, self._deserialize) self.provider = ProviderOperations(self._client, self._config, self._seriali...
1m0r74l17y/FortyTwo
FortyTwo/__init__.py
Python
mit
80
0.0125
fro
m Fort
yTwo.fortytwo import * def Start(): """No Clue what to add here"""
sloria/sepal
sepal/datasets/tasks.py
Python
bsd-3-clause
8,545
0.007373
import os from django.conf import settings import yaafelib as yf import wave import contextlib from celery import task from sepal.datasets.models import * from sepal.datasets.utils import filter_by_key, find_dict_by_item @task() def handle_uploaded_file(f): '''Saves an uploaded data source to MEDIA_ROOT/data_so...
tract_features(dataset_id, instance_id, audiofile_path): dataset = Dataset.o
bjects.get(pk=dataset_id) inst = Instance.objects.get(pk=instance_id) n_frames, sample_rate, duration = 0, 0, 0 # Calculate the sample rate and duration with contextlib.closing(wave.open(audiofile_path, 'r')) as audiofile: n_frames = audiofile.getnframes() sample_rate = audiofile.ge...
blocktrail/blocktrail-sdk-python
tests/cross_platform_test.py
Python
mit
1,454
0.003439
import unittest import hashlib import httpsig.sign as sign from httpsig.utils import parse_authorization_header from requests.models import RequestEncodingMixin class CrossPlatformTestCase(unittest.TestCase): def test_content_md5(self): data = {'signature': "HPMOHRgPSMKdXrU6AqQs/i9S7alOakkHsJiqLGmInt05Cxj...
HsJiqLGmInt05Cxj6b%2FWhS7kJxbIQxKmDW08YKzoFnbVZIoTI2qofEzk%3D" assert hashlib.md5(RequestEncodingMixin._encode_params(data).encode("utf-8")).hexdigest() == "fdfc1a717d2c97649f3b8b2142507129" def test_hmac(self): hs = sign.HeaderSigner(key_id='pda', algorithm='hmac-sha256', secret='secret', headers=...
'GET', path='/path?query=123') auth = parse_authorization_header(signed['authorization']) params = auth[1] self.assertIn('keyId', params) self.assertIn('algorithm', params) self.assertIn('signature', params) self.assertEqual(params['keyId'], 'pda') self.assertEqu...
istommao/wechatkit
wechatkit/resource.py
Python
mit
1,185
0
"""Resource manage module.""" import os from .utils import RequestUtil class ResourceAPI(object): """Resource wechat api.""" ADD_TEMP_URI = ('https://api.weixin.qq.com/cgi-bin/media/' 'upload?access_token={}&type={}') @classmethod def upload(cls, path, token, rtype, upload_type=...
ath :token str: Wechat access token :rtype str: Resource type such as image, voice ... :upload_type: Upload type, Now support temp and forever """ if not os.path.exists(path): return False method = getattr(cls, '_upload_{}'.format(upload_type), None) ...
return method(path, token, rtype) return False @classmethod def _upload_temp(cls, path, token, rtype): """Upload temp media to wechat server. :path str: Upload entity local path :token str: Wechat access token :rtype str: Upload entity type :Return dict: ...
singingwolfboy/webhookdb
webhookdb/load/pull_request_file.py
Python
agpl-3.0
1,058
0.002836
# coding=utf-8 from __future__ import unicode_literals, print_function from flask import request, jsonify, url_for from flask_login import current_user import bugsnag from . import load from webhookdb.tasks.pull_request_file import spawn_page_tasks_for_pull_request_files @load.route('/repos/<owner>/<repo>/pulls/<int:...
_request_files(owner, repo, number): """ Queue tasks to load the pull request files (diffs) for a single pull request into WebhookDB. :statuscode 202: task successfully queued """ bugsnag_ctx = {"owner": owner, "repo": repo, "number": number} bugsnag.configure_request(meta_data=bugsnag_ctx)...
st_files.delay( owner, repo, number, children=children, requestor_id=current_user.get_id(), ) resp = jsonify({"message": "queued"}) resp.status_code = 202 resp.headers["Location"] = url_for("tasks.status", task_id=result.id) return resp
brooksandrew/postman_problems
postman_problems/tests/test_example_sleeping_giant.py
Python
mit
6,009
0.002663
import math import pkg_resources import itertools import pandas as pd import networkx as nx from postman_problems.viz import add_node_attributes from postman_problems.graph import ( read_edgelist, create_networkx_graph_from_edgelist, get_odd_nodes, get_shortest_paths_distances ) from postman_problems.solver import ...
ance'] for edge in rpp_solution]) assert math.isclose(rpp_solution_distance, 32.12) # make sure our circuit begins and ends at the same place assert rpp_solution[0][0] == rpp_solution[-1][1] == START_NODE # make sure original graph is properly returned assert len(graph.edges()) == 133 [e[3].ge...
ata=True, keys=True)].count(True) == 30