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
zengenti/ansible
lib/ansible/modules/network/exoscale/exo_dns_record.py
Python
gpl-3.0
12,408
0.00137
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2016, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible 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 Lice...
state: absent ''' RETURN = ''' --- exo_dns_record: description: API record results returned: success type: dictionary contains: content: description: value of the record returned: success type: string sample: 1.2.3.4 created_at: ...
domain: description: Name of the domain returned: success type: string sample: example.com domain_id: description: ID of the domain returned: success type: int sample: 254324 id: descripti...
StingraySoftware/dave
src/test/python/test/utils/test_dave_reader.py
Python
apache-2.0
4,412
0.002267
from test.fixture import * from hypothesis import given from hypothesis.strategies import text from astropy.io import fits import utils.dave_reader as DaveReader from utils.dave_reader import save_to_intermediate_file, load_dataset_from_intermediate_file import utils.file_utils as FileUtils from stingray.events impor...
(dataset.tables[table_ids[1]].columns) == 2 @given(text()) def test_get_events_fits_dataset_with_stingray(s): destination = FileUtils.get_destination(TEST_RESOURCES, "test.evt")
ds_id = "fits_table" table_ids = ["Primary", "EVENTS", "GTI"] # Opening Fits hdulist = fits.open(destination) dataset = DaveReader.get_events_fits_dataset_with_stingray(destination, hdulist) assert dataset assert len(dataset.tables) == 2 assert table_ids[1] in dataset.tables asser...
rocket-league-replays/rocket-league-replays
rocket_league/apps/replays/migrations/0039_auto_20160417_1058.py
Python
gpl-3.0
548
0.001825
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db im
port migrations, models class Migration(migrations.Migration): dependencies = [ ('replays', '0038_auto_20160417_1042'), ] operations = [ migrations.CreateModel( name='Body', fields=[ ('id', models.PositiveIntegerField(serialize=False, primary_key=T...
('name', models.CharField(max_length=100, default='Unknown')), ], ), ]
AButenko/selenium_tests
framework/gui/loginpage.py
Python
bsd-3-clause
1,961
0.00306
# -*- coding: utf-8 -*- from framework.gui.common.basepage import BasePage from framework.gui.common.locators import HOMEPAGE from framework.gui.common.tools import wait_for_page_load, page_contain_assert from selenium.webdriver.common.keys import Keys # from se
lenium.webdriver.support import expected_conditions as EC # from selenium.webdriver.support.wait import WebDriverWait class LoginPage(BasePage): def __init__(self, driver): super().__init__(driver) self.login_page = HOMEPAGE + "/l
ogin" self.logout_page = HOMEPAGE + "/account/logout" def enter_login_credentials(self, username, password): name = self._driver.find_element_by_name("username") name.send_keys(username) psswd = self._driver.find_element_by_name("password") psswd.send_keys(password) ...
npuichigo/ttsflow
third_party/tensorflow/tensorflow/tools/dist_test/scripts/k8s_tensorflow_test.py
Python
apache-2.0
4,446
0.001574
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
verning permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.tools.dist_test.scripts.k8s_tensorflow_lib.""" from __f
uture__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.platform import googletest from tensorflow.tools.dist_test.scripts import k8s_tensorflow_lib class K8sTensorflowTest(googletest.TestCase): def testGenerateConfig_LoadBalancer(self): # Us...
carolinux/QGIS
python/plugins/processing/script/ScriptAlgorithmProvider.py
Python
gpl-2.0
3,302
0.000909
# -*- coding: utf-8 -*- """ *************************************************************************** ScriptAlgorithmProvider.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***************...
EditScriptAction import EditScriptAction from processing.gui.DeleteScriptAction import DeleteScriptAction from processing.gui.CreateNewScriptAction import CreateNewScriptAction from processing.script.ScriptUtils import ScriptUtils from processing.script.AddScriptFromFileAction import AddScriptFromFileAction from proces...
e__))[0] class ScriptAlgorithmProvider(AlgorithmProvider): def __init__(self): AlgorithmProvider.__init__(self) self.actions.extend([CreateNewScriptAction(self.tr('Create new script', 'ScriptAlgorithmProvider'), CreateNewScriptAction.SCRIPT_PYTHON), ...
larsks/cloud-init
cloudinit/distros/centos.py
Python
gpl-3.0
245
0
# This file is part of cloud-init. See LICENSE file for license information. from cloudinit.distros import rhel fr
om cloudinit import log as logging LOG = logging.getLogger(__name__
) class Distro(rhel.Distro): pass # vi: ts=4 expandtab
nathanbjenx/cairis
cairis/core/TemplateRequirement.py
Python
apache-2.0
1,446
0.011757
# 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...
ither express or implied. See the License for the # specific language governing permissions and limitations # under the License. __author__ = 'Shamal Faily' class TemplateRequirement: def __init__(self,reqId,reqName,assetName,reqType,reqDesc,reqRat,reqFC): s
elf.theId = reqId self.theName = reqName self.theAssetName = assetName self.theType = reqType self.theDescription= reqDesc self.theRationale = reqRat self.theFitCriterion = reqFC def id(self): return self.theId def name(self): return self.theName def asset(self): return self.theAssetName ...
jerryling315/ShadowsocksFork
playground/socketServer_client2.py
Python
apache-2.0
173
0.00578
__author__ = 'Exmof' import socket HOST = 'loca
lhost' PORT = 1033 s
oc = socket.socket() soc.connect((HOST, PORT)) data = soc.recv(1024) soc.close() print("Received", data)
cyx1231st/nova
nova/scheduler/rpcapi.py
Python
apache-2.0
6,665
0
# 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/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
c_obj'] msg_args['request_spec'] = spec_obj.to_legacy_request_spec_dict() msg_args['filter_properties' ] = spec_obj.to_legacy_filter_properties_dict() version = '4.0' cctxt = self.client.prepare(version=version) return cctxt.call(ctxt, 'select_des...
all schedulers cctxt = self.client.prepare(fanout=True, version='4.1') cctxt.cast(ctxt, 'update_aggregates', aggregates=aggregates) def delete_aggregate(self, ctxt, aggregate): # NOTE(sbauza): Yes, it's a fanout, we need to update all schedulers cctxt = self.client.prepare(fanout=Tr...
dstufft/warehouse
warehouse/config.py
Python
apache-2.0
18,226
0.000988
# 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 Li...
ment: settings.setdefault("enforce_https", False) settings.setdefault("pyramid.reload_assets", True) settings.setdefault("pyramid.reload_templates", True) settings.setdefault("pyramid.prevent_http_cache", True) settings.setdefault("debugtoolbar.hosts", ["0.0.0.0/0"]) sett...
".".join(["pyramid_debugtoolbar.panels", panel]) for panel in [ "versions.VersionDebugPanel", "
daverigby/kv_engine
scripts/cbnt_perfsuite_strip_results.py
Python
bsd-3-clause
2,943
0.001019
#!/usr/bin/env python2.7 """ Copyright 2018 Couchbase, 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 agree...
'test files are located') required_args.add_option('-p', '--prefix', action='store', type='string', dest='prefix', help='The prefix each of the test ' 'files start with') requir
ed_args.add_option('-i', '--ignore', dest='ignore', action='append', help='Section of string used to ignore results, ' 'eg \'.pct96\'') parser.add_option_group(required_args) (options, args) = parser.parse_args() # Check no arguments were passe...
pybee/seasnake
tests/test_enum.py
Python
bsd-3-clause
3,328
0
from __future__ import unicode_literals from tests.utils import ConverterTestCase class EnumTestCase(ConverterTestCase): def test_empty(self): self.assertGeneratedOutput( """ enum Bar { }; """, """ from enum import Enum ...
enum Bar { TOP = 37, RIGHT = 42, BOTTOM = 55, LEFT = 69 }; """, """ from enum import Enum class Bar(Enum): TOP = 37 RIGHT = 42 BOTTOM = 55 ...
ottokart/punctuator2
main.py
Python
mit
6,735
0.003563
# coding: utf-8 from __future__ import division, print_function from collections import OrderedDict from time import time import models import data import theano try: import cPickle except ImportError: import _pickle as cPickle import sys import os.path try: input = raw_input except NameError: pass ...
ield X, Y X_batch = [] Y_batch = [] if with_pauses: P_batch = [] if __name__ == "__main__": if len(s
ys.argv) > 1: model_name = sys.argv[1] else: sys.exit("'Model name' argument missing!") if len(sys.argv) > 2: num_hidden = int(sys.argv[2]) else: sys.exit("'Hidden layer size' argument missing!") if len(sys.argv) > 3: learning_rate = float(sys.argv[3]) else:...
mattilyra/gensim
gensim/corpora/bleicorpus.py
Python
lgpl-2.1
5,756
0.002085
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Сorpus in Blei's LDA-C format.""" from __future__ import with_statement from os import path import logging from gensim import uti...
`fname` and `fname.vocab`, where `fname.vocab` is the vocabulary file. Parameters ---------- fname : str Path to output file. corpus : iterable of iterable of (int, float) Input corpus in BoW format. id2word : dict of (str, str), optional Mapp...
THIS PARAMETER WILL BE IGNORED. Returns ------- list of int Offsets for each line in file (in bytes). """ if id2word is None: logger.info("no word id mapping provided; initializing from corpus") id2word = utils.dict_from_corpus(cor...
arth-co/shoop
shoop_tests/notify/test_notification.py
Python
agpl-3.0
3,453
0.001158
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.contrib.auth.models import AnonymousUser from django.core.urlres...
) n.save()
with pytest.raises(ValueError): n.set_reverse_url() assert n.url == reverse(**kwargs) finally: set_urlconf(None) def test_urlless_notification(): assert not Notification().url
avara1986/gozokia
gozokia/utils/functional.py
Python
mit
4,105
0.000487
import copy import operator empty = object() def unpickle_lazyobject(wrapped): """ Used to unpickle lazy objects. Just return its argument, which will be the wrapped object. """ return wrapped def new_method_proxy(func): def inner(self, *args): if self._wrapped is empty: ...
ect(object): """ A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the instantiation. If you don't need to do that, use SimpleLazyObject. """ # Avoid infinite rec
ursion when tracing __init__ (#19456). _wrapped = None def __init__(self): self._wrapped = empty __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value): if name == "_wrapped": # Assign to __dict__ to avoid infinite __setattr__ loops. self.__...
slavapestov/swift
utils/profdata_merge/server.py
Python
apache-2.0
2,159
0
# utils/profdata_merge/server.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.or...
self.connection.close() def kill_server(server): server.shutdown() # must be killed on another thread, or else deadlock thread.start_new_thread(kill_server, (self.server,)) else: # Add all the files to the queue for f in d...
self.server.file_queue.put(f) class ProfdataServer(SocketServer.TCPServer, object): def __init__(self, file_queue): super(ProfdataServer, self).__init__(SERVER_ADDRESS, ProfdataTCPHandler) self.file_queue = file_queue self.files_merged = set(...
rfedmi/reposdmpdos
davidmp/mainIndex.py
Python
gpl-2.0
385
0.01039
# coding: utf-8 ''' Create
d on 17/2/2015 @author: PC06 ''' from include import app from flask.templating import render_template from ec.edu.itsae.dao import PersonaDA
O @app.route("/") def login(): return render_template("login.html") @app.route("/persona") def index(): x=PersonaDAO.PersonaDAO().reportarPersona() print x return render_template("index.html", dato=x)
KenanBek/rslservices
app/payroll/migrations/0010_auto_20160803_1622.py
Python
gpl-3.0
1,650
0.003636
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('payroll', '0009_auto_20160722_1720'), ] operations = [ migrations.AddField( mod
el_name='netsalary', name='company_gross_spf', field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3), preserve_de
fault=True, ), migrations.AddField( model_name='netsalary', name='company_li_spf', field=models.DecimalField(default=0.0, max_digits=7, decimal_places=3), preserve_default=True, ), migrations.AddField( model_name='netsalary', ...
Dakno/compose
compose/config/validation.py
Python
apache-2.0
8,262
0.003631
import json import os from functools import wraps from docker.utils.ports import split_port from jsonschema import Draft4Validator from jsonschema import FormatChecker from jsonschema import ValidationError from .errors import ConfigurationError DOCKER_CONFIG_HINTS = { 'cpu_share': 'cpu_shares', 'add_host':...
th.".format(service_name)) elif 'image' not in error.instance and 'build' not in error.instance: required.appen
d( "Service '{}' has neither an image nor a build path " "specified. Exactly one must be provided.".format(service_name)) elif 'image' in error.instance and 'dockerfile' in error.instance: required.append( "Servi...
OCA/management-system
mgmtsystem_survey/models/__init__.py
Python
agpl-3.0
93
0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
. from . import survey_s
urvey
globality-corp/microcosm-dynamodb
microcosm_dynamodb/health.py
Python
apache-2.0
163
0.006135
""" Simple dynamodb health check. "
"" def check_health(graph): # TODO: Is there a basic service health check to perform here aki
n to 'SELECT 1;' ? pass
PhonologicalCorpusTools/SLP-Annotator
bin/position_hand.py
Python
gpl-3.0
8,676
0.012679
# Import statements import re import os from math import pi, radians import bpy """To Run in Blender: filename = 'C:\\Users\\mFry2\\Google Drive\\PCT\\position_hand.py' exec(compile(open(filename).read(), filename, 'exec')) """ # Function to translate handshape coding to degrees of rotation, adduction, flexion def t...
if code[1] == '<': handShapeParams['thumb.01.' + hand] = [0, 0, 0] if code[0] == 'O' and hand == 'L': handShapeParams['thumb.01.' + hand + '.001'] = [0, -70, -40] handShapeParams['thumb.02.' + hand] = [0, -70,
flexionDict[code[2]][0]] handShapeParams['thumb.03.' + hand] = [0, 0, flexionDict[code[3]][1]] elif code[0] == 'O' and hand == 'R': handShapeParams['thumb.01.' + hand + '.001'] = [0, 70, 40] handShapeParams['thumb.02.' + hand] = [0, -70, flexionDict[code[2]][0]] ...
gjlawran/ckanext-bcgov
ckanext/bcgov/scripts/export/run_exporter.py
Python
agpl-3.0
518
0.017375
# run using env as parameter: python run_exporter.py cad
id api_key import exporter #parse into data type files import dataset_export import update_datastore_content #enter key as an argument from sys import argv script, env, res_id, api_key = argv with open(env + '.csv', 'w') as f: csv_string = exporter.export(
'https://' + env + '.data.gov.bc.ca', 'columns.json') f.write(csv_string) if __name__ == '__main__': dataset_export.export_type(env) update_datastore_content.update_resource(env, res_id, api_key)
melviso/phycpp
beatle/app/resources/_folder.py
Python
gpl-2.0
5,664
0.052613
# -*- coding: utf-8 -*- _folder = [ "24 24 273 2", " c None", ". c #F6D021", "+ c #FACF0E", "@ c #FAD00F", "# c #FAD00E", "$ c #FACF0C", "% c #F5CD22", "& c #EEDA94", "* c #F2C32C", "= c #F5D463", "- c #F3D35E", "; c #F6D055", "> c #F3CE4A", ", c #F3CA36", "' c #F2E4C1", ") c #F7EED0", "! c #F7EAC7", ...
5 c #F2F1F4", "6 c #F3F1F5", "7 c #F5F2F6", "8 c #F4F1F4", "9 c #F0F0F0",
"0 c #ECF1F1", "a c #E5B157", "b c #EEC742", "c c #F1C616", "d c #F6CD16", "e c #F8D21A", "f c #FAD31B", "g c #F9D51F", "h c #FAD627", "i c #F9D62C", "j c #F9D731", "k c #F8D835", "l c #F9DA37", "m c #F9D939", "n c #F9DA39", "o c #F8D939", "p c #F7D939", "q c #F8D738", "r c #F6D33C", "s c #F4CF44",...
p0psicles/SickRage
sickbeard/helpers.py
Python
gpl-3.0
59,494
0.002588
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # URL: https://sickrage.github.io # Git: https://github.com/SickRage/SickRage.git # # This file is part of SickRage. # # SickRage 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...
: pass def makeDir(path): """ Make a directory on the filesystem :param path: directory to make :retur
n: True if success, False if failure """ if not ek(os.path.isdir, path): try: ek(os.makedirs, path) # do the library update for synoindex synoindex_notifier.addFolder(path) except OSError: return False return True def searchIndexerForShowID(...
tensorflow/privacy
tensorflow_privacy/privacy/analysis/privacy_accountant.py
Python
apache-2.0
4,041
0.004702
# Copyright 2021, The TensorFlow 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
cy.privacy.analysis import dp_event_builder class NeighboringRelation(enum.Enum): ADD_OR_REMOVE_ONE = 1 REPLACE_ONE = 2 class UnsupportedEventError(Exception): """Exception to raise if _compose is called on unsupported event type.""" class PrivacyAccountant(metaclass=abc.ABCMeta): """Abstract base class f...
ts.""" def __init__(self, neighboring_relation: NeighboringRelation): self._neighboring_relation = neighboring_relation self._ledger = dp_event_builder.DpEventBuilder() @property def neighboring_relation(self) -> NeighboringRelation: """The neighboring relation used by the accountant. The neigh...
pratikmallya/heat
heat/tests/test_sahara_job_binary.py
Python
apache-2.0
5,419
0
# # 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...
chobject(job_binary.JobBinary, 'client', return_value=self.client) def _create_resource(self, name, snippet, stack): jb = job_bina
ry.JobBinary(name, snippet, stack) value = mock.MagicMock(id='12345') self.client.job_binaries.create.return_value = value scheduler.TaskRunner(jb.create)() return jb def test_create(self): jb = self._create_resource('job-binary', self.rsrc_defn, self.stack) args = s...
rohitwaghchaure/erpnext_develop
erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
Python
gpl-3.0
24,694
0.026444
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe, erpnext import frappe.model from frappe.utils import cint, flt, today, nowdate, add_days import frappe.defaults from erp...
where voucher_type='Purchase Inv
oice' and voucher_no=%s order by account asc""", pi, as_dict=1) self.assertTrue(gl_entries) expected_values = dict((d[0], d) for d in [ ["_Test Payable - _TC", 0, 720], ["Stock Received But Not Billed - _TC", 500.0, 0], ["_Test Account Shipping Charges - _TC", 100.0, 0], ["_Test Account VAT - _TC", ...
DaanHoogland/cloudstack
systemvm/debian/opt/cloud/bin/cs/CsLoadBalancer.py
Python
apache-2.0
3,393
0.001768
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(w, -1) for w in x.split('\n')] file1.commit() file2 = CsFile(HAPROXY_CONF_P)
if not file2.compare(file1): CsHelper.copy(HAPROXY_CONF_T, HAPROXY_CONF_P) proc = CsProcess(['/run/haproxy.pid']) if not proc.find(): logging.debug("CsLoadBalancer:: will restart HAproxy!") CsHelper.service("haproxy", "restart") el...
ava-project/ava-website
website/core/settings/common/auth.py
Python
mit
608
0.006579
LOG
IN_URL = '/user/login' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRE
CT_URL = '/' AUTHENTICATION_BACKENDS = [ 'user.backend.AuthenticationBackend', 'user.backend.EmailBackend', ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.Min...
jorgecarleitao/xapian-haystack
tests/xapian_tests/tests/test_interface.py
Python
gpl-2.0
8,542
0.002927
from __future__ import unicode_literals import datetime from django.db.models import Q from django.test import TestCase from haystack import connections from haystack.inputs import AutoQuery from haystack.query import SearchQuerySet from ..models import Document from ..search_indexes import DocumentIndex from ..tes...
3, day=1)] summaries = ['This is a huge corrup\xe7\xe3o summary', 'This is a medium summary', 'This is a small summary'] for i in range(1, 13): doc = Document() doc.type_name = types_names[i % 3] doc.number = i * 2 ...
self.index = DocumentIndex() self.ui = connections['default'].get_unified_index() self.ui.build(indexes=[self.index]) self.backend = connections['default'].get_backend() self.backend.update(self.index, Document.objects.all()) self.queryset = SearchQuerySet() def te...
Synss/pyhard2
pyhard2/ctrlr/deltaelektronika.py
Python
mit
1,159
0
"""Graphical user interface to Delta-Elektronika SM-700 Series controllers.""" import sys import pyhard2.driver as drv import pyhard2.driver.virtual as virtual import pyhard2.driver.deltaelektronika as delta import pyhard2.ctrlr as ctrlr def createController(): """Initialize controller.""" config = ctrlr.Co...
) if config.virtual: driver = virtual.VirtualInstrument() iface = ctrlr.virtualInstrumentController(config, driver) else: driver = delta.Sm700Series(drv.Serial(config.port)) iface = ctrlr.Controller(config, driver) iface.addCommand(dri
ver.source.voltage, "Voltage", poll=True, log=True) iface.addCommand(driver.source.current, "Current", poll=True, log=True) iface.populate() return iface def main(argv): """Start controller.""" from PyQt4 import QtGui app = QtGui.QApplication(argv) app.lastWindowClosed.connect(app.quit...
mediawiki-utilities/python-mwdb
mwdb/schema.py
Python
mit
7,277
0.000275
""" A :class:`mwdb.Schema` represents a pool of connections to a database. New connections will be spawned as needed. A :class:`mwdb.Schema` can execite queries within the context of a :func:`mwdb.Schema.transaction` or directly via :func:`mwdb.Schema.execute`. .. autoclass:: mwdb.Schema :members: :member-or...
try: yield session session.commit() except: session.rollback() raise finally: session.close() def execute(self, clause, params=None, **kwargs): """ Executes a a query and returns the result. :Example: ...
import mwdb >>> enwiki = mwdb.Schema("mysql+pymysql://enwiki.labsdb/enwiki_p" + ... "?read_default_file=~/replica.my.cnf") >>> >>> result = enwiki.execute("SELECT * FROM user " + ... "WHERE user_id=:user_id", ...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/nbconvert/exporters/html.py
Python
bsd-2-clause
3,189
0.004078
"""HTML Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os from traitlets import default, Unicode from traitlets.config import Config from nbconvert.filters.highlight import Highlight2HTML from nbconvert.filters.markdown_mistune import IP...
/png',
'image/jpeg', 'text/plain' ] }, 'CSSHTMLHeaderPreprocessor':{ 'enabled':True }, 'HighlightMagicsPreprocessor': { 'enabled':True ...
QuantumElephant/horton
horton/io/xyz.py
Python
gpl-3.0
2,419
0.00124
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2017 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
".xyz".
data An IOData instance. Must contain ``coordinates`` and ``numbers``. May contain ``title``. ''' with open(filename, 'w') as f: print >> f, data.natom print >> f, getattr(data, 'title', 'Created with HORTON') for i in xrange(data.natom): n = pe...
nagyistoce/netzob
src/netzob/Import/TreeViews/TreeProcessesGenerator.py
Python
gpl-3.0
5,577
0.010946
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #|
| #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011 Georges Bossert and Frédéric Guihéry | #| This program is ...
ibute 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. | #| ...
KoderDojo/hackerrank
python/challenges/python/collections-default-dict.py
Python
mit
294
0
from collections impor
t defaultdict n, m = map(int, input().strip().split(' ')) a = defaultdict(list) b = [] for i in range(n): char = input().strip() a[char].append(str(i+1)) for j in range(m): b.append(input().s
trip()) for k in b: print(' '.join(a[k]) if k in a else -1)
ergodicbreak/evennia
evennia/contrib/tutorial_world/objects.py
Python
bsd-3-clause
40,255
0.003155
""" TutorialWorld - basic objects - Griatch 2011 This module holds all "dead" object definitions for the tutorial world. Object-commands and -cmdsets are also defined here, together with the object. Objects: TutorialObject Readable Climbable Obelisk LightSource CrumblingWall Weapon WeaponRack """ from future.utils...
------------------------------------------- # # Readable - an object that can be "read" # #--------
---------------------------------------------------- # # Read command # class CmdRead(Command): """ Usage: read [obj] Read some text of a readable object. """ key = "read" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ Implements the re...
cmos3511/cmos_linux
python/op/op_site/proj_checker/migrations/0002_proj_lock.py
Python
gpl-3.0
375
0
# Generated by D
jango 2.0 on 2017-12-14 08:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proj_checker', '0001_initial'), ] operations = [ migrations.AddField( model_name='proj', name='lock', field=models.Boolean...
se), ), ]
vencax/feincms-auth-app
socialauthapp/views.py
Python
bsd-2-clause
1,277
0.005482
''' Created on Feb 14, 2012 @author: vencax ''' from django.http import HttpResponseRedirect from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .profile import ProfileEditFor...
args) ctx['profileform'] = kwargs.pop('form') return ctx def form_valid(self, form): form.save() messages.info(self.request, _('user details updated')) return HttpResponseRedirect('/') def addInfoMessage(method, info): def addInfo(request, **kwargs):
retval = method(request, **kwargs) if isinstance(retval, HttpResponseRedirect): messages.info(request, info) return retval return addInfo
brendanzhao/ProjectEuler
src/P035.py
Python
mit
719
0.026426
import math def sieve(limit): primes_set = set() primes = [True] * limit primes[0] = primes[1] = False for (i, is_prime) in enumerate(primes): if is_prime: primes_set.add(i) for n in xrange(i*i, limit, i): primes[n] = False return primes_set def P035(): limit = 1000000 prim
e_set = sieve(limit) count = 0 for prime in prime_set: rotating_prime = prime rotation_count = int(math.log10(prime)) for _ in xrange(rotation_count): rotating_prime, digit = divmod(rotating_prime, 10) rotating_pr
ime += digit * 10 ** (rotation_count) if rotating_prime not in prime_set: count += 1 break return len(prime_set) - count print P035()
FHIBioGroup/fafoom-dev
examples/ga.py
Python
gpl-3.0
8,274
0.000121
import numpy as np import sys from fafoom import MoleculeDescription, Structure, selection, print_output,\ remover_dir, set_default, file2dict import fafoom.run_utilities as run_util # Decide for restart or a simple run. opt
= run_util.simple_or_restart() p_file = sys.argv[1] # Build a dictionary from two section of the parameter file. params = file2dict(p_file, ['GA settings', 'Run settings']) dict_default = {'energy_var': 0.001, 'selection': "roulette_wheel", 'fitness_sum_limit': 1.2, 'popsize': 10, 'prob...
'iter_limit_conv': 20, 'energy_diff_conv': 0.001} # Set defaults for parameters not defined in the parameter file. params = set_default(params, dict_default) energy_function = run_util.detect_energy_function(params) cnt_max = 200 population, blacklist = [], [] min_energy = [] if opt == "simple": mol ...
janastu/audio-tagger
servers/audioApp.py
Python
mit
3,589
0.000279
from flask import (Flask, session, render_template, request, redirect, url_for, make_response, Blueprint, current_app) import requests import json from datetime import datetime, timedelta from flask.ext.cors import CORS, cross_origin bp = Blueprint('audioTag', __name__) def create_app(blueprint=bp...
atetime.utcnow() return redirect(url_for('audioTag.index')) @bp.route('/admin', methods=['GET', 'POST']) def admin(): if request.method == 'POST': phone = request.form.get('usertel') print repr(phone) return render_template('admin.html') @bp.route('/upl
oad', methods=['GET', 'POST']) def upload(): return render_template('upload_url.html') if __name__ == '__main__': app = create_app() app.run(debug=app.config.get('DEBUG'), host=app.config.get('HOST'))
guiguiabloc/api-domogeek
Holiday.py
Python
gpl-2.0
6,861
0.055386
#!/usr/bin/python # -*- coding: utf-8 -*- """ Source : Les recettes Python de Tyrtamos http://python.jpvweb.com/mesrecettespython/doku.php?id=date_de_paques """ class jourf
erie: def datepaques(self,an): """Calcule la date de Pâques d'une année donnée an (=nombre entier)""" a=an//100 b=an%100 c=(3*(a+25))//4 d=(3*(a+25))%4 e=(8*(a+11))//25 f=(5*a+b)%19 g=(19*f+c-e)%30 h=(f+11*g)//319 j=(60*
(5-d)+b)//4 k=(60*(5-d)+b)%4 m=(2*j-k-g+h)%7 n=(g-h+m+114)//31 p=(g-h+m+114)%31 jour=p+1 mois=n return [jour, mois, an] def dateliste(self,c, sep='/'): """Transforme une date chaîne 'j/m/a' en une date liste [j,m,a]""" j, m, a = c.split(sep) return [int(j...
Fokko/incubator-airflow
airflow/hooks/mysql_hook.py
Python
apache-2.0
8,067
0.000992
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
ursor as ``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details. Note: For AWS IAM authentication, use iam in the extra connection parameters and set it to true. Leave the password field empty. This will use the "aws_default" connection to get the temporary token unless you override ...
mmit = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.schema = kwargs.pop("schema", None) self.connection = kwargs.pop("connection", None) def set_autocommit(self, conn, autocommit): """ MySql connection sets autocommit in a different w...
yhat/db.py
db/column.py
Python
bsd-2-clause
7,909
0.001897
from prettytable import PrettyTable import pandas as pd class Column(object): """ A Columns is an in-memory reference to a column in a particular table. You can use it to do some basic DB exploration and you can also use it to execute simple queries. """ def __init__(self, con, query_template...
nd("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def _str_ref_keys(self): keys = [] for col...
ys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def head(self, n=6): """ Returns first n values of your column as a DataFrame. This is executing...
pmghalvorsen/gramps_branch
gramps/plugins/tool/dateparserdisplaytest.py
Python
gpl-2.0
11,654
0.011327
# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Martin Hawlisch, Donald N. Allingham # Copyright (C) 2008 Brian G. Matherly # Copyright (C) 2010 Jakim Friant # # This program is free software; you can redistribute it and/or modify # it under the terms o...
d = Date() #d.set(Date.QUAL_NONE,Date.MOD_NONE, # Date.CAL_GREGORIAN,(44,7,1789,False),"Text comment") #dates.append( d) #d = Date() #d.set(Date.QUAL_NONE,Date.MOD_NONE, # Date.CAL_GREGORIAN,(4,77,1789,False),"Text comment") #d
ates.append( d) #d = Date() #d.set(Date.QUAL_NONE,Date.MOD_SPAN, # Date.CAL_GREGORIAN, # (4,7,1789,False,55,8,1876,False),"Text comment") #dates.append( d) #d = Date() #d.set(Date.QUAL_NONE,Date.MOD_SPAN, # Date.CAL_GREGORIAN, # ...
Winterflower/khmer
scripts/fastq-to-fasta.py
Python
bsd-3-clause
2,268
0.000441
#! /usr/bin/env python # # This file is part of khmer, https://github.com/dib-lab/khmer/, and is # Copyright (C) Michigan State University, 2009-2015. It is licensed under # the three-clause BSD license; see LICENSE. # Contact: khmer-project@idyll.org # # pylint: disable=invalid-name,missing-docstring """ Convert FAST...
a).', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('input_sequence', help='The name of the input' ' FASTQ sequence file.') parser.add_argument('-o', '--output', metavar="filename", help='The name of the output' ...
, action='store_true', help='Option to drop reads containing \'N\'s in ' + 'input_sequence file.') return parser def main(): args = get_parser().parse_args() print(('fastq from ', args.input_sequence), file=sys.stderr) n_count = 0 for n, record in e...
Anlim/decode-Django
Django-1.5.1/django/dispatch/saferef.py
Python
gpl-2.0
10,971
0.004523
""" "Safe weakrefs", originally from pyDispatcher. Provides a way to safely weakref any function, including bound methods (which aren't handled by the core weakref module). """ import traceback import weakref 弱引用 def safeRef(target, onDelete = None): """Return a *safe* weak reference to a callable target ta...
.weakSelf = weakref.ref(target.__self__, remove) self.weakFunc = weakref.ref(target.__func__,
remove) self.selfName = str(target.__self__) self.funcName = str(target.__func__.__name__) def calculateKey( cls, target ): 这不是一个类方法, 因为没有 self """Calculate the reference key for this reference Currently this is a two-tuple of the id()'s of the target object and the target...
XiKuuKy/Stack2
Stack2.py
Python
mit
1,481
0.00135
""" By Simon Harms. Copyright 2015 Simon Harms, MIT LICENSE Name: Stack2 Summary: Stack Version 2 """ class Stack: """ Python Stack V2 with view and change. """ def __init__(self): """ Initialize the Stack. """ self.__storage = [] def is_empty(self): """ ...
n. (use the newStacks getStack function.) """ self.__storage = new_stack def get_str
ing(self): """ Get a string of the stack. """ return "".join(self.__storage)
MarxMustermann/OfMiceAndMechs
src/itemFolder/plants/poisonBloom.py
Python
gpl-3.0
1,539
0.001949
import src class PoisonBloom(src.items.Item): """ a poisonous plant """ type = "PoisonBloom" name = "poison bloom" description = "Its spore sacks shriveled and are covered in green slime" usageInfo = """ You can eat it to die. """ walkable = True dead = False bolted = False ...
not self.contai
ner: self.dead = True character.die() if not self.dead: new = src.items.itemMap["PoisonBush"]() self.container.addItem(new,self.getPosition()) character.addMessage("you eat the poison bloom and die") self.destroy(generateScrap=False) def pickU...
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_12_01/aio/operations/_gallery_images_operations.py
Python
mit
25,178
0.004885
# 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 ...
rd 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 :keyword int polling_int...
for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either GalleryImage or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2019_12_01.models.GalleryImage] :raises: ~azure.core.ex...
cojacoo/testcases_echoRD
gen_test1110k.py
Python
gpl-3.0
431
0.044084
mcinif='mcini_gen1' runname='gen_test11
10k' mcpick='gen_test1.pickle' pathdir='/beegfs/work/ka_oj4748/echoRD' wdir='/beegfs/work/ka_oj4748/gen_tests' update_prec=0.01 update_mf='False' update_part=100 import sys sys.path.append(pathdir) import run_echoRD as rE rE.echoRD_job(mcinif=mcinif,mcpick=mcpick,runname=runname,wdir=wdir,pa
thdir=pathdir,update_prec=update_prec,update_mf=update_mf,update_part=update_part,hdf5pick=False)
jeffmahoney/supybot
plugins/Seen/plugin.py
Python
bsd-3-clause
13,345
0.001499
### # Copyright (c) 2002-2004, Jeremiah Fincher # Copyright (c) 2010-2011, 2013, James McCoy # 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 ...
a fake message') if not world.testing: for channel in irc.state.channels: irc.queueMsg(ircmsgs.who(channel)) irc.queueMsg(ircmsgs.names(channel)) def doPrivmsg(self, irc, msg): if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg): return
if irc.isChannel(msg.args[0]): channel = msg.args[0] said = ircmsgs.prettyPrint(msg) self.db.update(channel, msg.nick, said) self.anydb.update(channel, msg.nick, said) try: id = ircdb.users.getUserId(msg.prefix) self.db.upda...
frekenbok/frekenbok
frekenbot/apps.py
Python
mit
95
0
from dja
ngo.apps import AppConfig class TelegramBotConfig(AppConfig): name = 'frekenbot'
oudalab/phyllo
phyllo/extractors/tungerDB.py
Python
apache-2.0
3,235
0.007112
import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup, NavigableString from phyllo.phyllo_logger import logger import nltk from itertools import cycle nltk.download('punkt') from nltk import sent_tokenize # Case 1: Sections split by numbers (Roman or not) followed b...
ge TEXT,' ' link TEXT, documentType TEXT)') c.execute("DELETE FROM texts WHERE author='Augustin Tünger'") for url in textsURL: openurl = urllib.request.urlopen(url) textsoup = BeautifulSoup(openurl, 'html5lib') title = 'FACETIAE LATINAE ET GERMANICAE' ...
, author, date, url) logger.info("Program runs successfully.") if __name__ == '__main__': main()
FreshXOpenSource/wallaby-base
wallaby/pf/peer/ping.py
Python
bsd-2-clause
353
0.008499
# Copyrig
ht (c) by it's authors. # Some rights reserved. See LICENSE, AUTHORS. from peer import * class Ping(Peer): Ping = Pillow.InOut def __init__(self, *args): Peer.
__init__(self, *args) self._catch(Ping.In.Ping, self.message) def message(self, pillow, feathers): self._throw(Ping.Out.Ping, int(feathers)+1);
jmvrbanac/barbican
barbican/common/resources.py
Python
apache-2.0
1,430
0
# Copyright (c) 2013-2014 Rackspace, 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 ...
ONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """ Shared business logic. """ from barbican.common import utils from barbican.model import models LOG = utils.getLogger(__name__) def get_or_create_project(project_i...
it does not exist. :param project_id: The external-to-Barbican ID for this project. :param project_repo: Project repository. :return: Project model instance """ project = project_repo.find_by_external_project_id(project_id, suppress_exception=T...
lightmare/mapnik
scons/scons-local-4.1.0/SCons/Tool/rpm.py
Python
lgpl-2.1
4,494
0.007121
"""SCons.Tool.rpm Tool-specific initialization for rpm. 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. The rpm tool calls the rpmbuild command. The first and only argument should a tar.gz consisting of the sourc...
: # create a temporary rpm build root. tmpdir = os.path.join(os.path.dirname(target[0].get_abspath()), 'rpmtemp') if os.path.exists(tmpdir):
shutil.rmtree(tmpdir) # now create the mandatory rpm directory structure. for d in ['RPMS', 'SRPMS', 'SPECS', 'BUILD']: os.makedirs(os.path.join(tmpdir, d)) # set the topdir as an rpmflag. env.Prepend(RPMFLAGS = '--define \'_topdir %s\'' % tmpdir) # now call rpmbuild to create the rpm ...
Astoriane/jCrunchyroll
lib/crunchy-xml-decoder/crunchyDec.py
Python
lgpl-3.0
4,061
0.02167
import gzip, lxml, math, sha, zlib from Base64Decoder import Base64Decoder from binascii import hexlify, unhexlify from bs4 import BeautifulSoup from Common import Common from crypto.cipher.aes_cbc import AES_CBC from crypto.cipher.base import noPadding, padWithPadLen class crunchyDec: def __init__(self): pass de...
"\n" for event in eventlist: events += "Dialogue: 0,"+event['start']+","+event['end']+","+event['style']+","+event['name']+","+event['margin_l']+","+event['margin_r']+","+event['margin_v']+","+event['effect']+","+event['text']+"\n" formattedSubs = header+styles+events return formattedSubs # ---- CRYPTO --...
low: Do some black magic eq1 = int(int(math.floor(math.sqrt(6.9) * math.pow(2, 25))) ^ mediaid) eq2 = int(math.floor(math.sqrt(6.9) * math.pow(2, 25))) eq3 = (mediaid ^ eq2) ^ (mediaid ^ eq2) >> 3 ^ eq1 * 32 # Below: Creates a 160-bit SHA1 hash shaHash = sha.new(self.createString([20, 97, 1, 2]) + str(eq3)) ...
TariqEE/PrivEx
S2/S2-netified/noise.py
Python
bsd-3-clause
345
0.008696
import numpy import random impor
t math from exit_weight import * from privexUtils import resolution #def Noise(sensitivity, epsilon, delta, fingerprint, sigma): def Noise(sigma, fingerprint, sum_of_sq, p_exit): sigma_i = p_exit*sigma/math.sqrt(sum_of_sq) random_sample = random.gauss(0,sigma_i) return random_sample #
return 0
torgeirl/tradingpost-beepboop
bot/slack_bot.py
Python
mit
2,852
0.002805
import time import logging import traceback from slack_clients import SlackClients from messenger import Messenger from event_handler import RtmEventHandler logger = logging.getLogger(__name__) def spawn_bot(): return SlackBot() class SlackBot(object): def __init__(self, token=None): """Creates Sl...
Bot User token (for development token set in env)
""" self.last_ping = 0 self.keep_running = True if token is not None: self.clients = SlackClients(token) def start(self, resource): """Creates Slack Web and RTM clients for the given Resource using the provided API tokens and configuration, then connects w...
mdg/pygrate
pygration/db.py
Python
apache-2.0
2,877
0.012165
import sqlalchemy from sqlalchemy import Column, Integer, String from sqlalchemy.orm import mapper, sessionmaker import subprocess class PygrationState(object): '''Python object representing the state table''' def __init__(self, migration=None, step_id=None, step_name=None): self.migration = migration ...
ing_dict = {}): self._binary = binary self._args = [arg.format(filename="{filename}", **formatting_dict) for arg in args] def __call__(self, filename): args = [arg.format(filename=filename) for arg in self._args] print self._binary, args subprocess.check_call([self._bina...
a SQLAlchemy engine. Returns an open session. """ if url is None and drivername is None: raise Exception("Either a url or a driver name is required to open a db connection") if url is None: url = sqlalchemy.engine.url.URL(drivername = drivername, ...
tao12345666333/tornado-zh
tornado/simple_httpclient.py
Python
mit
23,983
0.000375
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, with_statement from tornado.escape import utf8, _unicode from tornado import gen from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy from tornado import httputil from tornado.http1connection...
import urlparse # py2 except ImportError: import urllib.parse as urlparse # py3 try: import ssl except ImportError: # ssl is not available on Google App Engine. ssl = None try: import certifi except ImportE
rror: certifi = None def _default_ca_certs(): if certifi is None: raise Exception("The 'certifi' package is required to use https " "in simple_httpclient") return certifi.where() class SimpleAsyncHTTPClient(AsyncHTTPClient): """Non-blocking HTTP client with no externa...
luv/webdav_tests
test_suite_09_limits.py
Python
gpl-3.0
3,365
0.01367
import subprocess import cfg import util import shutil import os import time import tempfile import easywebdav import filecmp from nose.tools import with_setup from nose.tools import assert_raises # # NOTE: following tests have been implemented using easywebdav instead of davfs2 # pjoin
= os.path.join assert sub
process # pyflakes assert cfg # pyflakes @with_setup(util.setup_func, util.teardown_func) def test_case_01_deep(): client = util.connect_easywebdav() rel_dir_path = "x/" * 300 rel_file_path = pjoin(rel_dir_path,"test_file") dir_path_dest = pjoin(cfg.webdav_backend_directory, rel_dir_path) file_pa...
redhat-openstack/neutron
neutron/plugins/linuxbridge/agent/arp_protect.py
Python
apache-2.0
5,344
0
# Copyright (c) 2015 Mirantis, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
in port_details['allowed_address_pairs']) addresses = set
(ip for ip in addresses if netaddr.IPNetwork(ip).version == 4) if any(netaddr.IPNetwork(ip).prefixlen == 0 for ip in addresses): # don't try to install protection because a /0 prefix allows any # address anyway and the ARP_SPA can only match on /1 or more. return ins...
CoRfr/testman4trac
tracgenericworkflow/trunk/setup.py
Python
gpl-3.0
2,209
0.010865
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2012 Roberto Longobardi # # This file is part of the Test Manager plugin for Trac. # # The Test Manager plugin for Trac 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 Fo...
Test Cases, organize them in catalogs and track their execution status and outcome. This module provides a generic workflow engine working on any Trac Resource.', keywords='trac plugi
n test case management workflow engine resource project quality assurance statistics stats charts charting graph', entry_points = {'trac.plugins': ['tracgenericworkflow = tracgenericworkflow']}, dependency_links=['http://svn.edgewall.org/repos/genshi/trunk#egg=Genshi-dev', 'http://trac-hacks.org/wiki/TestManage...
0nkery/django-websocket-redis3
ws4redis/exceptions.py
Python
mit
517
0
from socket import error as socket_error from django.http import BadHeaderError class WebSocketError(socket_error): """ Raised when an active websocket encounters a problem. """ class FrameTooLargeException(WebSocketError): """ Raised if a received
frame is too large
. """ class HandshakeError(BadHeaderError): """ Raised if an error occurs during protocol handshake. """ class UpgradeRequiredError(HandshakeError): """ Raised if protocol must be upgraded. """
mvidalgarcia/indico
indico/core/db/sqlalchemy/review_comments.py
Python
mit
2,710
0.000738
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy.ext.declarative import declared_attr from indico...
ed_attr def modified_by(cls): return db.relations
hip( 'User', lazy=True, foreign_keys=cls.modified_by_id, backref=db.backref( cls.user_modified_backref_name, primaryjoin='({0}.modified_by_id == User.id) & ~{0}.is_deleted'.format(cls.__name__), lazy='dynamic' ) ...
rochefort-lab/fissa
fissa/tests/test_readimagejrois.py
Python
gpl-3.0
5,999
0.0015
""" Tests for readimagejrois.py. """ import json import os import sys import unittest import numpy as np from .. import readimagejrois from .base_test import BaseTestCase class TestReadImageJRois(BaseTestCase): """readimagejrois testing class.""" def __init__(self, *args, **kw): super(TestReadImag...
ta_dir, name + ".roi")) def test_ellipse_right_offscreen(self): self.check_mask("ellipse-right-offscreen") def test_ellipse_bottom_offscreen(self): self.check_mask("ellipse-bottom-offscreen") def test_ellipse_tiny(self): # ROI which is too small to cover a single pixel nam...
dir, name + ".roi"))
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/copy.py
Python
unlicense
11,818
0.002623
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: copy.py """Generic (shallow and deep) copying operations. Interface summary: import copy x = copy.copy(y) # make a shallow ...
x.cop
y() if PyStringMap is not None: d[PyStringMap] = _copy_with_copy_method def _copy_inst(x): if hasattr(x, '__copy__'): return x.__copy__() if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() y = x.__class__(*args) else: y = _EmptyClass() y.__class__ = x...
kennethreitz/pipenv
pipenv/vendor/passa/cli/install.py
Python
mit
598
0.003344
# -*- coding=utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from ..actions.install import install from ._base import BaseCommand from .options import dev, no_check, no_clean class Command(BaseCommand): name = "install" desc
ription = "Generate Pipfile.lock to synchronize the environment." arguments = [no_check, dev, no_clean] def run(self, options): return install(project=options.project, che
ck=options.check, dev=options.dev, clean=options.clean) if __name__ == "__main__": Command.run_parser()
dathath/IJCAI_2017_SD
proteus/svm_classifier.py
Python
bsd-2-clause
1,509
0.095427
from oct2py import octave from cvxopt import matrix, solvers from cvxpy import * import numpy as np def svm_classifier(X, y,
mode): [num_sample,d]=X.shape mode_control=np.ones((num_sample,1)) for i in range(num_sample): if(mode==1): if(y[i]==-1): mode_control[i]=0; if(mode==2): if(y[i]==1): mode_control[i]=0; if(mode==4): mode_control[i]=0; #[G,bet
a]= octave.PWL_feature(X, M, beta_type); A=np.array([[]]) for i in range(num_sample): s=np.zeros((1,num_sample)); s[0,i]=1; temp_1=y[i]*np.concatenate((np.array([[1]]),[X[i,:]]),axis=1) temp_a=-np.concatenate((temp_1,s),axis=1) if(i==0): A=temp_a else: A=np.concatenate((A,temp_a),axis=0) dum_conca...
sclamons/murraylab_tools
examples/biotektests.py
Python
mit
999
0.029029
import murraylab_tools.biotek as mt_biotek import os gitexamplepath = "C:\\Users\\Andrey\\Documents\\GitHub\\"+\ "murraylab_tools\\examples\\biotek_examples\\" data_filename = gitexamplepath+\ "180515_big384wellplate.csv" supplementary_filename = gitexamplepath+\ "supp_in...
alse) import pandas as pd tidy_filename
= gitexamplepath+"180515_big384wellplate_tidy.csv" df = pd.read_csv(tidy_filename) #df.head() #df.head() #gdf = df.groupby(["Channel", "Gain", "Well"]) #gdf.head() #df[df.Channel == "GFP"].head() normdf = mt_biotek.normalize(df,norm_channel= "OD") #normdf[normdf.Gain==100].head() end_df = mt_biotek.window_averages(norm...
google/makani
config/m600/control/trans_in.py
Python
apache-2.0
13,367
0.001795
# Copyright 2020 Makani Technologies 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...
Maximum expected lift coefficient [#]. 'CL_max': CL_max, 'max_aero_climb_angle': max_aero_climb_angle_cmd, # Reference length [m] for the lateral tracking loop. #
# The desired lateral tracking bandwidth is given by # airspeed / (2.0 * pi * lateral_tracking_ref_length). 'lateral_tracking_ref_length': 150.0, # Maximum bandwidth [Hz] for the lateral tracking loop. 'max_lateral_tracking_freq_hz': 0.035, # Damping ratio [#] f...
liyao001/BioQueue
worker/ml_collector.py
Python
apache-2.0
3,685
0.002171
#!/usr/local/bin python from __future__ import print_function import psutil import time import getopt import sys import django_initial from QueueDB.models import Training vrt_mem_list = [] mem_list = [] cpu_list = [] read_list = [] write_list = [] def get_mem(pid): running_process = psutil.Process(pid) if ru...
ss_id)
total_cpu_usage = get_cpu(process_id) children = process_info.children() for child in children: t1, t2 = get_mem(child.pid) total_memory_usage += t1 vrt += t2 ...
saltstack/salt
salt/client/ssh/client.py
Python
apache-2.0
8,181
0.000733
import copy import logging import os import random import salt.client.ssh import salt.config import salt.syspaths import salt.utils.args from salt.exceptions import SaltClientError log = logging.getLogger(__name__) class SSHClient: """ Create a client object for executing routines via the salt-ssh backend ...
break return self.cmd_iter( f_tgt, fun, arg, timeout, tgt_type="list", ret=ret, kwarg=kwarg, **kwargs ) def destroy(self):
""" API compatibility method with salt.client.LocalClient """ def __enter__(self): """ API compatibility method with salt.client.LocalClient """ return self def __exit__(self, *args): """ API compatibility method with salt.client.LocalClient ...
mosra/m.css
documentation/test_python/inspect_recursive/inspect_recursive/second.py
Python
mit
358
0
"""Second module, imported as inspect_recursive.a, with no contents""" i
mport inspect_recursive.first as a import sys if sys.version_info >= (3, 7): # For some reason 3.6 says second doesn't exist yet. I get that, it's a
# cyclic reference, but that works in 3.7. import inspect_recursive.second as b from inspect_recursive import Foo as Bar
CVL-dev/cvl-fabric-launcher
LauncherOptionsDialog.py
Python
gpl-3.0
4,921
0.013818
import wx import sys import IconPys.MASSIVElogoTransparent64x64 class LauncherOptionsDialog(wx.Dialog): def __init__(self, parent, message, title, ButtonLabels=['OK'],onHelp=None,helpEmailAddress="help@massive.org.au",**kw): wx.Dialog.__init__(self, parent, style=wx.DEFAULT_DIALOG_STYLE, **kw) ...
taticBitmap(self.dialogPanel, wx.ID_ANY, iconAsBitmap, pos=(25,15), size=(64,64)) smallFont = wx.Syst
emSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if sys.platform.startswith("darwin"): smallFont.SetPointSize(11) self.messagePanel = wx.Panel(self.dialogPanel) if sys.platform.startswith("darwin"): self.messagePanel.SetSizer(wx.FlexGridSizer(cols=1,rows=2)) self....
jxta/cc
vendor/boto/boto/ec2/keypair.py
Python
apache-2.0
4,210
0.0019
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
e extension. If a file of that name already exists in the directory, an exception will be raised and the old file will not be overwritten. :rtype: bool :return: True if successful. """ ...
file_path): raise BotoClientError('%s already exists, it will not be overwritten' % file_path) fp = open(file_path, 'wb') fp.write(self.material) fp.close() return True else: raise BotoClientError('KeyPair contains no material') de...
j-carl/ansible
lib/ansible/parsing/mod_args.py
Python
gpl-3.0
13,925
0.002226
# (c) 2014 Michael DeHaan, <michael@ansible.com> # # This file is part of Ansible # # Ansible 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 ve...
the module name is # yet. If we have already figured it out, it's a 'new style' invocation. # ot
herwise, it's not if action is not None: args = self._normalize_new_style_args(thing, action) else: (action, args) = self._normalize_old_style_args(thing) # this can occasionally happen, simplify if args and 'args' in args: tmp_args = arg...
mfrasca/bauble.classic
bauble/meta.py
Python
gpl-2.0
2,702
0
# -*- coding: utf-8 -*- # # Copyright (c) 2005,2006,2007,2008,2009 Brett Adams <brett@belizebotanic.org> # Copyright (c) 2012-2015 Mario Frasca <mario@anche.no> # # This file is part of bauble.classic. # # bauble.classic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pub...
ense as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # bauble.classic 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 # along with bauble.classic. If not, see <http://www.gnu.org/licenses/>. # # meta.py # from sqlalchemy import Unicode, UnicodeText, Column import bauble.db as db import bauble.utils as utils VERSION_KEY = u'version' CREATED_KEY = u'created' REGISTRY_KEY = u'registry' # date format str...
koditr/xbmc-tr-team-turkish-addons
plugin.video.hintfilmkeyfi/xbmctools.py
Python
gpl-2.0
3,303
0.038147
# -*- coding: iso8859-9 -*- import urllib2,urllib,re,HTMLParser,cookielib import sys,os,base64,time import xbmc, xbmcgui, xbmcaddon, xbmcplugin import urlresolver,json __settings__ = xbmcaddon.Addon(id="plugin.video.hintfilmkeyfi") #---------------------------------------------------------------------- xbmcPlayer = xb...
l = source.resolve() addLink(name,url,'') playlist_yap(playList,name,url) xbmcPlayer.play(playList) def playlist_yap(playList,name,url): listitem = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnail
Image="") listitem.setInfo('video', {'name': name } ) playList.add(url,listitem=listitem) return playList def yeni4(name,url): xbmcPlayer = xbmc.Player() playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playList.clear() addLink(name,url,'') listitem = xbm...
aubreyrjones/libesp
scons_local/scons-local-2.3.0/SCons/Tool/f77.py
Python
mit
2,068
0.003385
"""engine.SCons.Tool.f77 Tool-specific initialization for the generic Posix 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, 2002, 2003, 2004, 2005, 2006, 2007, 2...
he # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, mer
ge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # T...
akrherz/iem
htdocs/plotting/auto/scripts/p18.py
Python
mit
7,957
0
"""Time series plot.""" import datetime import pytz import psycopg2.extras import numpy as np import pandas as pd from pyiem.plot import figure_axes from pyiem.util import get_autoplot_context, get_sqlalchemy_conn, get_dbconn from pyiem.exceptions import NoDataFound MDICT = dict( [ ("tmpf", "Air Temperatu...
o"][now.strftime("%m%d")]["high"], ] ) now += oneday j = {} j["title"] = dict( text=("[%s] %s Time Series") % (ctx["station"], ctx["_nt"].sts[ctx["station"]]["name"])
) j["xAxis"] = dict(type="datetime") j["yAxis"] = dict( title=dict(text="%s %s" % (MDICT[ctx["var"]], UNITS[ctx["var"]])) ) j["tooltip"] = { "crosshairs": True, "shared": True, "valueSuffix": " %s" % (UNITS[ctx["var"]],), } j["legend"] = {} j["time"] = {"useU...
Nextdoor/rightscale_rightlink10_rightscripts
tasks.py
Python
mit
6,904
0.000579
import sys import os from os import walk, chdir import fnmatch from invoke import run, task, Collection from colorama import init, Fore import yaml import numpy PEP8_IGNORE = 'E402,E266,F841' init() # These things don't pass syntax/lint checks and are external deps. EXCLUDE_DIRS = ['nextdoor/lib/python/kingpin', ...
be nice if librarian could be leveraged... """ newcwd = sys.path[0] if '' != newcwd: # I'm not sure this is absolutely necessary but to be careful... print(Fore.GREEN + "Changing cwd to {}".format(newcwd)) chdi
r(sys.path[0]) else: print(Fore.Red + "I am very confused about our sys.path[0] of ''!") sys.exit(-1) deps = {} with open('external_dependencies.yml') as deps: try: deps = yaml.load(deps) except yaml.YAMLError as e: print(Fore.RED + str(e)) ...
zwChan/VATEC
~/eb-virt/Lib/site-packages/pip/_vendor/requests/packages/urllib3/poolmanager.py
Python
apache-2.0
9,614
0.000312
from __future__ import absolute_import import logging try: # Python 3 from urllib.parse import urljoin except ImportError: from urlparse import urljoin from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool from .connectionpool import port_by_schem...
d, url, redirect=True, **kw): """ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:...
t, port=u.port, scheme=u.scheme) kw['assert_same_host'] = False kw['redirect'] = False if 'headers' not in kw: kw['headers'] = self.headers if self.proxy is not None and u.scheme == "http": response = conn.urlopen(method, url, **kw) else: res...
vertexproject/synapse
synapse/models/proj.py
Python
apache-2.0
6,668
0.00165
import synapse.common as s_common import synapse.lib.module as s_module prioenums = ( (0, 'none'), (10, 'lowest'), (20, 'low'), (30, 'medium'), (40, 'high'), (50, 'highest'), ) statusenums = ( (0, 'new'), (10, 'in validation'), (20, 'in backlog'), (30, 'in sprint'), (40, '...
self): return ( ('proj', { 'types': ( ('proj:epic', ('guid', {}), {}), ('proj:ticket', ('guid', {}), {}), ('proj:sprint', ('guid', {}), {}), ('proj:comment
', ('guid', {}), {}), ('proj:project', ('guid', {}), {}), ('proj:attachment', ('guid', {}), {}), ), 'forms': ( ('proj:project', {}, ( ('name', ('str', {'lower': True, 'strip': True, 'onespace': True}), ...
itahsieh/sparx-alpha
preprocessor/presparx/Disk_cyl2d/model.py
Python
gpl-3.0
5,481
0.021164
#################################################### # The model of disk and envelope (Keto&Zhang 2010) # #################################################### # Model Type : Function / Constant / TABLE / ZEUS ModelType = 'Function' # Molecule molec = 'hco+' # CMB temperature (Kelvin, outer B.C.) T_cmb = 2.73 # inn...
rameter #parameters from Keto&Zhang rho_e0 = 7.9e4 *1e6 # Envelope density at Rd (m^-3) Rd = 6900./206260. # AU to pc Ap = 5.1 Mt = 10.7 # stellar mass (Msun) Rt = 26.*0.0046491/206260 p = -1 BT = 15.0 vk = 1.2 # Keplerian velocity (km/s) rho_d0 = Ap*rho_e0 H0 = 0.01*Rt Tt = 30000. # unit converter km2m=1e3 pc2m=30.8...
olecular_mass*pc2m**2*km2m) # mass accretion rate (kg/s) G = 4.302e-3 # gravitational constant (pc Msun^-1 (km/s)^2) sigma = 5.67037321e-8 # Stefan-Boltzmann constant (W m^-2 K^-4) pp = 0.0 qq = 0.0 def CubicEq(x): global pp,qq return x*x*x + pp*x + qq from scipy.optimize import brentq class model: ...
hankcs/HanLP
hanlp/metrics/chunking/sequence_labeling.py
Python
apache-2.0
14,144
0.002828
# MIT License # # Copyright (c) 2018 chakki # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi...
ns import defaultdict import numpy as np def iobes_to
_span(words, tags): delimiter = ' ' if all([len(w) == 1 for w in words]): delimiter = '' # might be Chinese entities = [] for tag, start, end in get_entities(tags): entities.append((delimiter.join(words[start:end]), tag, start, end)) yield entities def get_entities(seq, suffix=Fal...
vpramo/contrail-controller
src/config/api-server/vnc_perms.py
Python
apache-2.0
3,590
0.000279
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # import sys from cfgm_common import jsonutils as json import string from provision_defaults import * from cfgm_common.exceptions import * from pysandesh.gen_py.sandesh.ttypes import SandeshLevel class VncPermissions(object): mode_str = {PERMS_R: ...
']['group_access'] <<
3 | \ id_perms['permissions']['other_access'] # check perms mask = 0 if user == owner: mask |= 0700 if group in roles: mask |= 0070 if mask == 0: # neither user nor group mask = 07 mode_mask = mode | mode << 3 | mode <<...
paddycarey/beardo-control
app/run-prospector.py
Python
mit
715
0.001399
#!/usr/bin/env python # -*- coding: utf-8 -*- """Prospector runner for beardo-control """ # stdlib imports import sys # third-party imports from prospector import run # this looks like an unused import, but we're only using it to do some path # manipulat
ion on import so you can safely ignore it (even
though your linter # may complain) import appengine_config # setup our appengine environment so we can import the libs we need for our tests, # we need to do this first so we can import the stubs from testbed from nacelle.test.environ import setup_environ setup_environ() if __name__ == '__main__': sys.argv = [s...
RevelSystems/revel-bootstrap
manage.py
Python
mit
476
0.002101
""" usage: manage.py [--help] <command> [<args>...] The most commonly used git commands are: syncdb Creates db models dropdb Drop db models """ from database import init_db from docopt import docopt def main(): args = docopt(__doc__, options_first=True) if args['<command>'] == 'syncdb
': init_db() else: exit("%r is not a manage.py command. See 'mana
ge.py help'." % args['<command>']) if __name__ == '__main__': main()
hkff/AccLab
pyAAL/AALMetaModel.py
Python
gpl-3.0
66,923
0.002944
""" AALMetaModel Copyright (C) 2014 Walid Benghabrit 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 distribut...
r_Id '(' value* ')']* Clause ::= CLAUSE Id '(' [Usage] [Audit Rectification] ')' Usage ::= ActionExp Audit ::= AUDITING Usage Rectification ::= IF_VIOLATED_THEN Usage ActionExp ::= Action |
NOT ActionExp | Modality ActionExp | Condition | ActionExp (AND|OR|ONLYWHEN|UNTIL|UNLESS) ActionExp | Author | Quant* | IF '(' ActionExp ')' THEN '{' ActionExp '}' Exp ::= Variable | Constant | Variable.Attribute Condition ::= [NOT] Exp | Exp ['==' | '!='] ...
hfp/libxsmm
samples/deeplearning/sparse_training/fairseq/fairseq/modules/fairseq_dropout.py
Python
bsd-3-clause
1,687
0.000593
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from typing import List, Optional import torch.nn as nn import torch.nn.functional as F logger = logging.getLogger(__name__)...
not set'.format(name) ) elif ( retain_dropout_modules is None # if None, apply to all modules or self.module_name in retain_dropout_modules
): logger.info( 'Enabling dropout during inference for module: {}'.format(name) ) self.apply_during_inference = True else: logger.info('Disabling dropout for module: {}'.format(name))
gustavofoa/pympm
apps/mpm/views/view_starratings.py
Python
apache-2.0
1,191
0.028547
from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404, render from django.http import HttpResponse, JsonResponse from django.views.decorators.cache import cache_control, cache_page from ..models import Musica import re @csrf_exempt def starratings_ajax(request): id = re...
"legend"] = musica.get_legend() return JsonResponse(jsonObj) return HttpResponse(str("0")) @cache_control(max_age = 60 * 60) @cache_page(60 * 5)#5 minutes def stars(request): musicas = Musica.objects.all() jsonObj = {} for musica in musicas: jsonObj[musica.slug] = {"r": musica.ratin
g if musica.rating else 0, "v":musica.votes if musica.votes else 0} return JsonResponse(jsonObj)
minddistrict/doublespeak
src/doublespeak/message.py
Python
bsd-3-clause
6,920
0.000578
"""Inspired by http://trac.edgewall.org/attachment/ticket/6353/babel-l10n-js.diff#L590 """ import os import glob import distutils import json from babel._compat import StringIO from babel._compat import string_types from babel.messages import frontend as babel from babel.messages.pofile import read_po import gettext ...
utils.log.error( 'error: %s:%d: %s', po_file, message.lineno, error) # Don't leak private information to the frontend. messages = {'': [None, '']} for message in list(cata
log): # See comment above about not leaking private information to the # frontend. if message.id == '': continue if not self.use_fuzzy and message.fuzzy: continue # If you need pluralization here, mak...
goffersoft/common-utils-python
experimental/com/goffersoft/raw/rawhdr.py
Python
gpl-2.0
543
0.001842
#! /usr/bin/python from com.goffersoft.utils.utils import readonly """ This Module Contains header types specific to raw me
ssaging protocol """ class _RawMsgHdrType(type): """Raw Message Header Names""" CONTENT = readonly('Content') CONTENT_TYPE = readonly('Content-Type') FROM = readonly('From') TO = readonly('To') REQ_ID = readonly('Req-Id') RESP_ID = readonly('Resp-Id') """Raw Message Header Type""" RawMsgH...
s