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 |
|---|---|---|---|---|---|---|---|---|
pjotrligthart/openmoo2-unofficial | game/gui/screen.py | Python | gpl-2.0 | 8,413 | 0.006894 | import time
from pygame.locals import *
import gui
MOUSE_LEFT_BUTTON = 1
MOUSE_MIDDLE_BUTTON = 2
MOUSE_RIGHT_BUTTON = 3
MOUSE_WHEELUP = 4
MOUSE_WHEELDOWN = 5
class Screen(object):
"""Base gui screen class
every game screen class should inherit from this one
"""
__triggers = []
... | en animations, e.g. ship trajectory on MainScreen.
GUI engine calls this method periodically
Animations should be time-dependant - such screens have to implement the timing!
"""
| pass
def get_escape_trigger(self):
"""Returns standard trigger for sending escape action"""
return {'action': "ESCAPE"}
def on_mousebuttonup(self, event):
"""Default implementation of mouse click event serving.
Checks the mouse wheel events (up and down scrolling)... |
jsirois/pants | src/python/pants/backend/python/util_rules/pex_environment.py | Python | apache-2.0 | 10,132 | 0.003652 | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent
from typing import Mapping, Optional, Tuple, cast
from pants.core.util_rules import subpro... | ] = None
def create_argv(
self, pex_filepath: str, *args: str, python: Optional[PythonExecutable] = None
) -> Tuple[str, ...]:
python = python or self.bootst | rap_python
if python:
return (python.path, pex_filepath, *args)
if os.path.basename(pex_filepath) == pex_filepath:
return (f"./{pex_filepath}", *args)
return (pex_filepath, *args)
def environment_dict(self, *, python_configured: bool) -> Mapping[str, str]:
""... |
sramkrishna/eidisi | scripts/meson_post_install.py | Python | gpl-3.0 | 838 | 0.00358 | #!/usr/bin/env python3
import os
import pathlib
import sysconfig
import compileall
import subproc | ess
prefix = pathlib.Path(os.environ.get('MESON_INSTALL_PREFIX', '/usr/local'))
datadir = prefix / 'share'
destdir = os.environ.get('DESTDIR', '')
if not destdir:
print('Compiling gsettings schemas...')
subprocess.call(['glib-compile-schemas', str(datadir / 'glib-2.0' / 'schemas')])
print('Updating icon ... | 'hicolor')])
print('Updating desktop database...')
subprocess.call(['update-desktop-database', '-q', str(datadir / 'applications')])
print('Compiling python bytecode...')
moduledir = sysconfig.get_path('purelib', vars={'base': str(prefix)})
compileall.compile_dir(destdir + os.path.join(moduledir, 'eidisi'), ... |
gangadhar-kadam/mtn-erpnext | patches/may_2012/std_pf_readonly.py | Python | agpl-3.0 | 718 | 0.044568 | from __future__ import unicode_literals
def execute():
"""Make | standard print formats readonly for system ma | nager"""
import webnotes.model.doc
new_perms = [
{
'parent': 'Print Format',
'parentfield': 'permissions',
'parenttype': 'DocType',
'role': 'System Manager',
'permlevel': 1,
'read': 1,
},
{
'parent': 'Print Format',
'parentfield': 'permissions',
'parenttype': 'DocType',
'role': ... |
dims/neutron | neutron/db/bgp_dragentscheduler_db.py | Python | apache-2.0 | 9,018 | 0 | # Copyright 2016 Huawei Technologies India Pvt. Ltd.
# 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 requi... | 'bgp_drscheduler_driver',
default='neutron.services.bgp.scheduler'
'.bgp_dragent_scheduler.ChanceScheduler',
help=_('Driver used for scheduling BGP speakers to BGP DrAgent'))
]
cfg.CONF.register_opts(BGP_DRAGENT_SCHEDULER_OPTS)
class BgpSpeakerDrAgentBinding(model_base.BASEV2):
... | aker and BGP DRAgent"""
__tablename__ = 'bgp_speaker_dragent_bindings'
bgp_speaker_id = sa.Column(sa.String(length=36),
sa.ForeignKey("bgp_speakers.id",
ondelete='CASCADE'),
nullable=False)
dragent =... |
antoinecarme/sklearn2sql_heroku | tests/regression/freidman1/ws_freidman1_MLPRegressor_mysql_code_gen.py | Python | bsd-3-clause | 128 | 0.015625 | from | sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("MLPRegressor" , "freidman1" , " | mysql")
|
Ziqi-Li/bknqgis | bokeh/bokeh/server/tests/test_server.py | Python | gpl-2.0 | 22,987 | 0.002871 | from __future__ import absolute_import
from datetime import timedelta
import pytest
import logging
import re
import mock
from tornado import gen
from tornado.ioloop import PeriodicCallback, IOLoop
from tornado.httpclient import HTTPError
import bokeh.server.server as server
from bokeh.application import Applicatio... |
server_context = session_context.server_context
server_context.add_next_tick_callback(self.on_next_tick_session)
server_context.add_timeout_callback(self.on_timeout_session, 2)
server_context.add_periodic_callback(self.on_periodic_session, 3)
def re | mover():
server_context.remove_periodic_callback(self.on_periodic_session)
self.session_periodic_remover = remover
self.hooks.append("session_created")
# this has to be async too
@gen.coroutine
def on_session_destroyed(self, session_context):
@gen.coroutine
def ... |
apark263/tensorflow | tensorflow/python/autograph/pyct/static_analysis/type_info_test.py | Python | apache-2.0 | 6,883 | 0.004794 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ule."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.autograph.pyct import anno
from tensorflow.python.autograph.pyct import cfg
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.autograph.pyct import qual_... | static_analysis import live_values
from tensorflow.python.autograph.pyct.static_analysis import reaching_definitions
from tensorflow.python.autograph.pyct.static_analysis import type_info
from tensorflow.python.client import session
from tensorflow.python.platform import test
from tensorflow.python.training import trai... |
radicalbit/ambari | ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/params_windows.py | Python | apache-2.0 | 3,411 | 0.007622 | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | on an "AS IS" BASIS,
WI | THOUT 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
#Used in subsequent imports from params
from resource_management.libraries.script.script import Script
from resource_management.libra... |
GabrielBrascher/cloudstack | test/selenium/smoke/TemplatesAndISO.py | Python | apache-2.0 | 6,757 | 0.027823 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | me.sleep(2)
# Go to Dash Board
driver.find_element_by_xpath(Global_Locators.dashboard_xpath).click()
ti | me.sleep(600)
##Verification will be if this offering shows up into table and we can actually edit it.
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
... |
jose-lpa/elastic-django | tests/test_client.py | Python | bsd-3-clause | 2,202 | 0 | from unittest import TestCase
from django.conf import settings
from django.test.utils import override_settings
from mock import patch
from elastic_django.client import ElasticsearchClient
from elastic_django.exceptions import ElasticsearchClientConfigurationError
class ElasticsearchClientTestCase(TestCase):
de... | _hosts_given_nor_configured(self, mock):
"""
Tests client behaviour when being called with no hosts specified and no
hosts defined in Django settings. It should fallback to the ES default
expected configuration (localhost, port 9200).
"""
# Delete setting.
del set... | ue = True
client = ElasticsearchClient()
self.assertEqual(client.hosts, [{'host': 'localhost', 'port': '9200'}])
@override_settings(
ELASTICSEARCH_HOSTS=[{'host': '127.0.0.1', 'port': '443'}])
@patch('elasticsearch.Elasticsearch.ping')
def test_no_hosts_given_and_configured(self, m... |
ovh/ip-reputation-monitoring | reputation/parsing/csv/blocklistde.py | Python | gpl-3.0 | 2,133 | 0.000469 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2016, OVH SAS
#
# This file is part of ip-reputation-monitoring.
#
# ip-reputation-monitoring 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 L... | def get_ip(self, data):
if len(data) != 6:
return None
return data[0]
def _get_service(self, cell):
""" Try to extract service associated to the issue from a c | ell """
return cell.strip().split(',')[0]
@staticmethod
def get_description():
""" Mandatory method for auto-registration """
return {
'name': PARSER_NAME,
'shortened': 'BLCK'
}
|
birkholz/homeboard | chores/migrations/0001_initial.py | Python | gpl-2.0 | 1,978 | 0.002022 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('home', '0001_initial'),
]
operat... | ('home', models.ForeignKey(related_name='chores', to='home.Home')),
],
options={
'abstract': False,
},
bases=(models.Model,),
),
migrations.AddField(
model_name='assignment',
name='chore',
field=mod... | ations.AddField(
model_name='assignment',
name='user',
field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
]
|
django-settings/django-settings | myproject/myproject/local_settings.py | Python | unlicense | 301 | 0.003322 | # Define settings that are specific to the local environment.
DATABASES = {
'default': {
| 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'database.db',
}
}
INTERNAL_IPS = ('127.0.0.1',)
f | rom custom_settings import INSTALLED_APPS
INSTALLED_APPS += (
# 'debug_toolbar',
)
|
diofant/diofant | diofant/tests/core/test_relational.py | Python | bsd-3-clause | 22,310 | 0.000359 | import operator
import random
import pytest
from diofant import (And, Eq, Equality, FiniteSet, Float, Function, Ge,
GreaterThan, Gt, I, Implies, Integer, Interval, Le,
LessThan, Lt, Ne, Not, Or, Rational, Rel, Relational,
StrictGreaterThan, StrictLessThan... | e
assert (oo < 1) is false
assert (oo >= oo) is true
assert (oo >= -oo) is true
assert (oo >= 1) is true
assert (oo <= oo) is true
assert (oo <= -oo) is false
assert (oo <= 1) is false
assert (-oo > oo) is false
assert (-oo > -oo) is | false
assert (-oo > 1) is false
assert (-oo < oo) is true
assert (-oo < -oo) is false
assert (-oo < 1) is true
assert (-oo >= oo) is false
assert (-oo >= -oo) is true
assert (-oo >= 1) is false
assert (-oo <= oo) is true
assert (-oo <= -oo) is true
assert (-oo <= 1) is true
de... |
adel-boutros/qpid-dispatch | tests/system_tests_multi_tenancy.py | Python | apache-2.0 | 35,894 | 0.004987 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | self.routers[1].addresses[1],
"addr_08",
"addr_08",
self.routers[0].addresses[0],
"M00.0.0.0/addr_08")
test.run()
self.assertEqual(None, test.err... | s[0],
self.routers[0].addresses[0],
"anything/addr_09",
"anything/addr_09",
self.routers[0].addresses[0],
"M0anything/addr_09... |
davenquinn/Attitude | attitude/stereonet.py | Python | mit | 7,069 | 0.014854 | import numpy as N
from mplstereonet import stereonet_math
from scipy.stats import chi2
from numpy.testing import assert_array_almost_equal
from .geom.util import vector, unit_vector, dot
def quaternion(vector, angle):
"""
Unit quaternion for a vector and an angle
"""
return N.cos(angle/2)+vector*N.sin... | ,**kwargs):
"""
kwargs:
traditional_layout boolean [True]
Lay the stereonet out traditionally, with n | orth at the pole of
the diagram. The default is a more natural and intuitive visualization
with vertical at the pole and the compass points of strike around the equator.
Thus, longitude at the equator represents strike and latitude represents
apparent dip at that azimuth.
"""
le... |
MatthewWilkes/mw4068-packaging | src/melange/src/soc/tasks/helper/__init__.py | Python | apache-2.0 | 654 | 0.004587 | #
# Copyright 2009 the Melange 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 c | opy 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 C | ONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains Melange Task API related helper modules.""" |
miyakz1192/neutron | neutron/tests/api/test_extra_dhcp_options.py | Python | apache-2.0 | 4,030 | 0.000248 | # Copyright 2013 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 requ... | Extra DHCP Options
body = self.client.create_port(
network_id=self.network['id'],
extra_dhcp_opts=self.extra_dhcp_opts)
port_id = | body['port']['id']
self.addCleanup(self.client.delete_port, port_id)
# Confirm port created has Extra DHCP Options
body = self.client.list_ports()
ports = body['ports']
port = [p for p in ports if p['id'] == port_id]
self.assertTrue(port)
self._confirm_extra_dhc... |
lkylei/ten_thousand | roms/u-boot/tools/patman/gitutil.py | Python | gpl-2.0 | 18,813 | 0.002232 | # Copyright (c) 2011 The Chromium OS Authors.
#
# SPDX-License-Identifier: GPL-2.0+
#
import command
import re
import os
import series
import subprocess
import sys
import terminal
import checkpatch
import settings
def CountCommitsToBranch():
"""Returns number of commits between HEAD and the tracking branch.
... | subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess. | PIPE)
stdout, stderr = pipe.communicate()
if pipe.returncode:
str = 'Could not move to commit before patch series'
print col.Color(col.RED, str)
print stdout, stderr
return False
# Apply all the patches
for fname in args:
ok, stdout = ApplyPatch(verbose, fname)
... |
operasoftware/tlscommon | test_results.py | Python | apache-2.0 | 4,642 | 0.019604 | # Copyright 2010-2012 Opera Software ASA
#
# 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, softwa | re
# 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.
'''
Created on 31. mars 2012
@author: yngve
'''
# List of st... |
GamesCrafters/GamesmanClassic | src/py/games/tt2.py | Python | gpl-2.0 | 963 | 0.001038 | import game
import server
class tt2(game.Game):
class TT2Process(server.GameProcess):
def memory_percent_usage(self):
return 0.0
def __init__(self, server, name):
game.Game.__init__(self, server, name)
self.process_class = self.TT2Process
def get_option(self, query)... | 'number': 2,
'width': 6,
| 'height': 3},
{}]
req.respond(self.format_parsed(
{'status': 'ok',
'response': options}))
else:
raise NotImplemented()
|
false-git/mail2entry | postentry.py | Python | gpl-2.0 | 621 | 0.011272 | #! /usr/bin/env python
"""Post a new | MT entry"""
# username, password, blogid, publish
from settings imp | ort *
import types
import xmlrpclib
def post(content):
"""Post an entry to a blog. Return postid on success."""
content.check()
weblogContent = { 'title' : content.getTitle(),
'description' : content.getEntry() }
server = xmlrpclib.ServerProxy(uri)
# on success, resul... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/__init__.py | Python | mit | 15,615 | 0.004163 | # 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 ... | PoliciesOperations
from ._operations import Operations
from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations
from ._private_link_resources_operations import PrivateLinkResourcesOperations
from ._recoverable_managed_databases_operations import RecoverableManagedDatabasesOperations
fr... | LabelsOperations
from ._recommended_sensitivity_labels_operations import RecommendedSensitivityLabelsOperations
from ._server_advisors_operations import ServerAdvisorsOperations
from ._server_automatic_tuning_operations import ServerAutomaticTuningOperations
from ._server_azure_ad_administrators_operations import Serve... |
damdam-s/rma | product_warranty/models/return_instruction.py | Python | agpl-3.0 | 2,163 | 0 | # -*- coding: utf-8 -*-
# ########################################################################
# #
# #
# #####################################################################... | #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. ... | #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
##########################################################################
from openerp import fields, models
class ReturnInstruction(models.Model)... |
gitsimon/spadup-lyra | frontend/import_handler.py | Python | mpl-2.0 | 1,952 | 0.002049 | import ast
from frontend.context import Context
from frontend.stubs.stubs_paths import libraries
class ImportHandler:
"""Handler for importing other modules during the type inference"""
@staticmethod
def get_ast(path, module_name):
"""Get the AST of a python module
:param path: t... | he name of the python module
:param base_folder: the base folder containing the python module
"""
return ImportHandler.get_ast("{}/{}.py".format(base_folder, module_name), module_name)
@staticmethod
def | get_builtin_ast(module_name):
"""Return the AST of a built-in module"""
return ImportHandler.get_ast(libraries[module_name], module_name)
@staticmethod
def infer_import(module_name, base_folder, infer_func, solver):
"""Infer the types of a python module"""
context = Context()
... |
nicko96/Chrome-Infra | appengine/chromium_cq_status/tests/login_test.py | Python | bsd-3-clause | 563 | 0.003552 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-st | yle license that can be
# found in the LICENSE file.
from tests.testing_utils import testing
import highend
class TestLogin(testing.AppengineTestCase):
app_module = highend.app
def test_login(self):
response = self.test_app.get('/login')
self.assertEquals(302, response.status_code)
self.assertEqual... | onse.location)
|
jsfenfen/django-calaccess-raw-data | example/manage.py | Python | mit | 304 | 0 | #! | /usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from django.core.management import execute_from_command_line
execu | te_from_command_line(sys.argv)
|
virantha/verifytree | test/test_verifytree.py | Python | apache-2.0 | 275 | 0 | import verifytree.VerifyTree as P
import pytest
import os
import logging
|
import smtplib
from mock import Mock
from mock import p | atch, call
from mock import MagicMock
from mock import PropertyMock
class Testverifytree:
def setup(self):
self.p = P.VerifyTree()
|
CLLKazan/iCQA | qa-engine/forum/migrations/0019_auto__del_likedcomment__del_comment__add_field_node_abs_parent__chg_fi.py | Python | gpl-3.0 | 27,368 | 0.008112 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'LikedComment'
db.delete_table('forum_likedcomment')
# Deleting... | x_length': '100'})
},
'forum.activity': {
'Meta': {'object_name': 'Activity', 'db_table': "u'activity'"},
'active_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'activity_type': ('django.db.models.fields.SmallIntegerFiel... | lds.AutoField', [], {'primary_key': 'True'}),
'is_auditted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to'... |
battlesnake/OpenSCAD | scripts/macosx-sanity-check.py | Python | gpl-2.0 | 4,696 | 0.010009 | #!/usr/bin/env python
#
# This is be used to verify that all the dependant libraries of a Mac OS X executable
# are present and that they are backwards compatible with at least 10.5.
# Run with an executable as parameter
# Will return 0 if the executable an all libraries are OK
# Returns != 0 and prints some textura... | p.returncode) + ":"
print err
return None
deps = output.split('\n')
for dep in deps:
# print dep
| dep = re.sub(".*:$", "", dep) # Take away header line
dep = re.sub("^\t", "", dep) # Remove initial tabs
dep = re.sub(" \(.*\)$", "", dep) # Remove trailing parentheses
if len(dep) > 0 and not re.search("/System/Library", dep) and not re.search("/usr/lib", dep):
libs.append(dep)
... |
artekw/sensmon | sensnode/decoders/outnode.py | Python | mit | 761 | 0.015769 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import time
import datetime
import inspect
import simplejson as json
def outnode(data):
"""Outnode"""
a = int(data[2])
b = int(data[3])
c = int(data[4])
d = i | nt(data[5])
e = int(data[6])
f = int(data[7])
g = int(data[8])
h = int(data[9])
i = int(data[10])
j = int(data[11])
name = inspect.stack()[0][3] # z nazwy funcji
timestamp = int(time.mktime(datetime.datetime.now().timetuple())) #unix time
template = ({
'name':na... | in template.iteritems())
|
Lilykos/invenio | invenio/legacy/bibedit/cli.py | Python | gpl-2.0 | 10,826 | 0.002402 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 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,... | given record revision to
become current revision
--check-revisions [recid] | check if revisions are not corrupted
(* stands for all records)
--fix-revisions [recid] fix revisions that are corrupted
(* stands for all records)
--clean-revisions [recid] clean duplicate revi... |
acq4/acq4 | acq4/devices/AxoPatch200/AxoPatch200.py | Python | mit | 25,005 | 0.012478 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import with_statement
import time
from collections import OrderedDict
import numpy as np
from pyqtgraph.WidgetGroup import WidgetGroup
from acq4.devices.DAQGeneric import DAQGeneric, DAQGenericTask, DAQGenericTaskGui, DataMapping
from acq4... | ic'}
| self.modeAliases = {'ic': 'I-Clamp', 'i=0': 'Track', 'vc': 'V-Clamp'}
elif self.version == '200A':
# telegraph voltage/output translation from the Axopatch 200 amplifier
self.mode_tel = np.array([6, 4, 2, 1])
self.modeNames = OrderedDict([(0, 'V-Clamp'), (1, 'Trac... |
jonathanmorgan/conv2wp | b2e/b2e_importer.py | Python | gpl-3.0 | 77,772 | 0.019454 | '''
Copyright 2013 Jonathan Morgan
This file is part of http://github.com/jonathanmorgan/conv2wp.
conv2wp 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 Software Foundation, either version 3 of the License, or
(at your optio... | s, **kwargs ):
'''
# get posts - if we have a blog ID, limit to that blog.
# For each post:
# - create Item, load with information from post.
# - get author user, add it to Authors.
# - get comments for post, store them in | Comments, asociated to Item.
# - get categories for post, look up and associate them.
'''
# return reference
status_OUT = cls.STATUS_SUCCESS
# declare variables
b2e_importer = None
my_db_cursor = None
table_name_prefix = ""
sql_select_pos... |
MasteringSpark/FirstStep | src/main/python/scikit/loss_function.py | Python | apache-2.0 | 918 | 0.002179 | __author__ = 'asdf2014'
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
def modified_huber_loss(y_true, y_pred):
z = y_pred * y_true
loss = -4 * z
loss[z >= -1] = (1 - z[z >= -1]) ** 2
lo | ss[z >= 1.] = 0
return loss
xmin, xmax = -4, 4
xx = np.linspace(xmin, xmax, 100)
plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], 'k-',
label="Zero-one loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0), 'g-',
label="Hinge loss")
plt.plot(xx, -np.minimum(xx, 0), 'm-',
label="Perceptron loss")
p... | xx)), 'r-',
label="Log loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, 'b-',
label="Squared hinge loss")
plt.plot(xx, modified_huber_loss(xx, 1), 'y--',
label="Modified Huber loss")
plt.ylim((0, 8))
plt.legend(loc="upper right")
plt.xlabel(r"Decision function $f(x)$")
plt.ylabel("$L(y,... |
felipenaselva/felipe.repository | plugin.video.streamhub/resources/lib/sources/en/watchfree.py | Python | gpl-2.0 | 8,466 | 0.012521 | # -*- coding: utf-8 -*-
'''
Covenant Add-on
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 prog... | es(url)
url = url.encode('utf-8')
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
if url == None: return sources
url = urlparse.urljoin(self.base_link, url)
result = pro... | nks:
try:
url = client.parseDOM(i, 'a', ret='href')
url = [x for x in url if 'gtfo' in x][-1]
url = proxy.parse(url)
url = urlparse.parse_qs(urlparse.urlparse(url).query)['gtfo'][0]
url = base64.b64decode... |
cryos/tomviz | acquisition/tomviz/__init__.py | Python | bsd-3-clause | 2,177 | 0 | import logging
import logging.handlers
import os
import sys
LOG_FORMAT = '[%(asctime)s] %(levelname)s: %(message)s'
MAX_LOG_SIZE = 1024 * 1024 * 10
LOG_BACKUP_COUNT = 5
LOG_PATH = log_path = os.path.join(os.path.expanduser('~'), '.tomviz', 'logs')
LOG_PATHS = {
'stderr': '%s/stderr.log' % LOG_PATH,
'stdout': ... | err_log_writer
sys.stdout = stdout_log_writer
def setup_loggers(debug=False):
logger = logging.getLogger('tomviz')
logger.setLevel(logging.DEBUG | if debug else logging.INFO)
stream_handler = logging.StreamHandler()
file_handler = logging.handlers.RotatingFileHandler(
LOG_PATHS['debug'], maxBytes=MAX_LOG_SIZE,
backupCount=LOG_BACKUP_COUNT)
formatter = logging.Formatter(LOG_FORMAT)
stream_handler.setFormatter(formatter)
file_ha... |
aragos/tichu-tournament | python/openpyxl/styles/styleable.py | Python | mit | 2,984 | 0.002011 | from __future__ import absolute_import
# Copyright (c) 2010-2016 openpyxl
from warnings import warn
from .numbers import BUILTIN_FORMATS, BUILTIN_FORMATS_REVERSE
from .proxy import StyleProxy
from .cell_style import StyleArray
class StyleDescriptor(object):
def __init__(self, collection, key):
self.col... | f __get__(self, instance, cls):
| if not getattr(instance, "_style"):
instance._style = StyleArray()
idx = getattr(instance._style, self.key)
if idx < 164:
return BUILTIN_FORMATS.get(idx, "General")
coll = getattr(instance.parent.parent, self.collection)
return coll[idx - 164]
class StyleableO... |
pilliq/balance | tests/test_loaders.py | Python | mit | 1,764 | 0.004535 | # AMDG
import unittest
from datetime import datetime
from balance import BasicLoader, RepayLoader
from base_test import BaseTest
class LoaderTests(BaseTest, unittest.TestCase):
def test_basic_loader(self):
loader = BasicLoader('tests/data/basic_loader')
entries, errors = loader.load(return_errors=... | len(entries))
entry = entries[0]
self.assertEquals(-5.00, entry.amount)
self.assertEquals(2, len(errors))
| self.assertEquals(errors[0]['entry'], '\n')
self.assertTrue(errors[0]['error'].message.startswith('Not a valid entry'))
self.assertEquals(errors[1]['entry'], 'this is a bad line:\n')
self.assertTrue(errors[1]['error'].message.startswith('Not a valid entry'))
def test_repay_loader(self):
... |
ashutosh-mishra/youtube-dl | youtube_dl/extractor/dailymotion.py | Python | unlicense | 8,993 | 0.003114 | import re
import json
import itertools
from .common import InfoExtractor
from .subtitles import SubtitlesInfoExtractor
from ..utils import (
compat_urllib_request,
compat_str,
get_element_by_attribute,
get_element_by_id,
orderedSet,
ExtractorError,
)
class DailymotionBaseInfoExtractor(InfoEx... | get('error') is not None:
msg = 'Couldn\'t get video, Dailymotion says: %s' % info['error']['title']
raise ExtractorError(msg, expected=True)
formats = []
for (key, format_id) in self._FORMATS:
| video_url = info.get(key)
if video_url is not None:
m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
if m_size is not None:
width, height = m_size.group(1), m_size.group(2)
else:
width, height = None, None
... |
BJEBN/Geometric-Analysis | Scripts/Old Scripts/Extract_Non_Duplicate_Nodes.py | Python | gpl-3.0 | 2,434 | 0.013969 | #==================================
#Author Bjorn Burr Nyberg
#University of Bergen
#Conta | ct bjorn.nyberg@uni.no
#Copyright 2013
| #==================================
'''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... |
OCA/l10n-brazil | l10n_br_hr/tests/__init__.py | Python | agpl-3.0 | 71 | 0 | from . import test | _l10n_br_hr
from . import test_hr_employee_dep | endent
|
jdgwartney/boundary-api-cli | tests/unit/boundary/cli_test.py | Python | apache-2.0 | 2,812 | 0.001067 | #!/usr/bin/env python
#
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | in m]
cli_name = str.join('-', m)
return cli_name
@staticmethod
def check_cli_help(test_case, cli):
| parameters = CLITestParameters()
name = cli.__class__.__name__
expected_output = parameters.get_cli_help(name)
m = re.findall("([A-Z][a-z]+)", name)
m = [a.lower() for a in m]
command = str.join('-', m)
try:
output = subprocess.check_output([command, '-h'])
... |
BRCDcomm/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_maps_ext.py | Python | apache-2.0 | 12,855 | 0.0021 | #!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_maps_ext(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def maps_get_all_policy_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
... | T.SubElement(output, "policy")
policyname = ET.SubElement(polic | y, "policyname")
policyname.text = kwargs.pop('policyname')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def maps_get_rules_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_g... |
iw3hxn/LibrERP | report_aeroo/wizard/report_print_by_action.py | Python | agpl-3.0 | 2,640 | 0.006061 | ##############################################################################
#
# Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <info@alistek.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take th... | browse(cr, uid, context['active_id'], context=context)
print_ids = eval("[%s]" % this.object_ids, {})
data = {'model':report_xml.model, 'ids':print_ids, 'id':print_ids[0], 'report_type': 'aeroo'}
return {
'type': 'ir.actions.report.xml',
| 'report_name': report_xml.report_name,
'datas': data,
'context':context
}
_columns = {
'name':fields.text('Object Model', readonly=True),
'object_ids':fields.char('Object IDs', size=250, required=True, help="Comma separated records ID"),
}
... |
SolusOS-discontinued/RepoHub | buildfarm/views.py | Python | mit | 5,488 | 0.030977 | # Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>
# SimpleXMLRPCDispatcher lets us r... | xt ({'form': form})
if form.is_valid ():
rdict = { 'html': "The new queue has been set up", 'tags': 'success' }
model = form.save (commit=False)
model.current = 0
model.length = 0
model.current_package_name = ""
model.save ()
else:
html = render_to_string ('buildfarm/new_queue.html', {'form_qu... | 'tags': 'fail' }
json = simplejson.dumps(rdict, ensure_ascii=False)
print json
# And send it off.
return HttpResponse( json, content_type='application/json')
else:
form = NewQueueForm ()
context = {'form': form }
return render (request, 'buildfarm/new_queue.html', context)
def queue_index(requ... |
AndrewKLeech/Pip-Boy | Game.py | Python | mit | 42,161 | 0.0347 | import tkinter as tk
from tkinter import *
import spotipy
import webbrowser
from PIL import Image, ImageTk
import os
from twitter import *
from io import BytesIO
import urllib.request
import urllib.parse
import PIL.Image
from PIL import ImageTk
import simplejson
song1 = "spotify:artist:58lV9VcRSjABbAbfWS6skp"
song2 = ... | def text_to_button(msg, color, buttonx, buttony | , buttonwidth, buttonheight,
size="smallFont"): # Blits text to button
textSurface, textRect = text_objects(msg, color, size)
textRect.center = ((buttonx + buttonwidth / 2), buttony + (buttonheight / 2))
gameDisplay.blit(textSurface, textRect)
def mes... |
vmagamedov/hiku | hiku/federation/denormalize.py | Python | bsd-3-clause | 314 | 0 | from collections import deque
from hiku.denormalize.graphql import DenormalizeGraphQL
class DenormalizeEntityGraphQL(Denormal | izeGraphQL):
def __init__(self, graph, result, root_type_name):
| super().__init__(graph, result, root_type_name)
self._type = deque([graph.__types__[root_type_name]])
|
svaarala/duktape | tests/perf/test-string-array-concat.py | Python | mit | 174 | 0.011494 | def test(): |
for i in xrange(int(5e3)):
t = []
for j in xrange(int(1e4)):
#t[j] = 'x'
t.append('x')
t = ''.join(t)
test( | )
|
kbussell/django-auditlog | src/auditlog/diff.py | Python | mit | 5,123 | 0.002733 | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, NOT_PROVIDED, DateTimeField
from django.utils import timezone
from django.utils.encoding import smart_text
def track_field(field):
"""
Returns whether the given field should be tracked by... | ve form before we can accuratly compare them for changes.
try:
value = field.to_python(getattr(obj, field.name, None))
if value is not None and settings.USE_TZ and not timezone.is_naive(value):
value = timezone.make_naive(value, timezone=timezone.utc)
except Objec... | ED else None
else:
try:
value = smart_text(getattr(obj, field.name, None))
except ObjectDoesNotExist:
value = field.default if field.default is not NOT_PROVIDED else None
return value
def model_instance_diff(old, new):
"""
Calculates the differences between two... |
cpennington/edx-platform | common/djangoapps/student/middleware.py | Python | agpl-3.0 | 1,580 | 0.001266 | """
Middleware that checks user standing for the purpose of keeping users with
disabled accounts from accessing the site.
"""
from django.conf import settings
from django.http import HttpResponseForbidden
from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import ugettext as _
from ope... | 'Your account has been disabled. If you believe '
'this was | done in error, please contact us at '
'{support_email}'
)).format(
support_email=HTML(u'<a href="mailto:{address}?subject={subject_line}">{address}</a>').format(
address=settings.DEFAULT_FEEDBACK_EMAIL,
subject_line... |
Shaswat27/sympy | sympy/printing/lambdarepr.py | Python | bsd-3-clause | 8,389 | 0.006556 | from __future__ import print_function, division
from .str import StrPrinter
from sympy.utilities import default_sort_key
class LambdaPrinter(StrPrinter):
"""
This printer converts expressions into strings that can be used by
lambdify.
"""
def _print_MatrixBase(self, expr):
return "%s(%s)... | printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_default_settings = {
"order": "none",
"full_prec": "auto",
}
def _print_seq(self, seq, delimiter=', '):
"General sequence printer: converts to tuple"
# Print tuples here instead of lis... | '({},)'.format(delimiter.join(self._print(item) for item in seq))
def _print_MatMul(self, expr):
"Matrix multiplication printer"
return '({0})'.format(').dot('.join(self._print(i) for i in expr.args))
def _print_Piecewise(self, expr):
"Piecewise function printer"
exprs = '[{0}... |
spcui/tp-qemu | qemu/tests/migration.py | Python | gpl-2.0 | 9,706 | 0.000309 | import logging
import time
import types
from autotest.client.shared import error
from virttest import utils_misc, utils_test, aexpect
def run(test, params, env):
"""
KVM migration test:
1) Get a live VM and clone it.
2) Verify that the source VM supports migration. If it does, proceed with
... | or_login(timeout=30)
logging.info("Logged in after migration")
# Make sure the background process is still running
session2.cmd(check_command, timeout=30)
# Get the output of migration_test_command
output = session2.cmd_output(test_command)
# Co... | |
william-richard/moto | tests/test_cloudformation/fixtures/kms_key.py | Python | apache-2.0 | 1,645 | 0.000608 | from __future__ import unicode_literals
template = {
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "AWS CloudFormation Sample Template to create a KMS Key. The Fn::GetAtt is used to retrieve the ARN",
"Resources": {
"myKey": {
"Type": "AWS::KMS::Key",
"Properties... | KeyPolicy": {
"Version": "2012-10-17",
"Id": "key-default-1",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
... | [
"arn:aws:iam::",
{"Ref": "AWS::AccountId"},
":root",
],
]
... |
civalin/cmdlr | src/cmdlr/analyzers/cartoonmad.py | Python | mit | 3,587 | 0.000561 | """The www.cartoonmad.com analyzer.
[Entry examples]
- http://www.cartoonmad.com/comic/5640.html
- https://www.cartoonmad.com/comic/5640.html
"""
import re
from urllib.parse import parse_qsl
from cmdlr.analyzer import BaseAnalyzer
from cmdlr.autil import fetch
class Analyzer(BaseAnalyzer):
"""The www.... | rl(src).s | plit('?', maxsplit=1)
qs = dict(parse_qsl(qs_string))
file_parts = qs['file'].split('/')
file_parts[-1] = '{:0>3}'
qs['file'] = '/'.join(file_parts)
qs_tpl = '&'.join(['{}={}'.format(key, value)
for key, value in qs.items()])
abspath_tpl = '{... |
braynebuddy/PyBrayne | act_twitter.py | Python | gpl-3.0 | 3,157 | 0.009819 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# TODO prog_base.py - A starting template for Python scripts
#
# Copyright 2013 Robert B. Hawkins
#
"""
SYNOPSIS
TODO prog_base [-h,--help] [-v,--verbose] [--version]
DESCRIPTION
TODO This describes how to use this script. This docstring
will be printed by ... | r__ = "Rob Hawkins <webwords@txhawkins.net>"
__version__ = "1.0.0"
__date__ = "2013.12.01"
# Version Date | Notes
# ------- ---------- -------------------------------------------------------
# 1.0.0 2013.12.01 Starting script template
#
import sys, os, traceback, argparse
import time
import re
#from pexpect import run, spawn
def test ():
global options, args
# TODO: Do something more interesting here...
... |
unt-libraries/django-invite | invite/migrations/0002_abstract_invitation.py | Python | bsd-3-clause | 1,634 | 0.002448 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import uuid
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
('invite', '0001_initial'),
]
operations = [
migrations.DeleteModel('PasswordRe... | 'abstract': False,
| },
bases=(models.Model,),
),
]
|
Terhands/saskdance | app/main.py | Python | gpl-3.0 | 373 | 0.010724 | import os
import webapp2
from app import routes
webapp2_config = {'webapp2_extras.sessions':
{'secr | et_key': 'hfgskahjfgd736987qygukr3279rtigu',
'webapp2_extras.jinja2': {'template_path': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates')}}}
application = | webapp2.WSGIApplication(debug=True, config=webapp2_config)
routes.add_routes(application) |
petrlosa/ella | ella/core/feeds.py | Python | bsd-3-clause | 4,034 | 0.001735 | from mimetypes import guess_type
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from django.http import Http404
from django.template import TemplateDoesNotExist, RequestContext, NodeList
from ella.core.models import Listing, Category
from ella.core.conf import core_... | item.publishable
box = p.box_class(p, core_settings.RSS_DESCRIPTION_BOX_TYPE, NodeList())
try:
desc = box.render(self.box_context)
except TemplateDoesNotExist:
desc = None
if not desc:
desc = item.publishable.description
return desc
def ... | ##############################################
def item_enclosure_url(self, item):
if not hasattr(item, '__enclosure_url'):
if hasattr(item.publishable, 'feed_enclosure'):
item.__enclosure_url = item.publishable.feed_enclosure()['url']
elif self.format is not None and... |
quinox/weblate | weblate/accounts/models.py | Python | gpl-3.0 | 26,496 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | ser.first_name
| # Use username if full name is empty
if full_name == '':
full_name = user.username
# Add email if we are asked for it
if not email:
return full_name
return '%s <%s>' % (full_name, user.email)
def notify_merge_failure(subproject, error, status):
'''
Notification on merge fai... |
markmcclain/astara | akanda/rug/api/configuration.py | Python | apache-2.0 | 6,984 | 0.000143 | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | ocations = []
for port in ports:
addrs = {
str(fixed.ip_address): subnets_dict[fixed.subnet_id].enable_dhcp
for fixed in port.fixed_ips
}
if not addrs:
continue
allocations.append(
{
'ip_addresses': addrs,
... | turn allocations
def generate_floating_config(router):
return [
{'floating_ip': str(fip.floating_ip), 'fixed_ip': str(fip.fixed_ip)}
for fip in router.floating_ips
]
|
ethanhlc/streamlink | src/streamlink/stream/stream.py | Python | bsd-2-clause | 915 | 0 | import io
import json
class Stream(object):
__shortname__ = "stream"
"""
This is a base class that should be inherited when implementing
different stream types. Should only be created by plugins.
"""
def __init__(self, session):
self.session = session
def __repr__(self):
... | rtname())
def open(self):
"""
Attempts to open a connection to the stream.
Returns a file-like object that can be used to read the stream data.
Raises :exc:`StreamError` on failure.
"""
raise NotImplementedError
@property
def json(self):
obj = self.... | pass
__all__ = ["Stream", "StreamIO"]
|
Nitaco/ansible | lib/ansible/module_utils/network/ios/ios.py | Python | gpl-3.0 | 5,949 | 0.002858 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | nv_fallback, ['ANSIBLE_NET_AUTHORIZE']), type='bool'),
'auth_pass': dict(removed_in_version=2.9, no_log=True),
'timeout': dict(removed_in_version=2.9, type='int')
}
ios_argument_spec.update(ios_top_spec)
def get_provider_argspec():
return ios_provider_spec
def get_connection(module):
if hasattr(modu... | onnection'):
return module._ios_connection
capabilities = get_capabilities(module)
network_api = capabilities.get('network_api')
if network_api == 'cliconf':
module._ios_connection = Connection(module._socket_path)
else:
module.fail_json(msg='Invalid connection type %s' % networ... |
Azure/azure-sdk-for-python | sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/activestamp/operations/_jobs_operations.py | Python | mit | 5,627 | 0.004087 | # 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 ... | rameters,
headers=header_parameters,
**kwargs
)
class JobsOperations(object):
"""JobsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alia... | :type models: ~azure.mgmt.recoveryservicesbackup.activestamp.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init_... |
somat/samber | elf.py | Python | mit | 861 | 0.003484 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError
from elftools.elf.segments import NoteSegment
class ReadELF(object):
def __init__(self, file):
self.elffile = ELFFile(file)
def get_build(self):
f... | f isinstance(segment, NoteSegment):
for note in segment.iter_notes():
print note
def main():
if(len(sys.argv) < 2):
print "Missing argument"
sys.exit(1)
with open(sys.argv[1], 'rb') as file:
try:
readelf = ReadELF(file)
readel... | pt ELFError as err:
sys.stderr.write('ELF error: %s\n' % err)
sys.exit(1)
if __name__ == '__main__':
main()
|
cyaninc/django-mysql-pymysql | src/mysql_pymysql/schema.py | Python | bsd-3-clause | 2,073 | 0.00193 | from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models import NOT_PROVIDED
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
sql_rename_table = "RENAME TABLE %(old_table)s TO %(new_table)s"
sql_alter_column_null = "MODIFY %(column)s %(type)s NULL"
sql_alter_column_... | X %(name)s"
sql_create_fk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) REFERENCES %(to_table)s (%(to_column)s)"
sql_delete_fk = "ALTER TABLE %(table)s DROP FOREIGN KEY %(name)s"
sql_delete_index = "DROP INDEX %(name)s ON %(table)s"
sql_delete_pk = "ALTER TABLE %(table)s D... | ing_set_null = 'MODIFY %(column)s %(type)s NULL;'
alter_string_drop_null = 'MODIFY %(column)s %(type)s NOT NULL;'
sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY"
def quote_value(self, value):
ret... |
MahdiZareie/PyShop | shop/models.py | Python | mit | 691 | 0.001447 | from django.db import models
from customer.models import Customer
from product.models import Product
from django.utils import timezone
# Create your models here.
class OrderStatus:
IN_BASKET = 0
PAYED = 1
class Order(models.Model):
customer = models.ForeignKey(C | ustomer)
product = models.ForeignKey(Product)
quantity = models.IntegerField(default=1)
status = models.SmallIntegerField()
created_at = models.DateTimeField()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if self.pk is None:
self.create... | orce_insert, force_update, using, update_fields)
|
marado/stars-to-addresses | stars-to-addresses.py | Python | gpl-3.0 | 5,571 | 0.009514 | # -*- coding: utf-8 -*-
"""
Go to Google Bookmarks: https://www.google.com/bookmarks/
On the bottom left, click "Export bookmarks": https://www.google.com/bookmarks/bookmarks.html?hl=en
After downloading the html file, run this script on it to get the addresses
This script is based on https://gist.github.com/endolit... |
latitude = ""
longitude = ""
try:
lines = content.split('\n') # --> ['Line 1', 'Line 2', 'Line 3']
for line in lines:
if re.search('cacheResponse\(', line):
... | values = eval(splitline)
print values[8][0][1]
longitude = str(values[0][0][1])
latitude = str(values[0][0][2])
continue
if latitude == "":
... |
obi-two/Rebelion | data/scripts/templates/object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_s11_training.py | Python | mit | 490 | 0.044898 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Weapon()
result.template = "object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_s1 | 1_training.iff"
result.attribute_template_id = 10
result.stfName("weapon_name","sword_lightsaber_type11")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATION | S ####
return result |
Sutto/cloud-custodian | tools/c7n_azure/tests_azure/test_filters_marked_for_op.py | Python | apache-2.0 | 3,258 | 0.002762 | # Copyright 2019 Microsoft Corporation
#
# 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 wri... | tools.get_resource({'custodian_status': 'missing: atsign'})]
self._test_filter_scenario(resources, 0)
def test_different_op_returns_no_resource(self):
date = now().strftime('%Y-%m-%d')
resources = [tools.get_resource({'custodian_status': 'TTL: dele | te@{0}'.format(date)})]
self._test_filter_scenario(resources, 0)
def test_misformatted_date_string(self):
date = "notadate"
resources = [tools.get_resource({'custodian_status': 'TTL: stop@{0}'.format(date)})]
self._test_filter_scenario(resources, 0)
def test_timezone_in_dates... |
raqet/acquisition-client | testing/test-iscsi.py | Python | gpl-3.0 | 1,527 | 0.061559 | #!/usr/bin/python3
import os
import sys
import subprocess
import unittest
def testequal(a,b):
if (a==b):
print ("SUCCESS")
else:
print ("FAIL")
def getPortal():
output=subprocess.check_output(["iscsi-ls","iscsi://localhost:3260"])
print (output)
target=output[7:-25]
#Test if iSCSI portal is created (last par... | sertEqual(target[:-12],"iqn.2003-01.org.linux-iscsi.testingclient-hostname:sn.") |
def test_lun0(self):
self.assertEqual(getLunCapacity(target,0),51200)
def test_lun1(self):
self.assertEqual(getLunCapacity(target,1),0)
def test_lun2(self):
self.assertEqual(getLunCapacity(target,2),66560)
if __name__ == '__main__':
global target
target=getPortal()
# getLun(target,0)
# getLun(target,1)... |
rdmorganiser/rdmo | rdmo/conditions/viewsets.py | Python | apache-2.0 | 2,141 | 0.000934 | from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rdmo.core.exports import XMLResponse
from rdmo.core.permis... | lf, request, pk=None):
serializer = ConditionExportSerializer(self.get_object())
xml = ConditionRenderer().render([serializer.data])
return XMLResponse(xml, name=self.get_object().key)
class RelationViewSet(ChoicesViewSet):
permission_classes = (IsAuthe | nticated, )
queryset = Condition.RELATION_CHOICES
|
felix-dumit/campusbot | yowsup2/yowsup/layers/protocol_contacts/protocolentities/test_iq_sync_get.py | Python | mit | 810 | 0.011111 | from yowsup.layers.protocol_contacts.protocolentities.iq_sync_get import GetSyncIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_contacts.protocolentities.test_iq_sync import Syn | cIqProtocolEntityTest
class GetSyncIqProtocolEntityTest(SyncIqProtocolEntityTest):
def setUp(self):
super(GetSyncIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = GetSyncIqProtocolEntity
users = [
ProtocolTreeNode("user", data = "abc"),
ProtocolTreeNode("use... | de = self.node.getChild("sync")
syncNode.setAttribute("mode", GetSyncIqProtocolEntity.MODE_DELTA)
syncNode.setAttribute("context", GetSyncIqProtocolEntity.CONTEXT_INTERACTIVE)
syncNode.addChildren(users)
|
MechanisM/musicdb | musicdb/classical/fuse_urls.py | Python | agpl-3.0 | 173 | 0.00578 | from django.co | nf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.f | use_index),
url(r'^/(?P<dir_name>[^/]+)$', views.fuse_artist),
)
|
papedaniel/oioioi | oioioi/zeus/utils.py | Python | gpl-3.0 | 1,047 | 0.000955 | from oioioi.base.permissions import make_request_condition
from oioioi.base.utils import request_cached
from oioioi.problems.models import Problem
from oioioi.testrun.utils import testrun_problem_instances
from oioioi.zeus.models import ZeusProblemData
def is_zeus_problem(problem):
try:
return bool(proble... | query_set because `instances` m | ay have some cache in it
problems = frozenset(Problem.objects
.filter(pk__in=[p.problem.pk for p in problem_instances])
.exclude(zeusproblemdata=None))
return [pi for pi in problem_instances if pi.problem in problems]
@request_cached
def zeus_testrun_problem_instances(request):
ret... |
justathoughtor2/atomicApe | cygwin/lib/python2.7/ctypes/util.py | Python | gpl-3.0 | 9,752 | 0.002051 | ######################################################################
# This file should be kept compatible with Python 2.3, see PEP 291. #
######################################################################
import sys, os
# find_library(name) returns the pathname of a library, or None.
if os.name == "nt":
d... | pe(name)
expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
f = os.popen('/sbin/ldconfig -r 2>/dev/null')
try:
data = f.read()
finally:
f.close()
res = re.findall(expr, data)
if not res:
| return _get_soname(_findLib_gcc(name))
res.sort(key=_num_version)
return res[-1]
elif sys.platform == "sunos5":
def _findLib_crle(name, is64):
if not os.path.exists('/usr/bin/crle'):
return None
if is64:
cmd = 'env ... |
TomBaxter/waterbutler | tests/core/test_utils.py | Python | apache-2.0 | 2,451 | 0 | import asyncio
from unittest import mock
import pytest
from waterbutler.core import utils
class TestAsyncRetry:
@pytest.mark.asyncio
async def test_returns_success(self):
mock_func = mock.Mock(return_value='Foo')
retryable = utils.async_retry(5, 0, raven=None)(mock_func)
x = await r... | o',)
assert mock_func.call_count == 6
@pytest.mark.asyncio
async def test_retries_by_its_self(self):
mock_func = mock.Mock(side_effect=Exception())
retryable = utils.async_retry | (8, 0, raven=None)(mock_func)
retryable()
await asyncio.sleep(.1)
assert mock_func.call_count == 9
async def test_docstring_survives(self):
async def mytest():
'''This is a docstring'''
pass
retryable = utils.async_retry(8, 0, raven=None)(mytest)
... |
macosforge/ccs-calendarserver | txdav/common/datastore/podding/migration/test/test_migration.py | Python | apache-2.0 | 30,577 | 0.002943 | ##
# Copyright (c) 2015-2017 Apple 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 by applicable l... | : None,
"puser06": None,
"puser07": None,
"puser08": None,
"puser09": None,
"puser10": None,
}
@inlineCallbacks
def _createShare(self, shareFrom, shareTo, accept=True):
# Invite
txnindex = 1 if shareFrom[0] == "p" else | 0
home = yield self.homeUnderTest(txn=self.theTransactionUnderTest(txnindex), name=shareFrom, create=True)
calendar = yield home.childWithName("calendar")
shareeView = yield calendar.inviteUIDToShare(shareTo, _BIND_MODE_READ, "summary")
yield self.commitTransaction(txnindex)
# A... |
AlexSafatli/EclipseBoardGame | record.py | Python | gpl-2.0 | 2,974 | 0.014459 | # record.py
# -------------------------
# Fall 2012; Alex Safatli
# -------------------------
# Software package for handling
# the recording and calculating
# of player scores for the Eclipse
# board game, along with keeping
# track of individual matches.
# Imports
import os, cPickle, datetime
# Match class. Encaps... | er of games for player.
num = 0
if player not in self.players:
return 0
for m in self.matches:
if player in m.participants:
num += 0
return num
def processMatch(self,match):
maxvp = match.maxvp
for player in match.participa... | ease.
vp = match.results[player]
modifier = 1.0 - 0.2*((maxvp-vp)/(maxvp/10.0))
c = self.changeScore(player,modifier)
match.changes[player] = c
self.matches.append(match)
self.update()
def changeScore(self,player,modifier):
if player n... |
vacancy/TensorArtist | tartist/nn/tfutils.py | Python | mit | 2,691 | 0.00223 | # -*- coding:utf8 -*-
# File : tfutils.py
# Author : Jiayu | an Mao
# Email : maojiayuan@gmail.com
# Date : 1/31/17
#
# This file is part of TensorArtist.
import re
import tensorflow as tf
class TArtGraphKeys:
PLACEHOLDERS = 'placeholders'
TART_VARIABLES = 'tart_variables'
INFERENCE_SUMMARIES = 'inference_summaries'
SCALAR_VARIABLES = 'scalar_variables'
... | ndswith(suffix):
name = name[:-len(suffix)]
return name
def escape_name(tensor):
name = tensor.name
return re.sub(':|/', '_', name)
def clean_summary_suffix(name):
return re.sub('_\d+$', '', name)
def remove_tower_name(name):
return re.sub('^tower/\d+/', '', name)
def format_summary_... |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dump.py | Python | apache-2.0 | 19,483 | 0 | #!/usr/bin/env python
# cardinal_pythonlib/sqlalchemy/dump.py
"""
===============================================================================
Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version ... | fileobj: file-like object to send DDL to
checkfirst: if ``True``, use ``CREATE TABLE IF NOT EXISTS`` or
equivalent.
"""
# http://docs.sqlalchemy.org/en/rel_0_8/faq.html#how-can-i-get-the-create-table-drop-table-output-as-a-string # noqa
| # https://stackoverflow.com/questions/870925/how-to-generate-a-file-with-ddl-in-the-engines-sql-dialect-in-sqlalchemy # noqa
# https://github.com/plq/scripts/blob/master/pg_dump.py
# noinspection PyUnusedLocal
def dump(querysql, *multiparams, **params):
compsql = querysql.compile(dialect=engine.d... |
dNG-git/mp_core | src/dNG/data/upnp/search/common_mp_entry_segment.py | Python | gpl-2.0 | 16,034 | 0.005987 | # -*- coding: utf-8 -*-
"""
MediaProvider
A device centric multimedia solution
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?mp;core
The following license agreement remains valid unless any additions o... |
:since: v0.2.00
"""
AbstractSegment.__init__(self)
self.condition_definition = None
"""
Database query condition definition
"""
self.pre_condition_failed = False
"""
True if a pre-condition fails
"""
#
def _ensure_condition_definition(self):
... |
:since: v0.2.00
"""
if ((not self.pre_condition_failed) and self.condition_definition is None):
self.condition_definition = self._rewrite_criteria_definition_walker(self.criteria_definition)
#
#
def get_count(self):
"""
Returns the total number of matches in this ... |
caphrim007/ansible | lib/ansible/plugins/action/__init__.py | Python | gpl-3.0 | 50,188 | 0.003447 | # Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_funct | ion)
__metaclass__ = type
import base64
import json
import os
import random
import re
import stat
import tempfile
import time
from abc import ABCMeta, abstractmethod
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleActionSkip, AnsibleActionFail
from ansible.... | e, string_types, text_type, iteritems, with_metaclass
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.utils.jsonify import jsonify
from ansible.release import __version__
from ansible.utils.unsafe_proxy import wrap_var
from ... |
lumened/touch-flux | src/demo.py | Python | gpl-2.0 | 805 | 0.012422 | import time, os
import io
import time
import picamera
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV' , '/dev/fb1')
os.putenv('SDL_MOUSEDRV' , 'TSLIB')
os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')
os.putenv('SDL_AUDIODR | IVER' , 'alsa')
# Create an in-memory stream
#my_stream = io.BytesIO()
#with picamera.PiCamera() as camera:
path="/home/pi/videos"
files = os.listdir(path)
files = sorted(files)
last_file = files[-1]
# index = -1
i = 0
while i < len(last_file):
if last_file[i].isdigit():
break
i = i+1;
start_index ... | _index-1
print int(last_file[start_index:end_index])
|
danforthcenter/plantcv | plantcv/plantcv/y_axis_pseudolandmarks.py | Python | mit | 9,161 | 0.002729 | # Function to scan for pseudolandmarks along the y-axis
import cv2
import os
import numpy as np
from plantcv.plantcv._debug import _debug
from plantcv.plantcv import params
from plantcv.plantcv import outputs
from plantcv.plantcv import fatal_error
def y_axis_pseudolandmarks(img, obj, mask, label="default"):
"""... | 1'] / 0.001)
x_centroids.append(int(smx))
y_centroids.append(int(smy))
else:
smx = (largest + smallest) / 2
smy = yval
x_centroids.append(int(smx))
y_centroids.append(int(smy))
left = list(zip(le... | zip(right_points, y_vals))
right = np.array(right)
right.shape = (20, 1, 2)
center_h = list(zip(x_centroids, y_centroids))
center_h = np.array(center_h)
center_h.shape = (20, 1, 2)
img2 = np.copy(img)
for i in left:
x = i[0, 0]
y = i[0, 1]... |
OpenMined/PySyft | packages/syft/src/syft/core/node/common/node_service/generic_payload/syft_message.py | Python | apache-2.0 | 3,573 | 0.002239 | # stdlib
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
# third party
from nacl.signing import VerifyKey
from pydantic import BaseModel
from pydantic.error_wrappers import ValidationError as PydanticValidationError
# relative
from .....common.message import Immediat... | estPayload
reply_payload_type = ReplyPayload
def __init__(
self,
address: Address,
kwargs: Optional[Dict[str, Any]] = None,
msg_id: Optional[UID] = None,
reply_to: Optional[Address] = None,
reply: bool = False,
) -> None:
super().__init__(address=addr... | sg_id)
self.reply_to = reply_to
self.reply = reply
self.kwargs = kwargs if kwargs else {}
@property
def payload(self) -> Payload:
kwargs_dict = {}
if hasattr(self.kwargs, "upcast"):
kwargs_dict = self.kwargs.upcast() # type: ignore
else:
... |
waynew/flaskpypi | tests/test_flaskpypi.py | Python | bsd-3-clause | 752 | 0.00266 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_flaskpypi
----------------------------------
Tests for `flaskpypi` module.
"""
import pytest
from flaskpypi import flaskpypi
# Code from https://wiki. | python.org/moin/PyPISimple
from xml.etree import ElementTree
from urllib.request import urlopen
def get_distributions(simple_index='https://pypi.python.org/simple/'):
with urlopen(simple_index) as f:
tree = ElementTree.parse(f)
return [a.text for a in tree.iter('a')]
def scrape_links(dist, simple_inde... | ython.org/simple/'):
with urlopen(simple_index + dist + '/') as f:
tree = ElementTree.parse(f)
return [a.attrib['href'] for a in tree.iter('a')]
def test_this_is_a_test():
assert True
|
shakamunyi/neutron-vrrp | neutron/db/migration/alembic_migrations/versions/19180cf98af6_nsx_gw_devices.py | Python | apache-2.0 | 3,313 | 0.000906 | # Copyright 2014 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 ... | umn('connector_type', sa.String(length=10), nullable=True),
sa.Column('connector_ip', sa.String(length=64), nullable=True),
sa.Column('status', sa.String(length=16), nullable=True),
sa.PrimaryKeyConstraint('id'))
# Create a networkgatewaydevice for each existing reference.
# For exis | ting references nsx_id == neutron_id
# Do not fill conenctor info as they would be unknown
op.execute("INSERT INTO networkgatewaydevices (id, nsx_id, tenant_id) "
"SELECT gw_dev_ref.id, gw_dev_ref.id as nsx_id, tenant_id "
"FROM networkgatewaydevicereferences AS gw_dev_ref "
... |
mh03r932/raspi2dht11 | examples/google_spreadsheet_twosens.py | Python | mit | 6,208 | 0.016591 | #!/usr/bin/python
# Google Spreadsheet DHT Sensor Data-logging Example
# Depends on the 'gspread' and 'oauth2client' package being installed. If you
# have pip installed execute:
# sudo pip install gspread oauth2client
# Also it's _very important_ on the Raspberry Pi to install the python-openssl
# package becau... | , temp = Adafruit_DHT.read(DHT_TYPE, inputpin)
# Reading the sensor depends on timing so to make sure we are not busy anymore insert a little sleep
# Skip to the next reading if a valid measurement couldn't be taken.
# T | his might happen if the CPU is under a lot of load and the sensor
# can't be reliably read (timing is critical to read the sensor).
if humidity is None or temp is None:
time.sleep(2)
attempts += 1
continue
print 'Temperature{0}: {1:0.1f} C'.format(inputpin,temp)
print 'Humidity{0}: {1:0.1f} %'.form... |
krfkeith/enough | gui/Keymap.py | Python | gpl-3.0 | 10,827 | 0.002586 | # Copyright (c) 2007 Enough Project.
# See LICENSE for details.
"""The things a keymap does:
1. Pass given keys to 'next' keymap (considered more 'specific') which
is stronger/overrides the keymap itself.
2. If the next keymap does not know the key, then it tries to handle
it itself according to a map it holds th... | self.notify_replace_item = self.obs_dict.notify.replace_item
self.next_keymap = None
self.key_registrations = {}
self.group_registrations = {}
self.disabled_group_registrations = {}
self.is_active = False
def __contains__(self, key):
if self.next_keymap i... | self.key_registrations:
return True
if key in self.group_registrations:
return True
return False
def iterkeys(self):
for key, value in self.iteritems():
yield key
def iteritems(self):
overridden = set()
if self.next_keymap is not... |
ComputationalSystemsBiology/GINsimScripts | stable_core/stable_core.py | Python | gpl-3.0 | 2,265 | 0.007947 | import jarray
g = gs.open(gs.args[0])
istates = gs.associated(g, "initialState", True).getInitialStates()
ssrv = gs.service("stable")
def copy_path(values, coreNodes):
n = len(coreNodes)
path = jarray.zeros(n, 'b')
i = 0
for idx in coreNodes:
path[i] = values[idx]
i += 1
retur... | ident = False
break
idx += 1
if ident:
return
stack.append( path )
return
idx, mx = jokers[0]
njk = jokers[1:]
for v in xrange(mx):
values[idx] = v
unfold_rec( | values, njk, stack, coreNodes)
values[idx] = -1
def unfold(values, maxvalues, stack, coreNodes):
n = len(values)
jokers = [ (idx, maxvalues[idx]+1) for idx in xrange(n) if values[idx] == -1 ]
unfold_rec(values, jokers, stack, coreNodes)
return stack
def find_stable_states(model, nodeOrder):
... |
gkoehler/TootList | TootList/manage.py | Python | mit | 257 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TootList.settings.local") |
from | django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
armstrong/armstrong.apps.events | armstrong/apps/events/tests/managers.py | Python | apache-2.0 | 2,622 | 0.002288 | import random
from datet | ime import date, timedelta, datetime
from django.core.urlresolvers import reverse
from ._utils import generate_random_event, TestCase, hours_ago, hours_ahead
from ..models import Event
class EventManagerTestCase(TestCase):
def test_upcoming_future(self):
event_future = generate_random_event(hours_ahead(1... | oming())
def test_upcoming_in_progress(self):
event_inprogress = generate_random_event(hours_ago(1), hours_ahead(1))
self.assertTrue(event_inprogress in Event.objects.upcoming())
self.assertTrue(event_inprogress in Event.objects.upcoming(days=1))
def test_upcoming_happened_today(self):... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/utils/simplejson/scanner.py | Python | bsd-3-clause | 2,009 | 0.002987 | """
Iterator based sre token scanner
"""
import sre_parse, sre_compile, sre_constants
from sre_constants import BRANCH, SUBPATTERN
from re import VERBOSE, MULTILINE, DOTALL
import re
__all__ = ['Scanner', 'pattern']
FLAGS = (VERB | OSE | MULTILINE | DOTALL)
class Scanner(object):
def __init__(self, lexicon, flags=FLAGS):
self.actions = [None]
# combine phrases into a compound pattern
s = s | re_parse.Pattern()
s.flags = flags
p = []
for idx, token in enumerate(lexicon):
phrase = token.pattern
try:
subpattern = sre_parse.SubPattern(s,
[(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))])
except sre_constants... |
jxp360/golfapp | golfapp/apps/piffycup/urls.py | Python | gpl-2.0 | 191 | 0.026178 | from django.conf.urls import patterns, url
import views as views
urlpatterns = patterns('',
#url( | r'^$', views.index, name='index'),
#url(r'index.html', views.index, | name='index')
)
|
Alexander-M-Waldman/local_currency_site | lib/python2.7/site-packages/allauth/socialaccount/providers/basecamp/views.py | Python | gpl-3.0 | 1,123 | 0 | import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackV | iew)
from .provider import BasecampProvider
class BasecampOAuth2Adapter(OAuth2Adapter):
provider_id = BasecampProvider.id
access_token_url = 'https://launchpad.37signals.com/authorization/token?type=web_server' # noqa
authorize_url = 'https://launchpad.37signals.com/authorization/new'
profile_url = '... | ': 'Bearer {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_vie... |
idlesign/django-sitemessage | sitemessage/management/commands/sitemessage_send_scheduled.py | Python | bsd-3-clause | 1,014 | 0.001972 | from traceback import format_exc
from django.core.management.base import BaseCommand
from ...toolbox import | send_scheduled_messages
class Command(BaseCommand):
help = 'Sends scheduled messages (both in pending and error statuses).'
def add_arguments(self, parser):
parser.add_argument(
'--priority', action='store', dest='priority', default=None,
help='Allows to filter scheduled mess... | handle(self, *args, **options):
priority = options.get('priority', None)
priority_str = ''
if priority is not None:
priority_str = f'with priority {priority} '
self.stdout.write(f'Sending scheduled messages {priority_str} ...\n')
try:
send_scheduled_mes... |
DeveloperMal/wger | wger/exercises/management/commands/download-exercise-images.py | Python | agpl-3.0 | 5,449 | 0.002936 | # -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager 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 option) any ... | os.path.basename(imag | e_name),
File(img_temp),
)
image.save()
else:
self.stdout.write(' No images for this exercise, nothing to do')
|
aldebaran/qibuild | python/qisys/sort.py | Python | bsd-3-clause | 4,651 | 0.00172 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Topological sort """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ imp... | visited = []
deps = data.get(head, list())
if head in visited:
if head == top_node and raise_exception:
raise DagError(head, head, result)
return result
visited.append(head)
for i in deps:
try:
result.index(i)
except ValueError:
#... | opological_sort(data, i, top_node, raise_exception, result, visited)
result.append(head)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.