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
highsineburgh/gallery_api
gallery_api/gallery/models.py
Python
gpl-3.0
1,130
0
from __future__ import unicode_literals from django.db import models class Artist(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) bio = models.TextField(null=True, blank=True) email_address = models.EmailField() created = models.DateTimeFi...
/interpreter >>> a = Artist(first_name="Vincent", last_name="Van Gough", bio="", \ email_address="vincent@vangough.com") >>> repr(a) '<Artist Vincent Van Gough>' """ return '<Artist {} {}>'.format(self.first_name, self.last_name) def __str__(self): """ ...
me="Vincent", last_name="Van Gough", bio="", \ email_address="vincent@vangough.com") >>> str(a) 'Vincent Van Gough' """ return '{} {}'.format(self.first_name, self.last_name)
ESSS/err
errbot/core_plugins/utils.py
Python
gpl-3.0
2,355
0.001699
from os import path from errbot import BotPlugin, botcmd def
tail(f, window=20): return ''.join(f.readlines()[-window:]) class Utils(BotPlugin): # noinspection
PyUnusedLocal @botcmd def echo(self, _, args): """ A simple echo command. Useful for encoding tests etc ... """ return args @botcmd def whoami(self, msg, args): """ A simple command echoing the details of your identifier. Useful to debug identity problems. """ ...
mgautierfr/devparrot
devparrot/core/utils/posrange/__init__.py
Python
gpl-3.0
938
0.001066
# This file is part of DevParrot. # # Author: Matthieu Gautier <matthieu.gautier@devparrot.org> # # DevParrot 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 ...
right 2011-2013 Matthieu Gautier from .index i
mport Index, Start, End from .range import Range from .mark import Mark from .tag import Tag from .modifier import *
santoshn/softboundcets-34
softboundcets-llvm-clang34/test/CodeGen/SystemZ/Large/branch-range-03.py
Python
bsd-3-clause
3,453
0
# Test 32-bit COMPARE AND BRANCH in cases where the sheer number of # instructions causes some branches to be out of range. # RUN: python %s | llc -mtriple=s390x-linux-gnu | FileCheck %s # Construct: # # before0: # conditional branch to after0 # ... # beforeN: # conditional branch to after0 # main: # 0xffcc by...
CK: jge [[LABEL]] branch_blocks = 8 main_size = 0xffcc print 'define void @f1(i8 *%base, i8 *%stop, i32 %limit) {' print 'entry:' print ' br label %before0' print '' for i in xrange(branch_blocks): next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main' print
'before%d:' % i print ' %%bstop%d = getelementptr i8 *%%stop, i64 %d' % (i, i) print ' %%bcur%d = load volatile i8 *%%bstop%d' % (i, i) print ' %%bext%d = sext i8 %%bcur%d to i32' % (i, i) print ' %%btest%d = icmp eq i32 %%limit, %%bext%d' % (i, i) print ' br i1 %%btest%d, label %%after0, label...
resmo/ansible
test/units/modules/network/fortios/test_fortios_user_device_group.py
Python
gpl-3.0
7,603
0.004209
# Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the...
mock.assert_not_called() assert not is_error assert ch
anged assert response['status'] == 'success' assert response['http_status'] == 200 def test_user_device_group_deletion_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'error', 'http_method': 'POST...
Distrotech/bzr
bzrlib/bisect_multi.py
Python
gpl-2.0
2,731
0.000366
# Copyright (C) 2007 Canonical Ltd # # 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 2 of the License, or # (at your option) any later version. # # This program is distributed in ...
section lookups for keys using byte based addressing. The keys are looked up via the content_lookup routine. The content_lookup routine gives bisect_multi_bytes information about where to keep looking up to find the data for the key, and bisect_multi_bytes feeds this back into the lookup function u
ntil the search is complete. The search is complete when the list of keys which have returned something other than -1 or +1 is empty. Keys which are not found are not returned to the caller. :param content_lookup: A callable that takes a list of (offset, key) pairs and returns a list of result tupl...
thijstriemstra/django-require
require/environments.py
Python
bsd-3-clause
1,816
0.001101
from __future__ import unicode_literals from distutils.spawn import find_executable from django.utils.functional import cached_property from require.conf import settings as require_settings from require.helpers import import_module_attr def load_environment(): environment = require_settings.REQUIRE_ENVIRONMENT...
)), "org.mozilla.javascript.tools.shell.Main",
"-opt", "-1", ] class AutoEnvironment(Environment): environments = [NodeEnvironment, RhinoEnvironment] @cached_property def environment(self): for environment in self.environments: environment = environment(self.env) executable = environment.args()[0] ...
bryancall/trafficserver
tests/gold_tests/pluginTest/tsapi/tsapi.test.py
Python
apache-2.0
4,053
0.003454
# 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...
License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the
License is 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. import os Test.Summary = ''' Test TS API. ''' Test.SkipUnless( Condition.HasCurlFeatur...
jortel/suds
suds/xsd/sxbase.py
Python
lgpl-3.0
19,664
0.003306
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will ...
self.type = root.get('type') self.ref = root.get('ref') self.form_qualified = schema.form_qualified self.nillable = False self.default = root.get('default') self.rawchildren = [] self.cache = {} def attributes(self, filter=Filter()): """ ...
ain the result. @type filter: L{Filter} @return: A list of tuples (attr, ancestry) @rtype: [(L{SchemaObject}, [L{SchemaObject},..]),..] """ result = [] for child, ancestry in self: if child.isattr() and child in filter: result.append((child, an...
nextgis-extra/tests
lib_gdal/ogr/ogr_xplane.py
Python
gpl-2.0
9,631
0.030215
#!/usr/bin/env python ############################################################################### # $Id: ogr_xplane.py 33793 2016-03-26 13:02:07Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: Test OGR XPlane driver functionality. # Author: Even Rouault <even dot rouault at mines dash paris dot org> # ##...
on( 'wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1]) ) return 'fail' feat_read = lyr.GetNextFeature() for item in layer[2]: if feat_read.GetField(item[0]) != item[1]: print(layer[0])
print(item[0]) print(feat_read.GetField(item[0])) return 'fail' return 'success' ############################################################################### # Test nav.dat reading def ogr_xplane_nav_dat(): xplane_nav_ds = ogr.Open( 'data/nav.dat' ) if xplane_nav_ds i...
hirofumi0810/tensorflow_end2end_speech_recognition
models/ctc/decoders/charlm_beam_search_decoder.py
Python
mit
157
0
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __f
uture__ import division from __fut
ure__ import print_function
mattiZed/minqlx-plugins
uneventeams.py
Python
gpl-3.0
9,450
0.00709
# This is an extension plugin for minqlx. # Copyright (C) 2016 mattiZed (github) aka mattiZed (ql) # 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. #...
nded for any reason. Stop all timing. ''' teams = self.teams() for p in teams["red"]: self._players[p.steam_id].stop() for p in teams["blue"]: self._players[p.steam_id].stop() def handle_team_switch(self, player, old_team, new_team): ...
er joined spectators he cant gain playtime. ''' if new_team == "spectator": self._players[player.steam_id].stop() self.deferred_removing(player, self._players[player.steam_id].elapsed()) if new_team == "red" or new_team == "blue": self._players[player...
ewheeler/rapidsms-core
lib/rapidsms/tests/harness.py
Python
lgpl-3.0
2,151
0.013482
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import os from rapidsms.router import Router from rapidsms.backends.backend import Backend from rapidsms.app import App # a really dumb Logger stand-in class MockLogger (list): def __init__(self): # enable logging during tests with an # environment variable,...
pps() def stop (self): self.running = False self.stop_all_backends() class MockBackend (Backend): def start (self): self._running = True self.outgoing = [] def run (self): while self.running: msg = self.next_message(0.25) if msg is not None:...
(self): self.calls.append(("start",)) def parse (self, message): self.calls.append(("parse", message)) def handle (self, message): self.calls.append(("handle", message)) def cleanup (self, message): self.calls.append(("cleanup", message)) def outgoing (self, message)...
DemocracyClub/yournextrepresentative
ynr/apps/candidates/admin.py
Python
agpl-3.0
1,386
0
from django.contrib import admin from django.forms import ModelForm from django.urls import reverse from .models import Ballot, LoggedAction, PartySet class LoggedActionAdminForm(ModelForm): pass @admin.register(LoggedAction) class LoggedActionAdmin(admin.ModelAdmin): form = LoggedActionAdminForm searc...
a>'.format(url, o.person.name) person_link.allow_tags = True class PartySetAdminForm(ModelForm): pass @admin.register(PartySet) class PartySetAdmin(admin.ModelAdmin): f
orm = PartySetAdminForm @admin.register(Ballot) class BallotAdmin(admin.ModelAdmin): list_display = ["post", "election", "winner_count"] list_filter = ("election__name", "election__current") raw_id_fields = ("post", "election") ordering = ("election", "post__label")
striglia/pyramid_swagger
pyramid_swagger/api.py
Python
bsd-3-clause
10,269
0
# -*- coding: utf-8 -*- """ Module for automatically serving /api-docs* via Pyramid. """ from __future__ import absolute_import import copy import os.path import simplejson import yaml from bravado_core.spec import strip_xscope from six.moves.urllib.parse import urlparse from six.moves.urllib.parse import urlunparse ...
return self._walk(value, *args, **kwargs) def _walk_item(self, value, *args, **kwargs): return value def get_path_if_relative(url): parts = urlparse(url) if parts.scheme or parts.netloc: # only rewrite relative paths
return if not parts.path: # don't rewrite internal refs return if parts.path.startswith('/'): # don't rewrite absolute refs return return parts class NodeWalkerForRefFiles(NodeWalker): def walk(self, spec): all_refs = [] spec_fname = spec.orig...
phonnz/azure-storage-python
tests/test_storage_queue.py
Python
apache-2.0
26,556
0.000415
# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft. 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 #...
try: self.qs.delete_queue(queue_name) except: pass return super(StorageQueueTest, self).tearDown() def _get_shared_access_policy(self, permission): date_format = "%Y-%m-%dT%H:%M:%SZ" start = datetime.datetime.utcnow() - datetime.timed...
jhemmi/QgisDiffPlugin
resources_rc.py
Python
cc0-1.0
2,620
0.001908
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt (Qt v4.8.5) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x01\x82\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\...
b\xef\x63\xc8\xc3\xc0\x01\xd7\x3d\xff\x3f\x5c\x7d\ \x8f\x93\xcf\x82\xcd\x45\xee\x97\x7d\x18\x7e\x7f\xf9\xcd\xf0\xf1\ \xf2\x07\x86\x6b\x4d\x97\x18\x18\x19\x19\x19\x64\x43\xe5\xe1\x72\ \x30\xf0\xe3\xc5\x77\x06\x7e\x2d\x01\x9c\x7c\x46\xf4\x74\xbe\x53\ \x77\x0b\x8a\x01\xaf\x0f\xbf\x62\xb8\x35\xe1\x3a\x83\xf5\x5a\x7b\ \x14\...
\xa3\x2d\x58\xe5\xd1\xd5\xa2\xf3\x07\x36\xb5\x7c\xb8\ \xf8\x81\x81\x5b\x81\x87\x2c\xc3\x59\x70\x49\xfc\xf9\xfa\x9b\xe1\ \xc3\xe5\x0f\x0c\xd7\xdb\x2e\x33\x28\x26\xa9\x50\xcf\xf0\x9d\xba\ \x5b\x18\x18\x59\x19\x19\xb8\x15\x78\x18\x14\x12\x95\xe1\x29\x85\ \x54\xc0\x38\x5a\x2a\x8e\x1a\x3e\x6a\x38\x65\x00\x00\xfa\x0b\xec\ \x...
eqrx/mauzr
mauzr/hardware/tsl2561/controller.py
Python
agpl-3.0
1,735
0
""" Controller for tsl2561 devices. """ import mauzr from mauzr.serializer import Struct as SS __author__ = "Alexander Sowitzki" FMAP = ((0, 0, 0), (0x40, 0x01f2, 0x01be), (0x80, 0x214, 0x2d1), (0xc0, 0x23f, 0x37b), (0x0100, 0x270, 0x3fe), (0x0138, 0x16f, 0x1fc), (0x019a, 0xd2, 0xfb), (0x29a, 0x18, 0...
:type cfgbase
: str :param kwargs: Keyword arguments that will be merged into the config. :type kwargs: dict """ cfg = core.config[cfgbase] cfg.update(kwargs) mqtt = core.mqtt base = cfg["base"] log = core.logger("<TSL2561@{}>".format(base)) mqtt.setup_publish(base + "illuminance", SS("!f"), 0) ...
fnoble/libsbp
python/sbp/__init__.py
Python
lgpl-3.0
4,591
0.053365
#!/usr/bin/env python # Copyright (C) 2011-2014 Swift Navigation Inc. # Contact: Fergus Noble <fergus@swiftnav.com> # # This source is subject to th
e license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, # EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. import base64 impor...
erdc/proteus
proteus/tests/BernsteinPolynomials/poisson_eqn/poisson_p.py
Python
mit
3,313
0.026864
from __future__ import absolute_import from __future__ import division from builtins import object from past.utils import old_div from proteus import * from proteus.default_p import * i
mport os try: from .parameters_for_poisson import * except: from parameters_for_poisson import * name = "poisson" assert ct.nd==2 or ct.nd==3, "Choose nd=2, or 3" nd = ct.nd initialConditions = None ########
## # DOMAIN # ########## nn=(2**ct.refinement)*10+1 he=old_div(1.0,(nn-1.0)) if (nd==2): box=Domain.RectangularDomain(L=(1.0,1.0), x=(0.0,0.0), name="box"); else: nn=5 he=old_div(1.0,(nn-1.0)) box=Domain.RectangularDomain(L=(1.0,1.0,1.0),...
sanderator/lab-o-matic
src/lab_o_matic/decryptor.py
Python
gpl-2.0
731
0
''' Created on Feb 6, 2011 Decrypts student exa
m submi
ssion file. author: (c)2011-2015 Peter Sander ''' import os.path import subprocess def decrypt(paths, decryption_key): ''' Decrypts submitted file. ''' result = False student = os.path.basename(paths['student']) exam_file = paths['student'] + '/examenPOO_' + student + '.tgz.cpt' if os.pa...
yupengyan/scrapy-webdriver
scrapy_webdriver/tests/test_request_queue.py
Python
mit
3,272
0
from functools import partial from time import sleep from mock import call, Mock from scrapy.crawler import Crawler from scrapy.http import Request from scrapy import log, signals from scrapy.settings import Settings from scrapy.spider import BaseSpider from scrapy.xlib.pydispatch import dispatcher from twisted.intern...
PIDER_MIDDLEWARES={ 'scrapy_webdriver.middlewares.WebdriverSpiderMiddleware': 543, }) class TestRequestQueue: @classmethod def setup_class(cls): cls._settings = BASE_SE
TTINGS def settings(self, **options): settings = self._settings.copy() settings.update(**options) return settings def _stop_reactor(self): reactor.stop() def _wait(self, url, *args, **kwargs): sleep(0.1) def test_priorization(self): webdriver = Mock() ...
grepme/CMPUT410Lab01
virt_env/virt1/lib/python2.7/site-packages/waitress-0.8.9-py2.7.egg/waitress/tests/test_channel.py
Python
apache-2.0
24,675
0.000811
import unittest import io class TestHTTPChannel(unittest.TestCase): def _makeOne(self, sock, addr, adj, map=None): from waitress.channel import HTTPChannel server = DummyServer() return HTTPChannel(server, sock, addr, adj=adj, map=map) def _makeOneWithMap(self, adj=None): if a...
inst.write_soo
n(b'') self.assertEqual(wrote, 0) self.assertEqual(len(inst.outbufs[0]), 0) def test_write_soon_nonempty_byte(self): inst, sock, map = self._makeOneWithMap() wrote = inst.write_soon(b'a') self.assertEqual(wrote, 1) self.assertEqual(len(inst.outbufs[0]), 1) def t...
openstack/glance
glance/cmd/cache_prefetcher.py
Python
apache-2.0
1,880
0.002128
#!/usr/bin/env python # Cop
yright 2011-2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # #
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language go...
jkyeung/XlsxWriter
xlsxwriter/test/comparison/test_chart_chartarea02.py
Python
bsd-2-clause
1,825
0
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """...
et1!$C$1:$C$5'}) chart.set_chartarea({ 'border': {'none': 1},
'fill': {'color': 'red'} }) chart.set_plotarea({ 'border': {'color': 'yellow', 'width': 1, 'dash_type': 'dash'}, 'fill': {'color': '#92D050'} }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
BIDS-collaborative/EDAM
data/brian/predict.py
Python
bsd-2-clause
15,980
0.018648
import pandas as pd import sklearn import sklearn.metrics as metrics import numpy as np import scipy import matplotlib import matplotlib.pyplot as plt import scipy.stats as stats from sklearn import cluster from sklearn.linear_model import LogisticRegression as LR from sklearn.ensemble import RandomForestC...
np.isnan(X)) X[inds]=np.take(col_mean,inds[1]) RF = RFC(n_estimators = 100, criterion = "e
ntropy") X_train, X_test, y_train, y_test = chooseRandom(X, y) RF.fit(X_train, y_train) return RF.score(X_test, y_test) def predictGBC(X, y): col_mean = np.nanmean(X,axis=0) inds = np.where(np.isnan(X)) X[inds]=np.take(col_mean,inds[1]) gbc = GBC(n_estimators = 100) X_train, X_test, y_train, y...
siosio/intellij-community
python/testData/intentions/convertingRawFStringQuotes_after.py
Python
apache-2.0
26
0
s
= rf"f<caret>oo{'bar'}"
joelfrederico/SciSalt
scisalt/facettools/ui_logbookForm.py
Python
mit
9,229
0.0026
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_logbookForm.ui' # # Created: Wed Jun 25 14:54:33 2014 # by: PyQt4 UI code generator 4.10.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except...
) self.textLayout.setSpacing(0) self.textLayout.setObjectName(_fromUtf8("textLayout")) self.textLabel = QtGui.QLabe
l(logbookForm) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.textLabel.sizePolicy().hasHeightForWidth()) self.textLabel.setSizePolicy(sizePolic...
PythonCharmers/orange3
Orange/tests/test_txt_reader.py
Python
gpl-3.0
1,539
0.00065
import unittest from tempfile import NamedTemporaryFile import os import numpy as np from Orange.data import ContinuousVariable, DiscreteVariable from Orange.data.io import CSVFormat tab_file = """\ Feature 1\tFeature 2\tFeature 3 1.0 \t1.3 \t5 2.0 \t42 \t7 """ csv_file = """\ Feature 1, F...
f1, f2, f3 = table.domain.variables self.assertIsInstance(f1, DiscreteVariable) self.assertEqual(f1.name, name + "1") self.assertIsInstance(f2, ContinuousVariable) self.assertEqual(f2.name, name + "2") self.assertIsInstance(f3, ContinuousVariable) ...
self.read_easy(tab_file, "Feature ") self.read_easy(tab_file_nh, "Feature ") def test_read_csv(self): self.read_easy(csv_file, "Feature ") self.read_easy(csv_file_nh, "Feature ")
nikolay-fedotov/tempest
tempest/cmd/run_stress.py
Python
apache-2.0
4,985
0.000201
#!/usr/bin/env python # Copyright 2013 Quanta Research Cambridge, 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 # # U...
l_inherited=ns.call_inherited) if ns.serial: # Duration is total time duration = ns.duration / len(tests) for test in tests: step_result = driver.stress_openstack([test], duration, ...
if (step_result != 0): result = step_result if ns.stop: return result else: result = driver.stress_openstack(tests, ns.duration, ns.number, ...
wubr2000/googleads-python-lib
examples/adwords/v201502/optimization/estimate_keyword_traffic.py
Python
apache-2.0
4,307
0.00534
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
ds.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Api: AdWordsOnly """ from googleads import adwords def main(client): # Initialize appropriate service. traffic_estimator_service = client.GetServic...
ords = [ {'text': 'mars cruise', 'matchType': 'BROAD'}, {'text': 'cheap cruise', 'matchType': 'PHRASE'}, {'text': 'cruise', 'matchType': 'EXACT'} ] negative_keywords = [ {'text': 'moon walk', 'matchType': 'BROAD'} ] keyword_estimate_requests = [] for keyword in keywords: keyword_es...
eduNEXT/edunext-ecommerce
ecommerce/referrals/migrations/0003_auto_20161027_1738.py
Python
agpl-3.0
700
0.005714
# -*- coding: utf-8 -*- """ This migration exists to fix the error introduced by https://github.com/edx/ecommerce/pull/9
68. The 0002 migration has been updated to
setup the site column correctly for new installations. This migration ensures installations that previously ran 0002 have the column setup correctly. """ from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('referrals', '0002_auto_20161011_1728'), ] ...
quom/google-cloud-python
bigquery/google/cloud/bigquery/__init__.py
Python
apache-2.0
1,261
0
# Copyright 2015 Google 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 l
aw or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google BigQuery API wrapper. The...
DONIKAN/django
tests/admin_inlines/tests.py
Python
bsd-3-clause
44,045
0.004087
from __future__ import unicode_literals import datetime import warnings from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests
import AdminSeleniumWebDriverTestCase from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.test import RequestFactory, TestCase, override_settings from django.utils.encoding import force_text from .ad...
site as admin_site from .models import ( Author, BinaryTree, Book, Chapter, Child, ChildModel1, ChildModel2, Fashionista, FootNote, Holder, Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stacked, Inner4Tabular, Novel, OutfitItem, Parent, ParentModelWithCustomPk, Person, Poll, Profile, ProfileC...
upul/Aurora
aurora/autodiff/autodiff.py
Python
apache-2.0
21,346
0.001124
import numpy as np try: from aurora.ndarray import gpu_op, ndarray except ImportError: pass class Node(object): """ Node object represents a node in the computational graph""" def __init__(self): """ New node will be created by Op objects __call__ method""" # list of inputs to this no...
nodeB: RHS operand Returns ------- :return: A new Node which represents the element-wise plus operation """ new_node = Op.__call__(self) new_node.inputs = [nodeA, nodeB] new_node.name = '({}+{})'.format(nodeA.name, nodeB.name) return new_node
def compute(self, node, input_vals, output_val, use_numpy=True): """ Given values of two input nodes, return result of element-wise addition. Parameters ---------- :param node: :param input_vals: List of two input nodes Returens -------- :return...
Ntcha/tools
mount_ftp.py
Python
mit
1,898
0.005796
#!/usr/bin/python """This module allows the use of a remote ftp as a local mountpoint""" import sys, os, urllib, logging, signal, time from fs import ftpfs from fs.errors import PermissionDeniedError, RemoteConnectionError from fs.expose import fuse def mount_ftp(ftpaddress, mountpoint, login=None, password=None): ""...
connection & mount are successful, spawn a new thread to
handle the mount""" try: ftp_fs = ftpfs.FTPFS(ftpaddress, user=login, passwd=password) except RemoteConnectionError: logging.error( 'Unable to connect: %s is not reachable' % ftpaddress) sys.exit(1) except PermissionDeniedError: logging.error( 'Unable to connect: credentials ...
softelnet/sponge
sponge-jython/examples/script/py/unordered_rules.py
Python
apache-2.0
3,372
0.008304
""" Sponge Knowledge Base Using unordered rules """ from java.util.concurrent.atomic import AtomicInteger from org.openksavi.sponge.examples import SameSourceJavaUnorderedRule from org.openksavi.sponge.core.library import Deduplication def onInit(): # Variables for assertions only sponge.setVariabl...
stemFailure e1", "diskFailure e2 :all"]).withOrdered(False) self.withCondition("e1", self.severityCondition) self.withConditions("e2", [self.severityCondition, self.diskFailureSourceCondition]) self.withDuration(Duration.ofSeconds(5)) def onRun(self, event): self.logger.info("Mo...
riable("hardwareFailureScriptCount").incrementAndGet() def severityCondition(self, event): return int(event.get("severity")) > 5 def diskFailureSourceCondition(self, event): # Both events have to have the same source return event.get("source") == self.firstEvent.get("source") and \ ...
openhumanoids/exotica
exotica_examples/setup.py
Python
bsd-3-clause
317
0.003155
## !
DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup # fetch values from package.xml setup_args = generate_distutils_setup( packages=['exotica_examples_py'], package_dir={'': 'src'}) setup(**setup_ar
gs)
INM-6/elephant
elephant/gpfa/gpfa_core.py
Python
bsd-3-clause
20,866
0
# -*- coding: utf-8 -*- """ GPFA core functionality. :copyright: Copyright 2014-2020 by the Elephant team, see AUTHORS.txt. :license: Modified BSD, see LICENSE.txt for details. """ from __future__ import division, print_function, unicode_literals import time import warnings import numpy as np import scipy.linalg as...
fault: 20.0 min_var_frac : float, optional fraction of ov
erall data variance for each observed dimension to set as the private variance floor. This is used to combat Heywood cases, where ML parameter learning returns one or more zero private variances. Default: 0.01 (See Martin & McDonald, Psychometrika, Dec 1975.) em_tol : float, optiona...
atiqueahmedziad/addons-server
src/olympia/addons/serializers.py
Python
bsd-3-clause
32,770
0
import re from django.conf import settings from rest_framework import exceptions, serializers from olympia import amo from olympia.accounts.serializers import BaseUserSerializer from olympia.amo.templatetags.jinja_helpers import absolutify from olympia.amo.urlresolvers import get_outgoing_url, reverse from olympia.a...
s) def get_url(self, obj): return absolutify(obj.get_url_path()) class SimpleESVersionSerializer(SimpleVersionSerializer): class Meta: model = Version # In ES, we don't have license and release notes info, so instead of # returning null, which is not necessarily true, we omit ...
, 'reviewed', 'url', 'version') class VersionSerializer(SimpleVersionSerializer): channel = ReverseChoiceField(choices=amo.CHANNEL_CHOICES_API.items()) license = LicenseSerializer() class Meta: model = Version fields = ('id', 'channel', 'compati
tkerola/chainer
tests/chainer_tests/functions_tests/array_tests/test_resize_images.py
Python
mit
6,159
0
import unittest import numpy from chainer.backends import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'in_shape': [(2, 3, 8, 6), (2, 1, 4, 6)], })) @testing.i
nject_backend_tests( None, # CPU tests [ {}, ] # GPU tests + testing.product({ 'use_cuda': [True],
'use_cudnn': ['never', 'always'], 'cuda_device': [0, 1], }) # ChainerX tests + testing.product({ 'use_chainerx': [True], 'chainerx_device': ['native:0', 'cuda:0', 'cuda:1'], }) ) class TestResizeImagesForwardIdentity(testing.FunctionTestCase): def generate_inputs(sel...
eirmag/weboob
modules/freemobile/pages/login.py
Python
agpl-3.0
5,012
0.003795
# -*- coding: utf-8 -*- # Copyright(C) 2012 Florent Fourcot # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your o...
fichier = basepage.browser.openurl(url) image = Image.open(fichier) matrix = image.load() s = "" # The digit is only displayed in the center of image for x in rang
e(15, 23): for y in range(12, 27): (r, g, b) = matrix[x, y] # If the pixel is "red" enough if g + b < 450: s += "1" else: s += "0" self.fingerprints.append(s) ...
kickstandproject/asterisk-testsuite-temporary
lib/python/qm.py
Python
gpl-2.0
7,358
0.011824
#!/usr/bin/env python """ This class implements the Quine-McCluskey algorithm for minimization of boolean functions. Based on code from Robert Dick <dickrp@eecs.umich.edu> and Pat Maupin <pmaupin@gmail.com>. Most of the original code was re-written for performance reasons. NOTE: The author stated that this code was ...
_covers[j] elif x > new_covers[j]: append = False if append: new_covers.append(x) covers = new_covers min_complexity = 99999999 for cover in covers: primes_in_cover = [primes[prime_index] for prime_index in cover] complexity = self.calculate_com...
culate_complexity(self, minterms): """ Calculate the complexity of the given function. The complexity is calculated based on the following rules: A NOT gate adds 1 to the complexity. A n-input AND or OR gate adds n to the complexity. minterms: a list of minterms that form the function ...
cragwen/hello-world
py/practise/impa.py
Python
unlicense
93
0.053763
import impb a = 3 def fa(): print(a)
if __name__ == "
__main__": fa() print(__name__)
EdwinvO/django_keyval
django_keyval/wsgi.py
Python
agpl-3.0
1,440
0.000694
""" WSGI config for django_keyval project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` a
nd ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a
custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_w...
socialsensor/public-figure-image-ranking
python/mainStaticPersonTask.py
Python
apache-2.0
5,159
0.015895
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: # Purpose: This .py file is the main Framework file # It ranks images of a specific person of interest in a static manner # # Required libs: python-dateutil, numpy...
es for "+person)
if decisionforAll == str('n') or personDecision == str('y'): dataStatic.photoRetrieval(topImages, person, captiondict,decisionforAll) dataStatic.popularity_coappearence(topImages, person, captiondict) elapsed = time.time() - t print('\nStage 3: %.2f seconds' % elapsed)
google-research/rigl
rigl/experimental/jax/models/mnist_fc.py
Python
apache-2.0
5,359
0.005225
# coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may n
ot use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the
License is 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. # Lint as: python3 """MNIST Fully-Connected Neural Network. A fully-connected model for the MNI...
jkhelil/kubernetes
hack/boilerplate/boilerplate.py
Python
apache-2.0
6,153
0.003413
#!/usr/bin/env python # Copyright 2015 The Kubernetes 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 appli...
the boilerplate, but shouldn't in the real thing regexs["year"] = re.compile( 'YEAR' ) # dates can be 2014, 2015 or 2016, company holder names can be anything regexs["date"] = re.compile( '(2014|2015|2016)' ) # strip // +build \n\n build constraints regexs["go_build_constraints"] = re.compile(r"^(/...
exs def main(): regexs = get_regexs() refs = get_refs() filenames = get_files(refs.keys()) for filename in filenames: if not file_passes(filename, refs, regexs): print(filename, file=sys.stdout) return 0 if __name__ == "__main__": sys.exit(main())
nrc/rustc-perf
collector/benchmarks/cranelift-codegen/cranelift-codegen/meta-python/cdsl/ti.py
Python
mit
28,415
0.000211
""" Type Inference """ from .typevar import TypeVar from .ast import Def, Var from copy import copy from itertools import product try: from typing import Dict, TYPE_CHECKING, Union, Tuple, Optional, Set # noqa from typing import Iterable, List, Any, TypeVar as MTypeVar # noqa from typing import cast fr...
class SameWidth(TypeConstraint): """ Constraint specifying that two types have the same width. E.g. i32x2 has the same width as i64x1, i16x4, f32x2, f64, b1x64 etc. """ def __init__(self, tv1, tv2): # type: (TypeVar, TypeVar) -> None self.tv1 = tv1
self.tv2 = tv2 def _args(self): # type: () -> Tuple[Any,...] """ See TypeConstraint._args() """ return (self.tv1, self.tv2) def is_trivial(self): # type: () -> bool """ See TypeConstraint.is_trivial() """ # Trivially true if (self.tv1 == self.tv2...
Weihonghao/ECM
Vpy34/lib/python3.5/site-packages/theano/compile/nanguardmode.py
Python
agpl-3.0
12,284
0.000407
from __future__ import absolute_import, print_function, division import collections import logging from six.moves import StringIO import numpy as np import theano from theano.configparser import config import theano.tensor as T import theano.sandbox.cuda as cuda from theano.compile import Mode from .mode import get_m...
_input], T.min(guard_input), mode='FAST_RUN
' ) except RuntimeError: # This can happen if cuda is available, but the # device is in exclusive mode and used by another # process. cuda_compile_failed = True if inf_is_error and not cuda_compile_failed and f_gpumax is None: try: ...
jbalogh/zamboni
apps/perf/urls.py
Python
bsd-3-clause
160
0.00625
fr
om django.conf.urls.defaults import patterns, url, include from . import views urlpatterns = patterns('', url('^$', views.index, name='perf.i
ndex'), )
seccomp/libseccomp
tests/15-basic-resolver.py
Python
lgpl-2.1
1,558
0.001284
#!/usr/bin/env python # # Seccomp Library test program # # Copyright (c) 2012 Red Hat <pmoore@redhat.com> # Author: Paul Moore <paul@paul-moore.com> # # # This library is free software; you can redistribute it and/or modify it # under the terms of version 2.1 of the GNU Lesser General Public License as # published by...
details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, see <http://www.gnu.org/licenses>. # import argparse import sys import util from seccomp import * def test(): f = SyscallFilter(KILL) # this differs from the native test as we don't suppo...
resolution functions by themselves f.add_rule(ALLOW, "open") f.add_rule(ALLOW, "read") try: f.add_rule(ALLOW, "INVALID") except RuntimeError: pass sys_num = resolve_syscall(Arch(), "open") sys_name = resolve_syscall(Arch(), sys_num) if (sys_name != b"open"): raise Ru...
moschlar/SAUCE
sauce/controllers/crc/selectors.py
Python
agpl-3.0
3,164
0.001896
''' @since: 2015-01-07 @author: moschlar ''' import sqlalchemy.types as sqlat import tw2.core as twc import tw2.bootstrap.forms as twb import tw2.jqplugins.chosen.widgets as twjc import sprox.widgets.tw2widgets.widgets as sw from sprox.sa.widgetselector import SAWidgetSelector from sprox.sa.validatorselector import ...
r, } # def select(self, field): # print 'MyValidatorSelector', 'select', field # return
super(MyValidatorSelector, self).select(field)
beeftornado/sentry
tests/sentry/event_manager/test_normalization.py
Python
bsd-3-clause
6,199
0.001613
from __future__ import absolute_import import pytest import logging from datetime import datetime from django.conf import settings from sentry.constants import MAX_CULPRIT_LENGTH, DEFAULT_LOGGER_NAME from sentry.event_manager import EventManager def make_event(**kwargs): result = { "event_id": "a" * 32...
(), CanonicalKeyDict) @pytest.mark.parametrize("environment", ["", None, "production"]) def test_environment_tag_removed(environment): event = make_event()
event["environment"] = environment event["tags"] = {"environment": "production"} manager = EventManager(event) manager.normalize() data = manager.get_data() assert "environment" not in dict(data.get("tags") or ()) assert data["environment"] == "production"
coolbreeze000/rpgine
rpgine_core/persistence/__init__.py
Python
apache-2.0
23
0
__aut
hor__ = 'Domi
nik'
daonb/tumulus
tumuli/wsgi.py
Python
agpl-3.0
389
0
""" WSGI co
nfig for tumuli project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE",...
) application = get_wsgi_application()
mcallistersean/b2-issue-tracker
toucan/notifications/apps.py
Python
mit
108
0
from
django.apps import AppConfig class NotificationsConfig(AppConfig): name = 'toucan.
notifications'
morganelle/pyramid-learning-journal
learning_journal/learning_journal/models/entries.py
Python
mit
365
0
from sqlalch
emy import ( Column, Integer, Unicode, DateTime ) from .meta import Base class JournalEntry(Base): """Journal entry model base class.""" __tablename__ = 'journal' id = Column(Integer, primary_key=True) title = Column(Unicode) body = Column(Unicode) author = Column(Unicode) ...
me)
zsloan/genenetwork2
wqflask/utility/helper_functions.py
Python
agpl-3.0
2,498
0.0004
from base import data_set from base.trait import create_trait from base.species import TheSpecies from utility import hmac from flask import g import logging logger = logging.getLogger(__name__) def get_species_dataset_trait(self, start_vars): if "temp_trait" in list(start_vars.keys()): if start_vars['...
t_ob = data_set.create_dataset(dataset_name) trait_ob = create_trait(dataset=dataset_ob, name=trait_name, cellid=None) if trait_ob: self.trait_list.append((trait_ob, dat
aset_ob)) def get_species_groups(): """Group each species into a group""" _menu = {} for species, group_name in g.db.execute( "SELECT s.MenuName, i.InbredSetName FROM InbredSet i " "INNER JOIN Species s ON s.SpeciesId = i.SpeciesId " "ORDER BY i.SpeciesId ASC, i.Name A...
fspaolo/mpisubmit
mpi-submit2.py
Python
bsd-3-clause
3,645
0.005213
#!/usr/bin/env python """ For basic applications, MPI is as easy to use as any other message-passing system. The sample code below contains the complete communications skeleton for a dynamically load balanced master/slave application. Following the code is a description of the few functions necessary to write typic...
# any type of message (-1) status=status) # info about the received msg (class) # Send the slave a new work unit comm.send(work, # message buffer dest=status.Get_source(), # to whom we just received from tag=WORKTAG) # u
ser chosen message tag """ # Fernandoo Paolo <fpaolo@ucsd.edu> # Jan 15, 2013 import os import sys import numpy as np from mpi4py import MPI from Queue import Queue WORKTAG = 1 DIETAG = 2 class Work(object): def __init__(self, prog, files): # importat: sort by file size in decreasing order! file...
jwodder/javaproperties
src/javaproperties/propclass.py
Python
mit
8,167
0.000245
from collections.abc import Mapping as MappingABC from typing import ( Any, BinaryIO, Dict, IO, Iterable, Iterator, Mapping, MutableMapping, Optional, Set, TextIO, Tuple, TypeVar, Union, ) from .reading import load from .writing import dump from .xmlprops import d...
:param Optional[str] comments: If non-`None`, ``comments`` will be
written to ``out`` as a comment before any other content :return: `None` """ dump(self.data, out, comments=comments) def stringPropertyNames(self) -> Set[str]: r""" Returns a `set` of all keys in the `Properties` instance and its `defaults` (and its `defaults`\ ’s `d...
StevenVanAcker/mitmproxy
mitmproxy/addons/save.py
Python
mit
2,873
0.001044
import os.path import typing from mitmproxy import exceptions from mitmproxy import flowfilter from mitmproxy import io from mitmproxy import ctx from mitmproxy import flow class Save: def __init__(self): self.stream = None self.filt = None self.active_flo
ws = set() # type: Set[flow.Flow] def open_file(self, path): if path.startswith("+"):
path = path[1:] mode = "ab" else: mode = "wb" path = os.path.expanduser(path) return open(path, mode) def start_stream_to_path(self, path, flt): try: f = self.open_file(path) except IOError as v: raise exceptions.OptionsError(...
jeromecc/doctoctocbot
src/moderation/migrations/0045_auto_20200323_0056.py
Python
mpl-2.0
965
0
# Generated by Django 2.2.10 on 2020-03-22 23:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('moderation', '0044_categorymetadata'), ] operations = [ migrations.AddField( model_name='categorymetadata', name='d...
en', field=models.TextField(blank=True, null=True), ), migrations.AddField( model_name='categorymetadata', name='description_fr', field=models.TextField(blank=True, null=True), ), migrations.AddField( model_name='categorymetadat
a', name='label_en', field=models.CharField(max_length=255, null=True, unique=True), ), migrations.AddField( model_name='categorymetadata', name='label_fr', field=models.CharField(max_length=255, null=True, unique=True), ), ]
pescobar/easybuild-framework
easybuild/toolchains/gcccuda.py
Python
gpl-2.0
1,443
0.001386
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flem
ish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publi
c License as published by # the Free Software Foundation v2. # # EasyBuild is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should hav...
KrzysiekJ/bestja
addons/bestja_application_moderation/__openerp__.py
Python
agpl-3.0
720
0
# -*- co
ding: utf-8 -*- { 'name': "BestJa: Application Moderation", 'summary': "Two stage recruitment process", 'description': """ BestJa Application Moderation ============================= Split recruitment process into two separate stages. The first ("preliminary") stage is handled by offer moderators. The sec...
", 'version': '0.1', 'depends': [ 'base', 'bestja_offers', 'bestja_offers_moderation', ], 'data': [ 'views/offer.xml', 'menu.xml', 'messages.xml', 'security/security.xml', ], }
gboeing/osmnx
osmnx/truncate.py
Python
mit
6,740
0.000593
"""Truncate graph by distance, bounding box, or polygon.""" import networkx as nx from . import utils from . import utils_geo from . import utils_graph def truncate_graph_dist(G, source_node, max_dist=1000, weight="length", retain_all=False): """ Remove every node farther than some network distance from sou...
d on to intersect_index_quadrats: the linear length (in degrees) of the quadrats with which to cut up the geometry (default = 0.05, approx 4km at NYC's latitude) min_num : int passed on to intersect_index_quadrats: the minimum number of linear
quadrat lines (e.g., min_num=3 would produce a quadrat grid of 4 squares) Returns ------- G : networkx.MultiDiGraph the truncated graph """ # convert bounding box to a polygon, then truncate polygon = utils_geo.bbox_to_poly(north, south, east, west) G = truncate_graph_poly...
prakritish/ansible
lib/ansible/cli/adhoc.py
Python
gpl-3.0
8,021
0.004488
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.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 Genera
l Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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...
nses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type ######################################################## import os from ansible import constants as C from ansible.cli import CLI from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.executor.task_qu...
mschex1/pokedex
pokedex/main.py
Python
mit
10,768
0.002137
# encoding: utf8 from __future__ import print_function import argparse import os import sys import pokedex.cli.search import pokedex.db import pokedex.db.load import pokedex.db.tables import pokedex.lookup from pokedex import defaults def main(junk, *argv): if len(argv) <= 0: command_help() retu...
'Find thi
ngs by various criteria', parents=[common_parser]) pokedex.cli.search.configure_parser(cmd_search) cmd_load = cmds.add_parser( 'load', help=u'Load Pokédex data into a database from CSV files', parents=[common_parser]) cmd_load.set_defaults(func=command_load, verbose=True) # TODO...
ychen820/microblog
y/google-cloud-sdk/bin/bootstrapping/gsutil.py
Python
bsd-3-clause
2,135
0.009836
#!/usr/bin/env python # # Copyright 2013 Google Inc. All Rights Reserved. # """A convenience wrapper for starting gsutil.""" import os import sys import bootstrapping from googlecloudsdk.core import config from googlecloudsdk.core.credentials impor
t gce as c_gce def main(): """Launches gsutil.""" project, account = bootstrapping.GetActiveProjectAndAccount() if account not in c_gce.Metadata().Accounts(): gsutil_path = config.Paths().LegacyCredentialsGSUtilPath(account) boto_config = os.environ.get('BOTO_CONFIG', None) boto_path = os.environ...
to_path = ':'.join([boto_config, gsutil_path]) elif boto_path: # this is ':' for windows as well, hardcoded into the boto source. boto_path = ':'.join([boto_path, gsutil_path]) else: path_parts = ['/etc/boto.cfg', os.path.expanduser(os.path.join('~', '.boto')), ...
reclosedev/lathermail
lathermail/smtp.py
Python
mit
3,815
0.002097
#!/usr/bin/env python # -*- coding: utf-8 -*- import email import smtpd import asyncore import logging import socket import base64 from lathermail.compat import bytes log = logging.getLogger(__name__) class SMTPChannelWithAuth(smtpd.SMTPChannel, object): def __init__(self, server, conn, addr, on_close=lambda s...
xception: log.exception("Failed to process message:") def _on_channel_close(self, peer): self._channel_by_peer.pop(peer, None) log.info
("Remove channel for peer: %s. Active channels: %s", peer, len(self._channel_by_peer)) def serve_smtp(host="127.0.0.1", port=10252, handler=None): if handler is None: def handler(to, sender, *args): print("{0} <- {1}".format(to, sender)) InboxServer((host, port), handler) log.info("R...
jsmesami/naovoce
src/user/api/token_auth/urls.py
Python
bsd-3-clause
205
0
from django.conf.urls import url from .views import GetAuthToken, GetAuthTokenFacebook urlpatterns = [
url(r'^$', GetAuthToken.as_view()), url(r'^facebook/$', GetA
uthTokenFacebook.as_view()), ]
blckshrk/Weboob
modules/750g/backend.py
Python
agpl-3.0
2,151
0.00186
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
).encode('utf-8')) def fill_recipe(self, recipe, fields): if 'nb_person' in fields or 'instructions' in fields: rec = self.get_
recipe(recipe.id) recipe.picture_url = rec.picture_url recipe.instructions = rec.instructions recipe.ingredients = rec.ingredients recipe.comments = rec.comments recipe.author = rec.author recipe.nb_person = rec.nb_person recipe.cooking...
ChainsAutomation/chains
lib/chains/reactor/config.py
Python
gpl-2.0
5,682
0.000352
from __future__ import absolute_import from __future__ import print_function from chains.common.config import CoreConfig from chains.common import ParameterException, ChainsException, log, utils import os config = CoreConfig() # todo: tests # todo: cleanup def enable(rule): if not rule: raise ParameterE...
s.path: if f == d: return # already set sys.path.append(d) def _makeDirWithInitFile(p): if not os.path.exists(p): os.makedirs(p) initf = '%s/__init__.py' % p if not os.path.exists(initf): with open(initf, 'w') as fp: fp.write('') def _dirRules(dir): ...
tmp = f.split('.') ext = tmp.pop() if ext != 'py': continue ret.append('.'.join(tmp)) return ret class NoSuchRuleException(ChainsException): pass class RuleAlreadyEnabledException(ChainsException): def __init__(self, rule): ChainsException.__init__(sel...
RaspPiTor/JAPTT
XSS/xssencode.py
Python
mit
1,283
0.024162
import random def randomurl(): chars='abcdefghijklmnopqrstuvwxyz' length=random.randint(5, 20) choice=random.choice return ''.join(choice(chars) for i in range(length))
+'.com' def xssencode(javascript): javascript2='eval(String.fromCharCode(%s))' % ','.join(str(ord(i)) for i in javascript) for js in [javascript, javascript2]: options=['<script>{}</script>
', '<a onmouseover="{}">%s</a>' % (' '*random.randint(0, 250)), '<dev onmouseover="{}">%s</dev>' % (' '*random.randint(0, 250)), '<span onmouseover="{}">%s</span>' % (' '*random.randint(0, 250)), '<img onmouseover="{}" src="#"/>', '<img onmouseover="{}"/>', '<img on...
indictranstech/focal-erpnext
selling/doctype/lead/test_lead.py
Python
agpl-3.0
697
0.014347
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Lead') class TestLead(unittest.TestCase): def test_make_customer(self): f...
self.assertEquals(customer.doctype, "Customer") self.assertEquals(customer.lead_name, "_T-Lead-00001") customer.company = "_Test Company" customer.customer_group
= "_Test Customer Group" customer.insert()
nondanee/sousenkyo-auto
2017/formatscript.py
Python
gpl-3.0
7,489
0.020265
# -*- coding: utf-8 -*- """ Created on Fri Jun 09 10:36:56 2017 @author: Nzix """ import urllib,urllib2,re,datetime,time,random,xlrd,xlwt,os cookie = "" def ticketcheck(membercode,serial_code_1,serial_code_2): timeout = 3 global cookie if type(membercode) is int: membercode = str(memberco...
"http://akb48-sousenkyo.jp/vote.php?membercode=%s&parent=team&parentkey=%s"%(membercode,teamcode) attempt = 0 result = "" proxy = 0 while True: attempt = attempt + 1 if attempt > 3: break headers={} headers["Host"] = "akb48-sousenkyo.jp" headers["U...
ent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" if cookie != "": headers["Cookie"] = cookie access = urllib2.Request(url=link, headers=headers) reconnect = 5 while True: ...
kleisauke/pyvips
pyvips/tests/test_iofuncs.py
Python
mit
2,511
0
# vim: set fileencoding=utf-8 : import unittest import pyvips from .helpers import PyvipsTester class TestIofuncs(PyvipsTester): # test the vips7 filename splitter ... this is very fragile and annoying # code with lots of cases def test_split7(self): def split(path): filename7 = pyvip...
""]], ["c:\\program files\\x:hello", ["c:\\program files\\x", "hello"]], ["C:\\fixtures\\2569067123_aca715a2ee_o.jpg", ["C:\\fixtures\\2569067123_aca715a2ee_o.jpg", ""]] ] for case in cases: self.assertEqualObjec...
im = pyvips.Image.mask_ideal(100, 100, 0.5, reject=True, optical=True) im2 = im.new_from_image(12) self.assertEqual(im2.width, im.width) self.assertEqual(im2.height, im.height) self.assertEqual(im2.interpretation, im.interpretation) self....
zouyapeng/horizon-newtouch
openstack_dashboard/dashboards/admin/instances/views.py
Python
apache-2.0
7,076
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use t...
irect=redirect) def get_initial(self): initial = super(LiveMigrateView, self).get_initial() _object = self.get_object() if _object: current_host = getattr(_object, 'OS-EXT-SRV-ATTR:host', '') initial.update({'instance_id': self.kwargs['instance_id'], ...
) return initial class DetailView(views.DetailView): redirect_url = 'horizon:admin:instances:index'
zsloan/genenetwork2
wqflask/wqflask/db_info.py
Python
agpl-3.0
5,959
0.002014
import http.client import urllib.request import urllib.error import urllib.parse import re from flask import Flask, g from utility.logger import getLogger logger = getLogger(__name__) class InfoPage: def __init__(self, start_vars): self.info = None self.gn_accession_id = None if 'gn_acce...
'group_name': results[5], 'gene_chip_name': results[6], 'geo_platform': results[7], 'avg_method_name': results[8], 'dataset_name': results[9], 'geo_series': results[10], 'publication_title': results[11], 'dataset_status_name': result
s[12], 'dataset_summary': results[13], 'about_cases': results[14], 'about_tissue': results[15], 'about_data_processing': results[16], 'acknowledgement': results[17], 'experiment_design': results[18], 'contributors': results[19], 'citation': results[20], ...
harwee/electrum-xvg-tor
gui/qt/transaction_dialog.py
Python
gpl-3.0
10,558
0.003599
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@gitorious # # 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...
n if is_relevant: if is_mine: if fee is not None: self.amount_label.setText(_("Amount sent:")+' %s'% self.parent.format_amount(-v+fee) + ' ' + self.parent.base_unit()) self.fee_label.set
Text(_("Transaction fee")+': %s'% self.parent.format_amount(-fee) + ' ' + self.parent.base_unit()) else: self.amount_label.setText(_("Amount sent:")+' %s'% self.parent.format_amount(-v) + ' ' + self.parent.base_unit()) self.fee_label.setText(_("Transaction fee")+'...
BTCfork/hardfork_prototype_1_mvf-core
qa/rpc-tests/mvf-core-retarget.py
Python
mit
15,092
0.010403
#!/usr/bin/env python2 # Copyright (c) 2016 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test MVF post fork retargeting # # on node 0, test pure block height trigger at height FORK_BLOCK # from test_f...
self.nodes[0].setmocktime(best_block['time'] + STANDARD_BLOCKTIME) self.nodes[0].generate(1) assert_equal(True, self.is_fork_triggered_on_node(0)) print "Fork triggered successfully (block height %s)" % best_block['height'] # Test fork difficulty reset best_block = self...
"Post-fork difficulty reset success: %.10f %s " % (best_block['difficulty'], best_block['bits']) # use to track how many times the same bits are used in a row prev_block = 0 diffadjinterval = 0 # the first nexttimeblock test phase is cyclical increases of 50 seconds starting from here ...
martinohanlon/BlueDot
examples/click_wheel.py
Python
mit
266
0.011278
from bluedot import BlueDot from signal import pause count = 0 def rotated(rot
ation): global count count += rotation.value print("{} {} {}".format(count, rotation.clockwise, rotation.anti_clockwise)) bd = BlueDot() bd.when_rotated = rotated
pause()
igor-toga/knob2
knob/objects/service.py
Python
apache-2.0
2,894
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 the ...
elete(cls, context, service_id, soft_delete=True): db_api.service_delete(context, service_id, soft_delete) @classmethod def get_all(cls, context): return cls._from_db_objects(context,
db_api.service_get_all(context)) @classmethod def get_all_by_args(cls, context, host, binary, topic): return cls._from_db_objects( context, db_api.service_get_all_by_args(context, host, ...
move-II/horst
test/dbus/thermal.py
Python
gpl-3.0
634
0
#!/usr/bin/env python import dbus import dbus.service import dbus.mainloop.glib import sys class ThermalService(dbus.service.Object): def __init__(self, connection): dbus
.service.Object.__init__(self, connection, "/moveii/thm") @dbus.servic
e.signal(dbus_interface='moveii.thm', signature='s') def thmStateChange(self, state): print state if __name__ == "__main__": dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus() name = dbus.service.BusName('moveii.thm', session_bus) thermal = ThermalService...
willmcgugan/rich
tests/test_inspect.py
Python
mit
12,081
0.000291
import io import sys import pytest from rich import inspect from rich.console import Console skip_py36 = pytest.mark.skipif( sys.version_info.minor == 6 and sys.version_info.major == 3, reason="rendered differently on py3.6", ) skip_py37 = pytest.mark.skipif( sys.version_info.minor == 7 and sys.version...
\n" "│ dict(mapping) -> new dictionary initialized │\n" "│ from a mapping object's │\n" "│ (key, value) pairs │\n" "│ dict(iterable) -> new dictionary initialized │\n" "│ as if via: │\n" ...
"│ d = {} │\n" "│ for k, v in iterable: │\n" "│ d[k] = v │\n" "│ dict(**kwargs) -> new dictionary initialized │\n" "│ with the name=value pairs │\n" "│ ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.3.0/Lib/test/test_inspect.py
Python
mit
87,813
0.001799
import re import sys import types import unittest import inspect import linecache import datetime import collections import os import shutil from os.path import normcase from test.support import run_unittest, TESTFN, DirsOnSysPath from test import inspect_fodder as mod from test import inspect_fodder2 as mod2 # C mo...
self.istest(inspect.ismodule, 'mod') self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory') self.istest(inspect.isgenerator, '(x for x in range(2))') self.istest(inspect.isgeneratorfunction, 'generator_function_example') if hasattr(types, 'MemberDescriptorType')...
.ismemberdescriptor(datetime.timedelta.days)) def test_isroutine(self): self.assertTrue(inspect.isroutine(mod.spam)) self.assertTrue(inspect.isroutine([].count)) def test_isclass(self): self.istest(inspect.isclass, 'mod.StupidGit') self.assertTrue(inspect.isclass(list)) ...
refinery29/chassis
chassis/services/dependency_injection/resolver.py
Python
mit
7,175
0
""" Resolver module """ import six from chassis.services.dependency_injection import ServiceFactory from chassis.util.tree import DependencyNode from chassis.util.tree import DependencyTree class CircularDependencyException(Exception): """ Raised when a circular dependency graph is detected """ def __init__...
self.message = "Circular Depedency Detected: %s" % self.node_path def detect_circle(nodes): """ Wrapper for recursive _detect_circle function """ # Verify nodes and traveled types if not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') dependencies = set(nodes.key...
led=None, path=None): """ Recursively iterate over nodes checking if we've traveled to that node before. """ # Verify nodes and traveled types if nodes is None: nodes = {} elif not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') if depende...
smn/goggles
goggles/warehouse/migrations/0018_profile_username.py
Python
bsd-2-clause
451
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('warehouse', '001
7_auto_20141223_1024'), ] operations = [ migrations.AddField( model
_name='profile', name='username', field=models.CharField(max_length=50, null=True), preserve_default=True, ), ]
nicain/dipde_dev
dipde/internals/connection.py
Python
gpl-3.0
9,914
0.006254
"""Module containing Connection class, connections between source and target populations.""" # Copyright 2013 Allen Institute # This file is part of dipde # dipde 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 Foundatio...
nd, curr_prob in zip(self.delay_inds, self.delay_probs): delay_ind_dict.setdefault(curr_ind, []).append(curr_prob) self.delay_inds = sorted(delay_ind_dict.keys()) self.delay_vals = np.array([self.simulation.dt*ii for ii in self.delay_inds])
self.delay_probs = np.array([np.sum(delay_ind_dict[ii]) for ii in self.delay_inds]) util.assert_probability_mass_conserved(self.delay_probs) max_delay_ind = max(self.delay_inds) self.delay_probability_vector = np.zeros(max_delay_ind+1) self.delay_probability_vector[self.delay...
dims/cinder
cinder/tests/unit/test_pure.py
Python
apache-2.0
112,015
0.000018
# Copyright (c) 2014 Pure Storage, 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 re...
wn": FC_WWNS, "target_lun": 1, "target_discovered": True, "initiator_target_map": INITIATOR_TARGET_MAP, "discard": True, }, } PURE_SNAPSHOT = { "created": "2015-05-27T17:34:33Z", "name": "vol1.snap1", "serial": "8343DFDE2DAFBE40000115E4", "size": 3221225472, "sour...
P = { "hgroups": None, "hosts": None, "name": "pg1", "source": "pure01", "targets": None, "volumes": ["v1"] } PGROUP_ON_TARGET_NOT_ALLOWED = { "name": "array1:replicated_pgroup", "hgroups": None, "source": "array1", "hosts": None, "volumes": ["array1:replicated_volume"], ...
skwashd/python-acquia-cloud
acapi/resources/server.py
Python
mit
338
0
"""Acquia Cloud API server resource. """ from acapi.resources.acquiaresource import AcquiaResource class Server(AcquiaResource): """Acquia Cloud API Server.""" valid_keys = [ "nam
e", "fqdn",
"services", "status", "ami_type", "ec2_region", "ec2_availability_zone", ]
kiith-sa/QGIS
python/plugins/fTools/tools/doMeanCoords.py
Python
gpl-2.0
8,830
0.007588
# -*- coding: utf-8 -*- #----------------------------------------------------------- # # fTools # Copyright (C) 2008-2011 Carson Farmer # EMAIL: carson.farmer (at) gmail.com # WEB : http://www.ftools.ca/fTools.html # # A collection of data management and analysis tools for vector data # #-----------------------------...
rom math import * from ui_frmMeanCoords import Ui_Dialog class Dialog(QDialog, Ui_Dialog): def __init__(self, iface, function): QDialog.__init__(self, iface.mainWindow()) self.iface = iface self.function = function self.setupUi(self) self.updateUi() QObject.connect(s...
("clicked()"), self.outFile) QObject.connect(self.inShape, SIGNAL("currentIndexChanged(QString)"), self.update) self.buttonOk = self.buttonBox_2.button( QDialogButtonBox.Ok ) self.progressBar.setValue(0) self.populateLayers() def populateLayers( self ): layers = ftools_utils...
uclouvain/osis
attribution/views/manage_my_courses/my_teaching_material.py
Python
agpl-3.0
1,622
0.001234
############################################################################## # # OSIS stands for Open Stu
dent Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright...
be) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it...
openstack/python-glanceclient
glanceclient/tests/unit/v2/test_client_requests.py
Python
apache-2.0
3,930
0
# Copyright (c) 2015 OpenStack Foundation # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # 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:/...
for the specific language governing permissions and limitations # under the License. from requests_mock.contrib import fixture as rm_fixture from glanceclient import client from glanceclient.tests.unit.v2.fixtures
import image_create_fixture from glanceclient.tests.unit.v2.fixtures import image_list_fixture from glanceclient.tests.unit.v2.fixtures import image_show_fixture from glanceclient.tests.unit.v2.fixtures import schema_fixture from glanceclient.tests import utils as testutils from glanceclient.v2.image_schema import _BA...
hofmeist/fabm-ihf
testcases/python/fabm_describe_model.py
Python
gpl-2.0
1,716
0.0169
#!/usr/bin/env python import sys import argparse try: import pyfabm except ImportError: print 'Unable to load pyfabm. See https://github.com/fabm-model/code/wiki/python.' sys.exit(1) parser = argparse.ArgumentParser(description='This script lists all state variables, diagnostic variables, conserved quantiti...
n model.bottom_
state_variables: print ' %s = %s (%s)' % (variable.name,variable.long_name,variable.units) print 'Interior diagnostic variables:' for variable in model.bulk_diagnostic_variables: print ' %s = %s (%s)' % (variable.name,variable.long_name,variable.units) print 'Horizontal diagnostic variables:' for variable in ...
somcomltd/django-openid-auth
example_consumer/settings.py
Python
bsd-2-clause
5,789
0.000864
# django-openid-auth - OpenID integration for django.contrib.auth # # Copyright (C) 2007 Simon Willison # Copyright (C) 2008-2013 Canonical Ltd. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions o...
# Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost.
Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE # although not all variations may be po...
aprajshekhar/pulp_packaging
ci/lib/promote.py
Python
gpl-2.0
8,229
0.002187
import re import subprocess import sys def get_promotion_chain(git_directory, git_branch, upstream_name='origin'): """ For a given git repository & branch, determine the promotion chain Following the promotion path defined for pulp figure out what the full promotion path to master is from wherever we...
ry, promotion_chain): """ For a given git repo & promotion path, validate that all branches have been merged forward :param git_directory: The directory containing the git repo :type git_directory: str :param promotion_chain: git branch promotion path :type promotion_chain: list of str """ ...
r pair in generate_promotion_pairs(promotion_chain): print "checking log comparision of %s -> %s" % (pair[0], pair[1]) output = subprocess.check_output(['git', 'log', "^%s" % pair[1], pair[0]], cwd=git_directory) if output: print "ERROR: in %s...
zurcoin/zurcoin
contrib/devtools/github-merge.py
Python
mit
10,860
0.018048
#!/usr/bin/env python3 # Copyright (c) 2016 Zurcoin Core Developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # This script will locally construct a merge commit for a pull request on a # github repository, inspect it, sign ...
itory. ''' try: return subprocess.check_output([GIT,'config','--get',option]).rstrip().decode('utf-8') except subprocess.CalledProcessError as e: return default def retrieve_pr_info(repo,pull): ''' Retrieve pull request information from github. Return None if no title can be fou...
s. ''' try: req = Request("https://api.github.com/repos/"+repo+"/pulls/"+pull) result = urlopen(req) reader = codecs.getreader('utf-8') obj = json.load(reader(result)) return obj except Exception as e: print('Warning: unable to retrieve pull information from g...
washort/zamboni
mkt/api/middleware.py
Python
bsd-3-clause
15,987
0.000125
import hashlib import hmac import re import time from urllib import urlencode from django.conf import settings from django.contrib.auth.middleware import (AuthenticationMiddleware as BaseAuthenticationMiddleware) from django.contrib.auth.models import AnonymousUser from djan...
og = commonw
are.log.getLogger('z.api') class RestOAuthMiddleware(object): """ This is based on https://github.com/amrox/django-tastypie-two-legged-oauth with permission. """ def process_request(self, request): # For now we only want these to apply to the API. # This attribute is set in APIBas...
akosyakov/intellij-community
python/testData/quickFixes/RenameElementQuickFixTest/shadowingBuiltins_after.py
Python
apache-2.0
21
0.047619
def foo():
a = 10