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
georgemarshall/django-cryptography
tests/fields/test_pickle.py
Python
bsd-3-clause
3,763
0.000531
import json import pickle from django.core import exceptions, serializers from django.db import IntegrityError from django.test import TestCase from django.utils import timezone from django_cryptography.fields import PickledField from .models import PickledModel, NullablePickledModel class TestSaveLoad(TestCase): ...
name, path, args, kwargs = field.deconstruct() self.assertEqual
("django_cryptography.fields.PickledField", path) self.assertEqual(args, []) self.assertEqual(kwargs, {}) class TestSerialization(TestCase): test_data = ( # Python 3.4 '[{"fields": {"field": "gANdcQAoSwFLAk5lLg=="}, "model": "fields.pickledmodel", "pk": null}]' ) if pickle.HIGH...
OBIGOGIT/etch
binding-python/runtime/src/main/python/etch/binding/util/URLSerializer.py
Python
apache-2.0
2,249
0.004891
""" # 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...
ld import * from ..msg.ImportExportHelper import * from ..msg.StructValue import * from ..msg.Type import * from ..msg.ValueFactory import * from ..support.Class2TypeMap import * from ..support.Validator_string import * from ...util.URL import * class URLSerializer(ImportExportHelper): """ An etch serializer f...
@classmethod def init(cls, typ, class2type): """ Defines custom fields in the value factory so that the importer can find them. @param typ @param class2type """ field = typ.getField(cls.FIELD_NAME) class2type.put(URL, typ) typ.setCompo...
kdart/pycopia3
QA/pycopia/QA/db/tui/eventloop.py
Python
apache-2.0
2,784
0.000359
#!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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...
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 permissions and # limitations under the License. """ An urwid event loop that integrates with the Pycopia event loop and ti...
mjames-upc/python-awips
dynamicserialize/dstypes/com/raytheon/uf/common/management/response/diagnostic/__init__.py
Python
bsd-3-clause
327
0.003058
## ## # File auto-generated by PythonFileGenerator __all__ =
[ 'ClusterMembersResponse', 'ContextsResponse', 'StatusResponse' ]
from .ClusterMembersResponse import ClusterMembersResponse from .ContextsResponse import ContextsResponse from .StatusResponse import StatusResponse
swayf/pyLoad
module/plugins/hoster/MegavideoCom.py
Python
agpl-3.0
3,767
0.007966
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from time import time from module.plugins.Hoster import Hoster from module.unescape import unescape class MegavideoCom(Hoster): __name__ = "MegavideoCom" __type__ = "hoster" __pattern__ = r"http://(www\.)?megavideo.com/\?v=.*" __version__ = "0.2"...
self.download_html() # get id id = re.search("previewplayer/\\?v=(.*?)&width", self.html).group(1) # check for hd link and return if there if "flashvars.hd = \"1\";" in self.html: content =
self.req.load("http://www.megavideo.com/xml/videolink.php?v=%s" % id) return unescape(re.search("hd_url=\"(.*?)\"", content).group(1)) # else get normal link s = re.search("flashvars.s = \"(\\d+)\";", self.html).group(1) un = re.search("flashvars.un = \"(.*?)\";", self.h...
hacklabr/mapasculturais-openid
iddacultura/settings/staging.py
Python
gpl-2.0
270
0
# coding: utf-8 from .base import * DEBUG = True TEMPLATE_DEBUG =
DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.
backends.postgresql_psycopg2', 'NAME': 'openid-staging', } } STATIC_ROOT = join(SITE_ROOT, '../webfiles-staging/static/')
all-umass/manifold_spanning_graphs
viz.py
Python
mit
2,551
0.02548
import numpy as np from matplotlib import pyplot def scatterplot(X, marker='.', title=None, fig=None, ax=None, **kwargs): '''General plotting function for a set of points X. May be [1-3] dimensional.''' assert len(X.shape) in (1,2), 'Only valid for 1 or 2-d arrays of points' assert len(X.shape) == 1 or X.shape[...
tZ = tX.copy() tZ[:,:-1] = t[:,:,2] # needs to be a real array, so we use .ravel()
instead of .flat ax.plot(tX.ravel(), tY.ravel(), tZ.ravel(), edge_style, zorder=1) if vertex_style is not None: ax.scatter(X[:,0], X[:,1], X[:,2], marker=vertex_style, zorder=2, edgecolor=vertex_edgecolor, c=vertex_colors, s=vertex_sizes) else: # tX.flat looks like: [x1,x2,NaN, x3,x...
gusseppe/pymach
pymach/core/fselect.py
Python
mit
2,360
0.003814
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Gusseppe Bravo <[email protected]> # License: BSD 3 clause """ This module provides a few of useful functions (actually, methods) for feature selection the dataset which is to be studied. """ from __future__ import print_function import numpy as np import pandas as pd ...
earn.decomposition import PCA from sklearn.feature_selection import SelectFromModel from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.base import BaseEstimator, TransformerMixin # __all__ = [ # 'pipeline'] class Select: """ A class for feature selection """ #
data = None def __init__(self, definer): self.definer = definer self.problem_type = definer.problem_type self.infer_algorithm = definer.infer_algorithm # self.response = definer.response # self.data_path = definer.data_path self.n_features = definer.n_features ...
rytis/Apache-access-log-parser
plugins/plugin_geoip_stats.py
Python
apache-2.0
767
0.005215
#!/usr/bin/env python from manager import Plugin from operator import itemgetter import GeoIP class GeoIPStats(Plugin): def __init__(self, **kwargs): self.gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) self.countries = {} def process(self, **kwargs): if 'remote_host' in kwargs: ...
ount) in sorted(self.countries.iteritems(), key=itemgetter(1), reverse=True): p
rint " %10d: %s" % (count, country)
HaebinShin/tensorflow
tensorflow/contrib/learn/python/learn/estimators/svm_test.py
Python
apache-2.0
10,014
0.001897
# Copyright 2016 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...
put_fn=input_fn, steps=1) loss = metrics['loss'] accuracy =
metrics['accuracy'] # Adding small L1 regularization favors even smaller weights. This results # to somewhat moderate unregularized loss (bigger than the one when there is # no L1 regularization. Still, since L1 is small, all the predictions will # be correct resulting to perfect accuracy. self.as...
Acidity/PyPermissions
pypermissions/decorators.py
Python
mit
5,369
0.007078
from pypermissions.permission import PermissionSet def _prepare_runtime_permission(self, perm=None, runkw=None, args=None, kwargs=None): """This function parses the provided string arguments to decorators into the actual values for use when the decorator is being evaluated. This allows for permissions to be c...
ime. """ return set_has_permission(perm, perm_set, on_failure, perm_
check=PermissionSet.has_any_permission, **runkw)
mmccoo/kicad_mmccoo
toggle_visibility/__init__.py
Python
apache-2.0
606
0.006601
import pcbnew from . import toggle_visibility class ToggleVisibilityPlugin(pcbnew.ActionPlugin): def defaults(self): self.na
me = "Toggle visibility of value/reference (of selected modules)" self.category = "A descriptive category name" self.description = "This plugin toggles the visibility of any selected module v
alues/references" def Run(self): # The entry function of the plugin that is executed on user action toggle_visibility.ToggleVisibility() ToggleVisibilityPlugin().register() # Instantiate and register to Pcbnew print("done adding toggle")
youkochan/shadowsocks-analysis
shadowsocks/manager.py
Python
apache-2.0
12,796
0.000315
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 clowwindy # # 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 b...
self.remove_user(a_config) self._send_control_data(b'ok') elif command == 'ping': self._send_control_data(b'pong') else: logging.error('unknown command %s', command) ...
control_data(b'unknown command') except AssertionError: self._send_control_data(b'error command') else: self._send_control_data(b'error command') def _parse_command(self, data): # commands: # add: {"server_port": 8000, "password": "foo...
tantale/bumpversion_demo
setup.py
Python
mit
356
0.002809
from distutils.core import setup setup( name='bumpversion_demo',
version='0.1.0', packages=[''], url='https://github.com/tantale/bumpversion_demo', license='MIT License', author='Tantale', author_email='[email protected]', description='Demonstration of ``bumpversion`` usage in the context of a Pyth
on project.' )
rocket-league-replays/rocket-league-replays
rocket_league/apps/replays/migrations/0014_auto_20151013_2217.py
Python
gpl-3.0
1,589
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('replays', '0013_replaypack_file'), ] operations = [ migrations.AddField( model_name='player', name='...
.BooleanField(default=False), ), migrations.AddField( model_name='player', name='goals', field=models.PositiveIntegerField(default=0, blank=True), ), migrations.AddField( model_name='player', name='online_id', field=...
ls.BigIntegerField(null=True, blank=True), ), migrations.AddField( model_name='player', name='platform', field=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='player', name='saves', ...
Exteris/lsdeflate
tests/context.py
Python
gpl-3.0
122
0.016393
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '
..'))
) import lsdeflate
team-vigir/vigir_behaviors
behaviors/vigir_behavior_simple_joint_control_test/src/vigir_behavior_simple_joint_control_test/simple_joint_control_test_sm.py
Python
bsd-3-clause
26,416
0.025515
#!/usr/bin/env python ########################################################
### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] tags will be kept. # ########################################################### import roslib; ...
behavior_simple_joint_control_test') from flexbe_core import Behavior, Autonomy, OperatableStateMachine, Logger from vigir_flexbe_states.check_current_control_mode_state import CheckCurrentControlModeState from vigir_flexbe_states.change_control_mode_action_state import ChangeControlModeActionState from vigir_flexbe_st...
VolodyaEsk/selenium_python_tony_project
tests/other/waits.py
Python
gpl-2.0
1,361
0.002204
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.
common.by import By from selenium.common.exceptions import TimeoutException import unittest class WaitForElements(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() cls.driver.maximize_window() cls.wait = WebDriverWait(cls.driver, 10) def test_...
s_selector(button_locator) # see_button = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, button_locator))) print see_button def test_wait_for_search_field(self): self.driver.get("http://travelingtony.weebly.com/") search_locator = 'input.wsite-search-input' ...
antoinearnoud/openfisca-france
openfisca_france/scripts/performance/measure_tests_performance.py
Python
agpl-3.0
1,894
0.00528
# -*- coding: utf-8 -*- """ This files tests the performance of the test runner of openfisca-run-test on a subset of YAML tests. It is placed in openfisca-france because it is the largest set we currently have. Usage example: python openfisca_france/scripts/performance/measure_tests_performance.py """ import os...
em # Create logger logging.basicConfig(level = logging.INFO) logger = logging.getLogger(__name__) # Baselines for comparision - unit : seconds BASELINE_TBS_LOAD_TIME = 9.10831403732 BASELINE_YAML_TESTS_TIME = 271.448431969 # Time tax benefit system loading start_time_tbs = time.time() tbs = CountryTaxBenefitSystem(...
.get_distribution('OpenFisca-France').location yaml_tests_dir = os.path.join(openfisca_france_dir, 'tests', 'mes-aides.gouv.fr') # Time openfisca-run-test runner start_time_tests = time.time() run_tests(tbs, yaml_tests_dir) time_spent_tests = time.time() - start_time_tests def compare_performance(baseline, test_res...
JoZie/denite-make
rplugin/python3/denite/source/make.py
Python
mit
5,366
0.010622
# ============================================================================ # FILE: make.py # AUTHOR: Johannes Ziegenbalg <Johannes dot Ziegenbalg at gmail.com> # License: MIT license # ============================================================================ import re import shlex import os, sys, stat from os i...
self.__last_message['line'], self.__last_message['col'] ), 'abbr' : clean_line, 'action__path' : self.__last_message['full_file'], 'action__line' : self.__last_message['line'], 'action__col' : self.__last_m...
r'].search( line ) if match: message = match.groupdict() self.__dir_map[message['process']] = message['dir'] return { 'word' : clean_line, 'abbr' : clean_line, 'action__path' : '' } def __create_make_wrapper(self): script...
WGS-TB/MentaLiST
scripts/create_new_scheme_with_novel.py
Python
mit
2,432
0.00699
#!/usr/bin/env python import logging logger = logging.getLogger() import argparse import collections import sys import os from Bio import SeqIO if __name__ == "__main__": parser = argparse.ArgumentParser(description="Adds novel alleles to an existing MLST scheme.") parser.add_argument("-n", "--novel", type=...
end(seq_record) # create folder if it does not exist: if not os.path.isdir(param.output): os.makedirs(param.output) # Open mlst mlst = {} logger.info("Opening the MLST schema and adding novel alleles ...") for f in param.files: logger.debug("Opening file %s ..." % f) fil...
are novel alleles for this locus, add: if len(novel[locus]) > 0: # find maximum id present, novel alleles gets next; id_list = [int(s.id.split("_")[-1]) for s in record_list] next_id = max(id_list) + 1 # append novels: for record in novel[locus]: ...
vsoch/expfactory-python
expfactory/testing/test_views.py
Python
mit
2,582
0.020139
#!/usr/bin/python """ Test experiments """ from expfactory.utils import copy_directory, get_installdir from expfactory.vm import custom_battery_download from expfactory.experiment import load_experiment from expfactory.views import * import tempfile import unittest import shutil import json import os import re class...
t = embed_experiment(self.experiment) self.assertTrue(re.search("<
!DOCTYPE html>",html_snippet)!=None) self.assertTrue(re.search("style.css",html_snippet)!=None) self.assertTrue(re.search("experiment.js",html_snippet)!=None) self.assertTrue(re.search("test_task",html_snippet)!=None) def test_experiment_web(self): generate_experiment_web(se...
pbrunet/pythran
pythran/run.py
Python
bsd-3-clause
5,948
0.000168
#!/usr/bin/env python """ Script to run Pythran file compilation with specified g++ like flags. """ import argparse import logging import os import sys import pythran from distutils.errors import CompileError logger = logging.getLogger("pythran") def convert_arg_line_to_args(arg_line): """Read argument from ...
file `{0}' not found".format( args.input_file)) module_name, ext = os.path.splitext(os.path.basename(args.input_file)) # FI
XME: do we want to support other ext than .cpp? if ext not in ['.cpp', '.py']: raise SyntaxError("Unsupported file extension: '{0}'".format(ext)) if ext == '.cpp': if args.translate_only: raise ValueError("Do you really ask for Python-to-C++ " ...
MaxHalford/xam
xam/nlp/nb_svm.py
Python
mit
695
0.001439
import numpy as np from scipy import sparse fr
om skl
earn import utils from sklearn import linear_model class NBSVMClassifier(linear_model.LogisticRegression): def predict(self, X): return super().predict(X.multiply(self.r_)) def predict_proba(self, X): return super().predict_proba(X.multiply(self.r_)) def fit(self, X, y, sample_weight=No...
fbradyirl/home-assistant
homeassistant/components/clementine/__init__.py
Python
apache-2.0
32
0
"
""The clementine component.""
"
melon-li/openstack-dashboard
horizon/test/tests/tables.py
Python
apache-2.0
65,049
0
# encoding=utf-8 # # Copyright 2012 Nebula, Inc. # Copyright 2014 IBM Corp. # # 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 # #...
ype_
singular = "Item" data_type_plural = "Items" def action(self, request, object_ids): pass class MyBatchActionWithHelpText(MyBatchAction): name = "batch_help" help_text = "this is help." action_present = "BatchHelp" action_past = "BatchedHelp" class MyToggleAction(tables.BatchAction):...
shashank971/edx-platform
openedx/core/djangoapps/credit/models.py
Python
agpl-3.0
24,732
0.001536
# -*- coding: utf-8 -*- """ Models for Credit Eligibility for courses. Credit courses allow students to receive university credit for successful completion of a course on EdX """ import datetime from collections import defaultdict import logging import pytz from django.conf import settings from django.core.cache im...
t and save it in the cache credit_providers = CreditProvider.objects.filter(active=True) credit_providers = [ { "id": provider.provider_id, "display_name": provider.display_name, "url": provider.provider_url, ...
r_status_url, "description": provider.provider_description, "enable_integration": provider.enable_integration, "fulfillment_instructions": provider.fulfillment_instructions, "thumbnail_url": provider.thumbnail_url, } ...
chengdujin/newsman
newsman/tools/text_based_feeds/feed_title_change.py
Python
agpl-3.0
797
0.002509
import sys reload(sys) sys.setdefaultencoding('utf-8') sys.path.append('../..') from config.settings import Collection, db from config.settings import FEED_REGISTRAR def _convert(language, country): feeds = Collection(db, FEED_REGISTRAR) f = open('feed_lists/%s_%s_feed_titles' % (language, country), 'r') ...
print d url, title = d.strip().split('*|*') item = feeds.update({'language': language, 'countries': country, 'feed_link': url.strip()}, {'$set': {'feed_title': title.strip()}}) if __name__ == "__main__": if len(sys.argv) > 1: _conv...
ountry'
RedhawkSDR/framework-codegen
redhawk/codegen/jinja/python/ports/frontend.py
Python
lgpl-3.0
2,269
0.004848
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of REDHAWK core. # # REDHAWK core is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free ...
m redhawk.codegen.jinja.ports import PortGenerator from redhawk.codegen.jinja.ports import PortFactory from generator import PythonPortGenerator from redhawk.codegen.lang import python class FrontendPortFactory(PortFactory): NAMESPACE = 'FRONTEND' def match(self, port): return IDLInterface(port.repid...
interface = IDLInterface(port.repid()).interface() return FrontendPortGenerator(port) class FrontendPortGenerator(PythonPortGenerator): def className(self): return "frontend." + self.templateClass() def templateClass(self): if self.direction == 'uses': porttype = 'Ou...
was4444/chromium.src
tools/perf/profile_creators/extension_profile_extender_unittest.py
Python
bsd-3-clause
1,275
0.009412
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import shutil import tempfile from profile_creators import extension_profile_extender from telemetry import decorators from telemetry.testing impo...
/crbug.com/586362. @decorators.Disabled('all') # Extension generation only works on Mac for now. def testExtensionProfileCreation(self): tmp_dir = tempfile.mkdtemp() files_in_crx_dir = 0 try
: options = options_for_unittests.GetCopy() options.output_profile_path = tmp_dir extender = extension_profile_extender.ExtensionProfileExtender(options) extender.Run() crx_dir = os.path.join(tmp_dir, 'external_extensions_crx') files_in_crx_dir = len(os.listdir(crx_dir)) finally...
Aloomaio/googleads-python-lib
examples/adwords/v201806/account_management/get_account_hierarchy.py
Python
apache-2.0
3,452
0.009849
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
[link['clientCustomerId']].append(link) # Map from customerID to account. for account in page['entries']: accounts[account['customerId']] = account offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset
< int(page['totalNumEntries']) # Find the root account. for customer_id in accounts: if customer_id not in parent_links: root_account = accounts[customer_id] # Display account tree. if root_account: print 'CustomerId, Name' DisplayAccountTree(root_account, accounts, child_links, 0) else: ...
berquist/pyquante2
pyquante2/dft/dft.py
Python
bsd-3-clause
899
0.032258
import numpy as np from pyquante2.dft.functionals import xs,cvwn5 # Maybe move these to the functionals module and import from there? xname = dict(lda=xs,xs=xs,svwn=xs) cname = dict(lda=cvwn5,svwn=cvwn5,xs=None) def get_xc(grid,D,**kwargs): xcname = kwargs.get('xcname','lda') # Does
not work on either gradient corrected functionals or spin-polarized functionals yet. xfunc = xname[xcname] cfunc = cname[xcname] rho = grid.getdens(D) fx,dfxa = xfunc(rho) if cfunc: fc,dfca,dfcb = cfunc(rho,rho) else: fc=dfca=dfcb=0 w = grid.points[:,3] ...
bfamps,grid.bfamps) # The fx comes from either the up or the down spin, whereas the fc comes from # both (which is why x is called with either one, and c is called with both Exc = np.dot(w,2*fx+fc) return Exc,Vxc
jwren/intellij-community
python/testData/codeInsight/smartEnter/firstClauseAfterEmptyMatchStatementWithSubjectAndColon.py
Python
apache-2.0
15
0.2
ma
tch x<caret>:
jmacmahon/invenio
modules/bibformat/lib/elements/bfe_oai_identifier.py
Python
gpl-2.0
1,610
0.004969
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012 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 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MER...
ved a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """BibFormat element - Prints record OAI identifier """ import cgi from invenio.config import CFG_OAI_ID_FIELD def format_element(bfo, instan...
plotly/octogrid
octogrid/builder/builder.py
Python
mit
2,032
0.000984
# -*- coding: utf-8 -*- """ octogrid.builder.builder This module helps i
n generating a GML file from the graph content """ from ..store.store import cache_file, copy_file from ..utils.utils import username_to_file FILE_PREFIX = 'graph\n[\n' FILE_SUFFIX = ']\n' NODE_PREFIX = '\tnode\n\t[\n' NODE_SUFFIX = '\t]\n' EDGE_PREFIX = '\tedge\n\t[\n' EDGE_SUFFIX = '\t]\n' SIGNATURE = 'Creator "oct...
sent a node """ return NODE_PREFIX + id + label + NODE_SUFFIX def format_edge(source, target): """ Return the formatted string to represent an edge """ return EDGE_PREFIX + source + target + EDGE_SUFFIX def format_content(node, edge): """ Return the formatted GML file content "...
facebookexperimental/eden
eden/scm/edenscm/mercurial/scmutil.py
Python
gpl-2.0
49,777
0.000743
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # scmutil.py - Mercurial core utility functions # # Copyright Matt Mackall <[email protected]> # # This software may be used and distributed a...
r=_("certificate error"), ) except error.TlsError as inst: # This is a generic TLS error that may or may not be due to the user's # client certificate, so print a more
generic message about TLS errors. helptext = ui.config("help", "tlshelp") if helptext is None: helptext = _("(is your client certificate valid?)") ui.warn( _("%s!\n\n%s\n") % (inst.args[0], helptext), error=_("tls error"), ) except error.RevlogErro...
chilcote/unearth
artifacts/mac_address.py
Python
apache-2.0
879
0.001138
from SystemConfiguration import ( SCDynamicStoreCopyValue, SCDynamic
StoreCreate, SCNetworkInterfaceCopyAll, SCNetworkInterfaceGetBSDName, SCNetworkInterfaceGetHardwareAddressString, ) factoid = "mac_addr
ess" def fact(): """Returns the mac address of this Mac""" primary_MAC = "None" net_config = SCDynamicStoreCreate(None, "net", None, None) states = SCDynamicStoreCopyValue(net_config, "State:/Network/Global/IPv4") primary_interface = states["PrimaryInterface"] primary_devices = [ x ...
michelesr/gasistafelice
gasistafelice/rest/views/blocks/users.py
Python
agpl-3.0
4,621
0.01082
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy from rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction from consts import EDIT, CONFIRM, EDIT_MULTIPLE, VIEW from lib.shortcuts import render_to_response, render_to_xml_response, render_to_context_response from gf.gas.form...
'is_active' : form['is_active'], 'person' : person, 'person_urn': person_urn, }) return formset, records, {}
tomchuk/meetup
meetup/todo/serializers.py
Python
mit
182
0
from rest_framework import seri
alizers from .models import Todo class TodoSerializer(ser
ializers.ModelSerializer): class Meta: model = Todo fields = '__all__'
cherokee/pyscgi
tests/test5.py
Python
bsd-3-clause
850
0.024706
import os import CTK UPLOAD_DIR = "/tmp"
def ok (filename, target_dir, target_file, params): txt = "<h1>It worked!</h1>" txt += "<pre>%s</pre>" %(os.
popen("ls -l '%s'" %(os.path.join(target_dir, target_file))).read()) txt += "<p>Params: %s</p>" %(str(params)) txt += "<p>Filename: %s</p>" %(filename) return txt class default: def __init__ (self): self.page = CTK.Page () self.page += CTK.RawHTML ("<h1>Direct Upload with params</h1>"...
alirizakeles/tendenci
tendenci/apps/categories/urls.py
Python
gpl-3.0
227
0.004405
from django.conf.urls import patterns, url urlpa
tterns = patterns('tendenci.apps.categories.views', url(r'^update/(?P<app_label>\w+)/(?P<model>\w+)/(?P<p
k>[\w\d]+)/$', 'edit_categories', name="category.update"), )
Cal-CS-61A-Staff/ok
migrations/versions/7e1d5c529924_custom_submission_times_for_backup.py
Python
apache-2.0
1,201
0.011657
"""Custom submission times for Backup Revision ID: 7e1d5c529924 Revises: 6ce2cf5c4534 Create Date: 2016-10-25 20:31:14.423524 """ # revision identifiers, used by Alembic. revision = '7e1d5c529924' down_revision = '6ce2cf5c4534' from alembic import op import sqlalchemy as sa import server from sqlalchemy.dialects im...
r_id_user'), 'backup', 'user', ['creator_id'], ['id']) op.drop_column('backup', 'extension') ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('backup', sa.Column('extension', mysql.TINYINT(display_width=1), autoincrement=False, nul...
p', type_='foreignkey') op.drop_column('backup', 'custom_submission_time') op.drop_column('backup', 'creator_id') ### end Alembic commands ###
cxchope/YashiLogin
tests/test_searchuser.py
Python
mit
448
0.004739
# -*- coding
:utf-8 -*- import test_core impo
rt sys import demjson test_core.title("搜索用户") f = open("testconfig.json", 'r') lines = f.read() f.close() jsonfiledata = demjson.decode(lines) if jsonfiledata["url"] == "": test_core.terr("错误: 'testconfig.json' 配置不完全。") exit() uurl = jsonfiledata["url"]+"search.php" udataarr = { 'type': "username", 'wor...
UdK-VPT/Open_eQuarter
oeq_tb/resources.py
Python
gpl-2.0
5,957
0.000839
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.12.1) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x04\x0a\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x...
00\x00\x01\x00\x00\x00\x00\ \x00\x00\x01\x69\x23\xc2\x96\x6e\ " qt_version = [int(v) for v in QtCore.qVersion().split('.')] if qt_version < [5, 8, 0]: rcc_version = 1 qt_resource_struct = qt_resource_struct_v1 else: rcc_version = 2 qt_resource_struct = qt_res
ource_struct_v2 def qInitResources(): QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources()
scryver/gampy
gampy/engine/events/time.py
Python
gpl-3.0
2,008
0.005976
__author__ = 'michiel' import time class Time: def __init__(self): self._delta = 0. @staticmethod def get_time(): return time.monotonic() @staticmethod def sleep(): time.sleep(0.001) @property def delta(self): return self._delta @delta.setter d...
t2 = time.time() #stop time t = (t2-t1)*1000.0 #time in milliseconds data = (func.__name__, t) self.col.send(data) #collect the data return res return wrapper def __str__(self): s = 'Timings:\n' ...
google/google-ctf
third_party/edk2/BaseTools/Source/Python/CommonDataClass/FdfClass.py
Python
apache-2.0
7,994
0.008506
## @file # classes represent data in FDF # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the ...
self.SecType = None self.SectFileName = None self.SectionList = [] self.KeepReloc = True ## Rule section data in FDF # # class EfiSectionClassObject (SectionClassObject): ## The constructor # # @param self The object pointer # def __init__(sel...
ileName = None self.FileExtension = None self.BuildNum = None self.KeepReloc = None ## FV image section data in FDF # # class FvImageSectionClassObject (SectionClassObject): ## The constructor # # @param self The object pointer # def __init__(self): ...
roadmapper/ansible
lib/ansible/modules/cloud/vmware/vmware_guest_serial_port.py
Python
gpl-3.0
19,614
0.003161
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Anusha Hegde <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version':...
'Valid attributes are:' - ' - C(backing_type) (str): Backing type is required for the serial ports to be added or reconfigured or removed.' - ' - C(state) (str): is required to identify whether we are adding, modifying or removing the serial port. - choices:
- C(present): modify an existing serial port. C(backing_type) is required to determine the port. The first matching C(backing_type) and either of C(service_uri) or C(pipe_name) or C(device_name) or C(file_path) will be modified. If there is only one device with a backing type, the ...
sumit4iit/django-guardian
guardian/tests/other_test.py
Python
bsd-2-clause
12,625
0.005861
from itertools import chain from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.test import TestCase import guardian from guardian.backends import ObjectPermissionBackend from guardian.exceptions import GuardianError from guardian.exceptions import...
roup_assign_validation') ctype = ContentType.objects.get_for_model(group) perm = Permission.objects.get(codename='change_user') create_info = dict( permission = perm, user = self.user, content_type = ctype, object_pk = group.pk ) s...
gn("change_user", self.user, self.user) self.assertTrue(isinstance(obj_perm.__unicode__(), unicode)) def test_errors(self): not_saved_user = User(username='not_saved_user') self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.assign, "change...
doismellburning/django
django/contrib/messages/storage/cookie.py
Python
bsd-3-clause
6,545
0.000764
import json from django.conf import settings from django.contrib.messages.storage.base import BaseStorage, Message from django.http import SimpleCookie from django.utils.crypto import salted_hmac, constant_time_compare from django.utils.safestring import SafeData, mark_safe from django.utils import six class Message...
ata is going to be stored eventually by SimpleCookie, which # adds its own overhead, which we must account for.
cookie = SimpleCookie() # create outside the loop def stored_length(val): return len(cookie.value_encode(val)[1]) while encoded_data and stored_length(encoded_data) > self.max_cookie_size: if remove_oldest: unstored_messages.append(messag...
CivicTechTO/django-councilmatic
councilmatic_core/migrations/0006_bill_subject.py
Python
mit
422
0
# -*- coding: utf
-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0005_auto_20151215_1430'), ] operations = [ migrations.AddField( model_name='bill', name='subjec...
55), ), ]
gtfierro/BAS
web/smapgeo/__init__.py
Python
gpl-3.0
1,039
0
# def inject_app_defaults(application): # """Inject an application's default settings""" # try: # __import__('%s.settings' % application) # import sys # # Import our defaults, project defaults, and project settings #
_app_settings = sys.modules['%s.settings' % application] # _def_settings = sys.modules['django.conf.global_settings'] # _settings = sys.modules['django.conf'].settings # # Add the values from the application.settings module # for _k in dir(_app_settings): # if _k.isu...
etattr(_def_settings, _k, getattr(_app_settings, _k)) # # Add the value to the settings, if not already present # if not hasattr(_settings, _k): # setattr(_settings, _k, getattr(_app_settings, _k)) # except ImportError: # # Silently skip failing settings ...
UrLab/incubator
manmail/admin.py
Python
agpl-3.0
3,491
0.002312
from django.contrib import admin from django.contrib import messages from django.core.mail import EmailMultiAlternatives from django.conf import settings from .models import Email from users.models import User @admin.register(Email) class EmailAdmin(admin.ModelAdmin): list_display = ('subject', 'sent', 'created'...
ver cet email" def send_email(self, request, queryset): if not queryset.count() == 1: self.message_user(request, message="Vous ne devez séléctionner qu'un emai
l à envoyer", level=messages.ERROR) return email = queryset.first() if email.sent: self.message_user(request, message="Cet email a déjà été envoyé", level=messages.ERROR) return if email.approvers.count() < settings.MINIMAL_MAIL_APPROVERS: self....
kjflyback/June-work
dailywork/forms.py
Python
apache-2.0
771
0.022049
from flask_wtf import Form from wtforms import TextField, Boole
anField, TextAreaField from wtforms.validators import Req
uired class LoginForm(Form): SECRET_KEY = "xman" openid = TextField('openid', validators = [Required()]) remember_me = BooleanField('remember_me', default = False) class PostForm(Form): clientname = TextField('clientname', validators = [Required()]) clienttype = TextField('clienttype') client...
mindnuts/proventeq-test-repo
src/python/ios_webview.py
Python
apache-2.0
1,607
0.001867
""" Simple iOS WebView tests. """ import unittest import os from random import randint from appium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys class WebVie
wIOSTests(unittest.TestCase): def setUp(self): # set up appium app = os.path.join(os.path.dirname(__file__), '../../apps/WebViewApp/build/Release-iphonesimulator', 'WebVie
wApp.app') app = os.path.abspath(app) self.driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities={ 'app': app, 'deviceName': 'iPhone Simulator', 'platformName': 'iOS', 'plat...
romain-intel/bcc
tools/lib/ugc.py
Python
apache-2.0
7,598
0.001579
#!/usr/bin/python # @lint-avoid-python-3-compatibility-imports # # ugc Summarize garbage collection events in high-level languages. # For Linux, uses BCC, eBPF. # # USAGE: ugc [-v] [-m] [-M MSEC] [-F FILTER] {java,python,ruby,node} pid # # Copyright 2016 Sasha Goldshtein # Licensed under the Apache License, Versi...
examples = """examples: ./ugc -l java 185 # trace Java GCs in process 185 ./ugc -l ruby 1344 -m # trace Ruby GCs reporting in ms ./ugc -M 10 -l java 185 # trace only Java GCs longer than 10ms """ parser = argparse.ArgumentParser( description="Summarize garbage collection events in high-level ...
Formatter, epilog=examples) parser.add_argument("-l", "--language", choices=languages, help="language to trace") parser.add_argument("pid", type=int, help="process id to attach to") parser.add_argument("-v", "--verbose", action="store_true", help="verbose mode: print the BPF program (for debugging purposes)...
dials/dials
util/filter_reflections.py
Python
bsd-3-clause
38,269
0.001934
""" Methods for filtering reflection tables for bad data. The filtering methods are combined into functions to perform the relevant filtering on a reflection table(s), to produce a filtered reflection table ready for export or further processing. The set of classes defined in this module have filtering methods implem...
oice - sum_partial_reflections: combines matching partials, replacing them with a single combined value filter_reflection_table takes in the following parameters: min_isigi=float, filter_ice_rings=bool, combine_partials=bool, partiality_threshold=float, intensity_choice=strings (passed in as a list e.g. ...
lgorithm: defines a full, general filtering algorithm for a reflection table - PrfIntensityReducer: implements methods specific to filtering of profile fitted (prf) intensities - SumIntensityReducer implements methods specific to filtering of summation (sum) intensities - SumAndPrfIntensityReduc...
junneyang/taskflow
taskflow/tests/unit/worker_based/test_pipeline.py
Python
apache-2.0
3,812
0.000525
# -*- coding: utf-8 -*- # Copyright (C) 2014 Yahoo! 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...
ask_classes): server, server_thread = self._fetch_server(task_classes) executor = self._fetch_executor() self.addCleanup(executor.stop) self.addCleanup(server_thread.join) self.addCleanup(server.stop) executor.start() server_thread.start() server.wait() ...
server = self._start_components([test_utils.TaskOneReturn]) self.assertEqual(0, executor.wait_for_workers(timeout=WAIT_TIMEOUT)) t = test_utils.TaskOneReturn() progress_callback = lambda *args, **kwargs: None f = executor.execute_task(t, uuidutils.generate_uuid(), {}, ...
kosior/taktyk
taktyk/entry.py
Python
mit
2,324
0.001721
import os from inspect import signature from . import db from . import settings class Entry: def __init__(self, id_=None, author=None, date=None, body=None, body_html=None, url=None, plus=None, media_url=None, tags=None, is_nsfw=None, entry_id=None, type_=None): self.id_ = id_ se...
R_NAME) if self.entry_id: # it's a comment return os.path.join(path, settings.COMMENTS_DIR_NAME, '{}_{}{}'.format(self.entry_id, self.id_, ext)) return os.pa
th.join(path, '{}{}'.format(self.id_, ext)) return ''
uwosh/uwosh.initiatives
uwosh/initiatives/browser/initiatives.py
Python
gpl-2.0
1,839
0.014138
from Products.Five.browser import BrowserView from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from plone.app.layout.viewlets.common import ViewletBase from Products.CMFCore.utils import getToolByName from AccessControl import getSecurityManager from zope.component import getMultiAdapter from zop...
f.should_display = True if self.should_display: self.sitetitle = site.title catalog = getToolByName(self.context, 'portal_catalog') self.view_all_url = props.getProperty('view_all_url', None) if self.view_all_url is None and 'initiatives' in ...
/initiatives' self.initiatives = catalog( portal_type = 'Initiative', review_state = 'published', sort_on = 'getObjPositionInParent', sort_order = 'ascending', getShowInitiative='True' ) ...
rhelmer/socorro
socorro/app/socorro_app.py
Python
mpl-2.0
19,914
0.001506
#! /usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """This module defines the class hierarchy for all Socorro applications. The base of the hierarc...
ler will change that back to True if it wants # the app to restart and run again. restart = False app_exit_code = klass._do_run( config_path=config_path, values_source_list=values_source_list ) r
eturn app_exit_code #-------------------------------------------------------------------------- @classmethod def _do_run(klass, config_path=None, values_source_list=None): # while this method is defined here, only derived classes are allowed # to call it. if klass is SocorroApp: ...
PyCQA/astroid
astroid/brain/brain_multiprocessing.py
Python
lgpl-2.1
3,516
0.000853
# Copyright (c) 2016, 2018, 2020 Claudiu Popa <[email protected]> # Copyright (c) 2019 Hugo van Kemenade <[email protected]> # Copyright (c) 2020-2021 hippo91 <[email protected]> # Copyright (c) 2020 David Gilman <[email protected]> # Copyright (c) 2021 Pierre Sassoulas <pierre.sassoula...
e return module def _multiprocessing_managers_transform(): return parse( """ import array import threading import multiprocessing.pool as pool import queue class Namespace(object): pass class Value(object): def __init__(self, typecode, value, lock=True): ...
lue def __repr__(self): return '%s(%r, %r)'%(type(self).__name__, self._typecode, self._value) value = property(get, set) def Array(typecode, sequence, lock=True): return array.array(typecode, sequence) class SyncManager(object): Queue = JoinableQueue = queue.Queue ...
Jamlum/pytomo
pytomo/dns/rdtypes/ANY/X25.py
Python
gpl-2.0
2,219
0.008562
# Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED ...
ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from __future__ import absolute_import from . import exception as dns_exception from . import rdata as dns_rdata from . impor
t tokenizer as dns_tokenizer class X25(dns_rdata.Rdata): """X25 record @ivar address: the PSDN address @type address: string @see: RFC 1183""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(X25, self).__init__(rdclass, rdtype) self.address = a...
Haabb/pwnfork
pwn/process.py
Python
mit
1,834
0.004362
import pwn from basechatter import basechatter class process(basechatter): def __init__(self, cmd, *args, **kwargs): env = kwargs.get('env', {}) timeout = kwargs.get('timeout', 'default') silent = kwargs.get('silent', False) basechatter.__init__(self, timeout, silent) self.p...
pwn.log.succeeded() def connected(self): return self.proc != None def close(self): if self.proc: self.proc.kill() self.proc = None def _send(self, dat): self.proc.stdin.write(dat) self.proc.stdin.flush() def _recv(self, numb): import ...
arne-cl/turian-parser
scripts/treebank-processing/modules/postags.py
Python
gpl-2.0
873
0.054983
# # postags.py # # List of function POS tags and content POS tags # # $Id: postags.py 1657 2006-06-04 03:03:05Z turian $ # ####################################################################### # Copyright (c) 2004-2006, New York University. All rights reserved ###################################################...
##### # Function POS tags function = { "AUX": 1, "AUXG": 1, "CC": 1, "DT": 1, "EX": 1, "IN": 1, "MD": 1, "PDT": 1, "POS": 1, "PRP": 1, "PRP$": 1, "RP": 1, "TO": 1, "WDT": 1, "WP": 1, "WP$": 1, "WRB": 1, "#": 1, "$": 1, ".": 1, ",": 1, ":": 1, "''": 1, "``": 1, "-LRB-": 1, "-RRB-": 1, "-NONE-": 1, } # Content POS tags...
1, "NNPS": 1, "RB": 1, "RBR": 1, "RBS": 1, "SYM": 1, "UH": 1, "VB": 1, "VBD": 1, "VBG": 1, "VBN": 1, "VBP": 1, "VBZ": 1, }
aspaas/ion
test/functional/reindex.py
Python
mit
1,525
0.003934
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distribute
d under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test running iond with -reindex and -reindex-chainstate options. -
Start a single node and generate 3 blocks. - Stop the node and restart it with -reindex. Verify that the node has reindexed up to block 3. - Stop the node and restart it with -reindex-chainstate. Verify that the node has reindexed up to block 3. """ from test_framework.test_framework import IonTestFramework from test_...
mikoim/japanization
reviews/urls.py
Python
mit
834
0.004796
from django.conf.urls import include, url from django.views.decorators.cache import cache_page as cp from django.views
.generic import TemplateView from rest_framework.routers import DefaultRouter from .v
iews import ReviewViewSet, ReviewView router = DefaultRouter() router.register(r'reviews', ReviewViewSet) urlpatterns = [ url(r'^$', cp(60 * 5)(ReviewView.as_view(template_name='reviews/index_list.html')), name='reviews-index'), url(r'^api/', include(router.urls), name='reviews-api'), url(r'^manual$', cp(...
Azure/azure-sdk-for-python
sdk/cognitiveservices/azure-cognitiveservices-knowledge-qnamaker/azure/cognitiveservices/knowledge/qnamaker/models/endpoint_settings_dto_active_learning.py
Python
mit
946
0
# 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 cause incorrect behavior and will be lost if the code is # regenerated. # ----...
------------------------------------------------------- from .active_learning_settings_dto import ActiveLearningSettingsDTO class EndpointSettingsDTOActiveLearning(ActiveLearningSettingsDTO): """Active Learning settings of the endpoint. :param enable: True/False string providing Active Learning :type en...
tox-dev/tox
tests/unit/config/test_config.py
Python
mit
123,326
0.000649
# coding=utf-8 import os import re import sys from textwrap import dedent import py import pytest from pluggy import PluginManager from six import PY2 from virtualenv.info import IS_PYPY import tox from tox.config import ( CommandParser, DepOption, PosargsOption, SectionReader, get_homedir, ge...
envconfig.interrupt_timeout assert 0.2 == envconfig.terminate_timeout envconfig = config.envconfigs["dev"] assert 30.0 == envconfig.suicide_timeout assert 5.0 == envconfig.interrupt_timeout assert 10.0 == envconfig.terminate_time
out class TestConfigPlatform: def test_config_parse_platform(self, newconfig): config = newconfig( [], """ [testenv:py1] platform = linux2 """, ) assert len(config.envconfigs) == 1 assert config.envconfigs["py1"].platform == "...
stevearc/python-pike
pike/nodes/source.py
Python
mit
1,294
0
""" Nodes that read files. """ from .base import Node from pike.items import FileMeta from pike.util import recursive_glob, resource_spec class SourceNode(Node
): """ Base class for source nodes. Source nodes are nodes that read files from disk and inject them into a graph.
""" name = 'source' def __init__(self, root): super(SourceNode, self).__init__() self.root = resource_spec(root) def process(self): return [FileMeta(filename, self.root) for filename in self.files()] def files(self): """ Return a list of all filenames for t...
diogocs1/comps
web/addons/pad/res_company.py
Python
apache-2.0
423
0.007092
# -*- coding: utf-8 -*- from openerp.osv import fields, osv cl
ass company_pad(osv.osv): _inherit = 'res.company' _columns = { 'pad_server': fields.char('Pad Server', help="Etherpad lite server. Example: beta.primarypad.com"), 'pad_key': fields.char('Pad Api Key', help="Etherpad li
te api key.", groups="base.group_system"), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
hdemers/webapp-template
webapp/publish.py
Python
mit
1,031
0
import gevent from cloudly.pubsub import RedisWebSocket from cloudly.tweets import Tweets, StreamManager, keep from cloudly import logger from webapp import config log = logger.init(__name__) pubsub = RedisWebSocket(config.pubsub_channel) pubsub.spawn() running = False def processor(tweets): pubsub.publish(kee...
streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates(), stop) log.info("Twitter stream manager has stopped.") def start(): global running if not running: running = True gevent.spawn(run) def subscribe(we
bsocket): log.info("Subscribed a new websocket client.") pubsub.register(websocket) def stop(): global running if len(pubsub.websockets) == 0: log.info("Stopping Twitter stream manager.") running = False return True return False
nefarioustim/parker
test/test_fileops.py
Python
gpl-3.0
1,419
0
# -*- coding: utf-8 -*- """Test the file operations.""" import os import parker.fileops TEST_FILE_PATH = "/tmp/test/file/path" TEST_FILE = "/tmp/t
est.log" TEST_S
TRING = "This is a string." TEST_DICT = { "this": "dict" } TEST_DICT_LINE = '{"this": "dict"}' TEST_CHUNK_STRING = 'MAGICUNICORNS' EXPECTED_CHUNK_PATH = 'MAG/ICU/NIC/ORN/S' def test_create_dirs_actually_creates_dirs(): """Test fileops.create_dirs actually creates all dirs in path.""" parker.fileops.create...
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/test_executor_check_feed.py
Python
apache-2.0
3,210
0
# Copyright (c) 2020 PaddlePaddle 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 app...
t=x, size=1, act=None) cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_cost = fluid.layers.mean(cost) opt = fluid.optimizer.Adam(learning_rate=lr) opt.minimize(avg_cost) return lr, avg_cost def test_program_check_feed(self): main_program = fluid.Program() startup_program = fluid.Program() scope = fluid.Scope() with fluid...
danielvdao/facebookMacBot
venv/lib/python2.7/site-packages/sleekxmpp/plugins/base.py
Python
mit
12,142
0
# -*- encoding: utf-8 -*- """ sleekxmpp.plugins.base ~~~~~~~~~~~~~~~~~~~~~~ This module provides XMPP functionality that is specific to client connections. Part of SleekXMPP: The Sleek XMPP Library :copyright: (c) 2012 Nathanael C. Fritz :license: MIT, see LICENSE for more details """ i...
et() with self._plugin_lock: if name not in _disabled and name in self._enabled: _disabled.add(name) plugin = self._plugins.get(name, None) if plugin is None: raise PluginNotFound(name) for dep in PLUGIN_DEPENDENTS[n...
self.disable(dep, _disabled) plugin._end() if name in self._enabled: self._enabled.remove(name) del self._plugins[name] def __keys__(self): """Return the set of enabled plugins.""" return self._plugins.keys() def __...
vadim-ex/subcommand
cmd-lib/cmdutil/utils.py
Python
mit
3,029
0.00066
#!/usr/bin/env python3 import pathlib import subprocess import sys def _exec(command, check): """ execute the `command`. If `check` is True, the execution end if git root not found. Otherwise `None` is returned. """ complete = subprocess.run(command, stdout=subprocess.PIPE, encoding="utf-8")...
en(current.parts) == 1: break current = current.parent if (current / file_name).is_file(): return current elif check: print(f"expected file `{file_name}` not found") sys.exit(4) else: return None def project_location(file_name, check=True): """ L...
If `check` is True, the execution end if git root not found. Otherwise `None` is returned. """ current = pathlib.Path.cwd() projects = current.glob("**/" + file_name) while not list(projects) and len(current.parts) > 1: current = current.parent projects = current.glob("**/" + f...
jcsp/manila
manila/db/api.py
Python
apache-2.0
34,750
0
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file...
n IMPL.quota_update(context, project_id, resource, limit, user_id=user_id) ################### def quota_class_create(context, class_name, resource, limit): """Create a quota class for the given name and resource.""" return IMPL.quota_class_create(context, class_name, resource, ...
ota class or raise if it does not exist.""" return IMPL.quota_class_get(context, class_name, resource) def quota_class_get_default(context): """Retrieve all default quotas.""" return IMPL.quota_class_get_default(context) def quota_class_get_all_by_name(context, class_name): """Retrieve all quotas as...
nprapps/visits
etc/gdocs.py
Python
mit
3,436
0.003492
#!/usr/bin/env python from exceptions import KeyError import os import requests class GoogleDoc(object): """ A class for accessing a Google document as an object. Includes the bits necessary for accessing the document and auth and such. For example: doc = { "key": "123456abcdef",...
s/download/spreadsheets/Export?key=%(key)s&exportFormat=%(format)s&gid=%(gid)s' new_spreadsheet_url = 'https://docs.google.com/spreadsheets/d/%(key)s/export?format=%(format)s&id=%(key)s
&gid=%(gid)s' auth = None email = os.environ.get('APPS_GOOGLE_EMAIL', None) password = os.environ.get('APPS_GOOGLE_PASS', None) scope = "https://spreadsheets.google.com/feeds/" service = "wise" session = "1" def __init__(self, **kwargs): """ Because sometimes, just sometimes...
hezral/Rogu
reference/menubutton.py
Python
gpl-3.0
750
0.005333
#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MenuButton(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.connect("destroy", Gtk.main_quit) menubutton = Gtk.MenuButton("MenuButton") self.add(menubutton) ...
ndow = MenuButton() window.show_all() Gt
k.main()
sassoftware/rbuild
rbuild/productstore/__init__.py
Python
apache-2.0
861
0
# # 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 o
f the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific la...
verning permissions and # limitations under the License. # """ Implementations of product stores for different implementations. - C{abstract}: product store base class - C{dirstore}: directory-based checkout as created by the C{rbuild init} command -C{decorators}: decorators for functions that work with the pro...
Yegor-Budnikov/cort
cort/core/external_data.py
Python
mit
4,384
0.000228
""" Read in and access data from external resources such as gender lists.""" import os import pickle import cort from cort.core import singletons from cort.core import util __author__ = 'smartschat' @singletons.Singleton class GenderData: """ Read in and access data from lists with gender information. A...
edent.attributes["tokens"], antecedent.attributes["pos"])) return ( (anaphor_cleaned, antecedent_cleaned) in self.pairs or (antecedent_cleaned, anaphor_cleaned) in self.pairs ) @singletons.Singleton class SingletonMentions: """ Read in and ac...
of potential singleton mentions. """ def __init__(self): """ Initialize the set of pairs from package_root/resources/singletons_not_cleaned.obj. """ directory = cort.__path__[0] + "/resources/" self.singletons = pickle.load( open(directory + "s...
elkingtowa/azove
azove/packet.py
Python
mit
9,338
0
import logging import rlp from utils import big_endian_to_int as idec from utils import int_to_big_endian4 as ienc4 from utils import int_to_big_endian as ienc from utils import recursive_int_to_big_endian import dispatch import sys import signals logger = logging.getLogger(__name__) def lrlp_decode(data): "alwa...
eers: assert ip.count('.') == 3 ip = ''.join(chr(int(x)) for x in ip.split('.')) data.append([ip, port, pid]) return self.dump_packet(data) def dump_Transactions(self, transactions): data = [self.cmd_map_by_name['Transactions']] + transactions return self...
[0x12, [nonce, receiving_address, value, ... ], ... ] Specify (a) transaction(s) that the peer should make sure is included on its transaction queue. The items in the list (following the first item 0x12) are transactions in the format described in the main Ethereum specification. ...
lkundrak/scraperwiki
web/codewiki/tests/models.py
Python
agpl-3.0
322
0.006211
from django.test import TestCase from codewiki.models impo
rt Scraper from django.contrib.auth.models import User class Test__unicode__(TestCase): def test_scraper_name(self): s
elf.assertEqual( 'test_scraper', unicode(Scraper(title='Test Scraper', short_name='test_scraper')) )
Artemkaaas/indy-sdk
docs/how-tos/issue-credential/python/step4.py
Python
apache-2.0
2,869
0.00488
# 14. print_log('\n14. Issuer (Trust Anchor) is creating a Credential Offer for Prover\n') cred_offer_json = await anoncreds.issuer_create_credential_offer(issuer_wallet_handle, cred_def_id) print_log('Credential Of...
\n') await wallet.delete_wallet(issuer_wallet_config, issuer_wallet_credentials) await wallet.delete_wallet(prover_w
allet_config, prover_wallet_credentials) # 20. print_log('\n20. Deleting pool ledger config\n') await pool.delete_pool_ledger_config(pool_name)
arevaloarboled/Clases_2015
topics/threads/Examples/python/basic.py
Python
gpl-2.0
203
0.014778
import threading def worker
(): """thre
ad worker function""" print 'Worker' return threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start()
MockyJoke/numbers
ex3/code/calc_distance_hint.py
Python
mit
1,089
0.00551
def output_gpx(points, output_filename): """ Output a GPX file with latitude and longitude from the points DataFrame. """ from xml.dom.minidom import getDOMImplementation def append_trkpt(pt, trkseg, doc): trkpt = doc.createElement('trkpt') tr
kpt.setAttribute('lat', '%.8f' % (pt['lat'])) trkpt.setAttribute('lon', '%.8f' % (pt['lon'])) trkseg.appendChild(trkpt) doc = getDOMImplementation().createDocument(None, 'gpx', None) trk = doc.createElement('trk') doc.documentElement.appendChild(trk) trkseg = doc.createElement('trks...
c) with open(output_filename, 'w') as fh: doc.writexml(fh, indent=' ') def main(): points = get_data(sys.argv[1]) print('Unfiltered distance: %0.2f' % (distance(points),)) smoothed_points = smooth(points) print('Filtered distance: %0.2f' % (distance(smoothed_points),)) output...
stripe/stripe-python
tests/test_integration.py
Python
mit
9,930
0
from __future__ import absolute_import, division, print_function import platform import sys from threading import Thread, Lock import json import warnings import time import stripe import pytest if platform.python_implementa
tion() == "PyPy": pytest.skip("skip integration tests with PyPy", allow_module_level=True) if sys.version_info[0] < 3: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer else: from http.server import BaseHTTPRequestHandler, HTTPServer class TestIntegration(object): @pytest.fixture(autouse=...
self.mock_server.shutdown() self.mock_server.server_close() self.mock_server_thread.join() @pytest.fixture(autouse=True) def setup_stripe(self): orig_attrs = { "api_base": stripe.api_base, "api_key": stripe.api_key, "default_http_c...
softlayer/softlayer-cinder-driver
slos/test/fixtures/Billing_Item.py
Python
mit
16
0
c
ancelItem
= {}
edespino/gpdb
gpMgmt/bin/gppylib/test/unit/test_unit_gpssh.py
Python
apache-2.0
1,292
0.002322
import imp import os import io import sys from mock import patch from gp_unittest import GpTestCase class GpSshTes
tCase(GpTestCase): def setUp(self): # because gpssh does not have a .py extension, we have to use imp to impor
t it # if we had a gpssh.py, this is equivalent to: # import gpssh # self.subject = gpssh gpssh_file = os.path.abspath(os.path.dirname(__file__) + "/../../../gpssh") self.subject = imp.load_source('gpssh', gpssh_file) self.old_sys_argv = sys.argv sys.argv = [...
roopali8/keystone
keystone/tests/unit/test_token_provider.py
Python
apache-2.0
29,676
0
# Copyright 2013 OpenStack Foundation # # 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...
8773/services/Cloud", "publicURL": "http://localhost:8773/services/Cloud", "region": "RegionOne" } ], "endpoints_links": [], "name": "ec2", "type": "ec2" }, { ...
, "internalURL": "http://localhost:8080/v1/AUTH_01257", "publicURL": "http://localhost:8080/v1/AUTH_01257", "region": "RegionOne" } ], "endpoints_links": [], "name": "swift", ...
FannyCheung/python_Machine-Learning
MapReduce处理日志文件/Reduce.py
Python
gpl-2.0
1,172
0.064607
# coding : utf-8 #file: Reduce.py import os,os.path,re def Reduce(sourceFoler,targetFile): tempData = {}
#缓存列表 p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据 for root,dirs,files in os.walk(sourceFolder): for fil in files: if fil.endswith('_map.txt'): #判断是reduce文件 sFile = open(os.path.abspath(os.path.join(root,fil)),'r') dataLine = sFile.readline() while dataLine: #当有数...
][1]) else: tempData[subdata[0][0]] = int(subdata[0][1]) dataLine = sFile.readline() #读入下一行数据 sFile.close() tList = [] for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True): tList.append(key + ' ' + str(value) + '\n' ) tFilename = os.path.join(sourceFolder...
brianmay/spud
spud/tests/b_integration/test_photos.py
Python
gpl-3.0
3,320
0.000301
import base64 import os import pytest import six from pytest_bdd import parsers, scenarios, then, when from spud import media, models scenarios('photos.feature') @when('we create a photo called <name> using <filename>') def step_create_photo(session, name, filename, data_files): url = "/api/photos/" path ...
Exist): models.photo.objects.get(title=name) @then('we should get a valid photo called <name>') def step_test_r_valid_photo(session, name): photo = session.obj assert photo['title'] == name assert isinstance(photo['description'], six.string_types) assert isinstance(photo['title'], six.string_t...
cription {description}')) def step_test_r_photo_description(session, description): photo = session.obj assert photo['description'] == description @then(parsers.cfparse('we should get {number:d} valid photos')) def step_test_r_n_results(session, number): data = session.obj assert data['count'] == numbe...
Branlala/docker-sickbeardfr
sickbeard/cherrypy/lib/httputil.py
Python
mit
15,480
0.004845
"""HTTP library functions.""" # This module contains functions for building an HTTP application # framework: any one, not just one whose name starts with "Ch". ;) If you # reference any modules from some popular framework inside *this* module, # FuManChu will personally hang you up by your thumbs and submit you # to a...
irst-byte-pos # value greater than the current length of the selected # resource), it SHOULD return a response code of 416 # (Requested range not satisfiable)." continue if stop < start: # From rfc 2616 sec 14.16: ...
ange-spec because it # is syntactically invalid, the server SHOULD treat # the request as if the invalid Range header field # did not exist. (Normally, this means return a 200 # response containing the full entity)." return None ...
milkmeat/thomas
project euler/q49.py
Python
mit
1,149
0.021758
import copy import math def permutation(s): if len(s)==1: return s all=[] for x in s: other=copy.deepcopy(s) other.remove(x) for rest in permutation(other): all.append(x+rest) return all def isprime(prime): if prime<2: return False ...
#['4','1','8','7'] #print permutation([str(d1),str(d2),str(d3),str(d4)]) for a in permutation([str(d1),str(d2),str(d3),str(d4)]): if isprime(int(a)): s.add(int(a)) p=sorted(list(s))
for a in range(len(p)): for b in range(a+1, len(p)): for c in range(b+1, len(p)): if p[b]-p[a]==p[c]-p[b]: print p[a],p[b],p[c]
google-research/pisac
pisac/tanh_normal_projection_network.py
Python
apache-2.0
5,102
0.002548
# coding=utf-8 # Copyright 2020 The PI-SAC Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
raise ValueError('Inputs to TanhNormalProjectionNetwork must match the ' 'sample_spec.dtype.') if mask is not None: raise NotImplementedError( 'TanhNormalProjectionNetwork does not yet implement action masking; ' 'got mask={}'.format(mask)) # outer_rank is need...
ction is not done on the raw # observations so getting the outer rank is hard as there is no spec to # compare to. batch_squash = network_utils.BatchSquash(outer_rank) inputs = batch_squash.flatten(inputs) means_and_stds = self._projection_layer(inputs, training=training) means, stds = tf.split...
smarthomeNG/smarthome
lib/model/mqttplugin.py
Python
gpl-3.0
11,395
0.004651
#!/usr/bin/env python3 # vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab ######################################################################### # Copyright 2019- Martin Sinn [email protected] ######################################################################### # T...
scribe_topic(self.get_shortname() + '-' + current, topic, callback=callback, qos=qos, payload_type=payload_type, bool_values=bool_values) re
turn def add_subscription(self, topic, payload_type, bool_values=None, item=None, callback=None): """ Add mqtt subscription to subscribed_topics list subscribing is done directly, if subscriptions have been started by self.start_subscriptions() :param topic: topic to subscr...
senechal/ssc0570-Redes-Neurais
run.py
Python
mit
708
0.002825
""" Usage: run.py mlp --train=<train> --test=<test> --config=<config> run.py som --train=<train> --test=<test> --config=<config> Options
: --train Path to training data, txt file. --test Path to test data, txt file. --config Json configuration for the network. """ from redes_neurais.resources.manager import run_mlp, run_som import docopt def run(): try: args = docopt.docopt(__doc__)
if args["mlp"]: run_mlp(args['--config'], args['--train'], args['--test']) if args["som"]: run_som(args['--config'], args['--train'], args['--test']) except docopt.DocoptExit as e: print e.message if __name__ == "__main__": run()
tianhuil/isaac-thedataincubator-project
analysis/models.py
Python
apache-2.0
3,132
0.004151
import os import cPickle as pkl from matplotlib.pyplot import * from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.grid_search import GridSearchCV from sklearn.decomposition import PCA from sklearn.feature_extraction.text import C...
best', SelectKBest(k=1000))])): """ Convert a data-frame's descriptions to text features, extract a set of numeric columns, and return the result as a matrix. Also return a vector indicating whether each loan has not yet failed. (1 = no
failure yet, 0 = loan has failed) """ y = ~df.failed.reshape(-1) if fit: text_trans.set_params(**params) text_trans.fit(df.desc.apply(str), y) textdat = text_trans.transform(df.desc.apply(str)) data = df[columns].fillna(-1).as_matrix().astype(float) alldata = concatenate((data,...
pymedusa/Medusa
medusa/session/factory.py
Python
gpl-3.0
748
0
"""Session class factory methods.""" from __future__ import unicode_literals import logging from cachecontrol import CacheControlAdapter from cachecontrol.cache import DictCache log = logging.getLogger(__name__) log.addHandler(
logging.NullHandler()) def add_cache_control(session, cache_control_config): """Add cache_control adapter to session object.""" adapter = CacheControlAdapter( DictCache(), cache_etags=cache_control_config.get('cache_etags', True), serializer=cache_control_config.get('serializer', None)...
c', None), ) session.mount('http://', adapter) session.mount('https://', adapter) session.cache_controller = adapter.controller
Azure/azure-sdk-for-python
sdk/recoveryservices/azure-mgmt-recoveryservices/azure/mgmt/recoveryservices/_configuration.py
Python
mit
3,262
0.003985
# 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 ...
._version import VERSION if TYPE_CHECKING: # pyl
int: disable=unused-import,ungrouped-imports from typing import Any from azure.core.credentials import TokenCredential class RecoveryServicesClientConfiguration(Configuration): """Configuration for RecoveryServicesClient. Note that all parameters used to create this instance are saved as instance ...
compops/gpo-abc2015
state/smc_resampling.py
Python
mit
3,290
0.006383
############################################################################## ############################################################################## # Routines for # Resampling # # Copyright (c) 2016 Johan Dahlin # liu (at) johandahlin.com # #####################################################################...
""" py::list ret; int jj = 0; for(int kk = 0; kk < N; kk++) { double uu = ( u(kk) + kk ) / N; while( ww(jj) < uu && jj < H - 1) { jj++; } ret.append(jj); } return_val = ret; """ H = len(w) if N == 0: ...
u = (np.random.uniform(0.0, 1.0, (N, 1))).astype(float) else: u = float(u) ww = (np.cumsum(w) / np.sum(w)).astype(float) idx = weave.inline(code, ['u', 'H', 'ww', 'N'], type_converters=weave.converters.blitz) return np.array(idx).astype(int) #######################...