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 |
|---|---|---|---|---|---|---|---|---|
davidbradway/fusefit | webui/app/views.py | Python | mit | 2,160 | 0.008333 | import os
# We'll render HTML templates and access data sent by P | OST
# using the re | quest object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, render_template, request, flash, redirect, url_for, send_from_directory
from app im... |
Open365/Open365 | lib/EyeosApi/Logout.py | Python | agpl-3.0 | 1,097 | 0.002735 | import time
from lib.DomainObjects.EyeosCard import EyeosCard
from lib.Errors.EyeosAPIError import EyeosAPIError
from lib.EyeosApi.EyeosApiCall import EyeosApiCall
from lib.Settings import Set | tings
from lib.Wrappe | rs.Logger import Logger
class Logout:
def __init__(self, injected_proxy_ip=None, injected_eyeos_api_call=None):
self.settings = Settings().getSettings()
self.proxy_ip = injected_proxy_ip or self.settings['general']['public_hostname']
self.logger = Logger(__name__)
self.eyeos_api_c... |
PieterMostert/Lipgloss | model/lipgloss/lp_recipe_problem.py | Python | gpl-3.0 | 17,317 | 0.009875 | # LIPGLOSS - Graphical user interface for constructing glaze recipes
# Copyright (C) 2017 Pieter Mostert
# 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, version 3 of the License.
# This progra... | iables[k]
try:
del self.constraints['ingredient_'+i+'_lower'] # Is this necessary?
del self.constraints['ingredient_'+i+'_upper'] # Is this necessary?
except:
pass
self.constraints['ing_total'] = self.lp_var['ingredient_total'] == \
... | ient(self, i, core_data):
pass
def update_other_restrictions(self):
"To be run when CoreData.other_dict is changed. May be better to do this for a specific other restriction"
for i in self.other_dict:
ot = 'other_'+i
coefs = self.other_dict[i].numerator_coefs
... |
savi-dev/quantum | quantum/plugins/ryu/nova/linux_net.py | Python | apache-2.0 | 2,805 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# <yamahata at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... | 'ofport', run_as_root=True)
return int(out.strip())
class LinuxOVSRyuInterfaceDriver(linux_net.LinuxOVSInterfaceDriver):
def __init__(self):
super(LinuxOVSRyuInterfaceDriver, self).__init__()
LOG.debug('ryu rest host %s', FLAGS.linuxnet_ovs_ryu_api_host)
self.ryu_cl... | FLAGS.linuxnet_ovs_integration_bridge)
if linux_net.binary_name == 'nova-network':
for tables in [linux_net.iptables_manager.ipv4,
linux_net.iptables_manager.ipv6]:
tables['filter'].add_rule(
'FORWARD',
'--in-int... |
swilly22/redisgraph-py | redisgraph/execution_plan.py | Python | bsd-2-clause | 5,416 | 0.001477 | class Operation:
"""
Operation, single operation within execution plan.
"""
def __init__(self, name, args=None):
"""
Create a new operation.
Args:
name: string that represents the name of the operation
args: operation arguments
"""
self.n... | ionPlan):
return False
# get root for both plans
root_a = self.structured_plan
root_b = o.structured_plan
# compare execution trees
return self._compare_operations(root_a, root_b)
def _operation_traverse(self, op, op_f, aggregate_f, combine_f):
"""
... | aggregate_f: aggregation function applied for all children of a single operation
combine_f: combine function applied for the operation result and the children result
"""
# apply op_f for each operation
op_res = op_f(op)
if len(op.children) == 0:
return op_res # ... |
webmedic/booker | src/gdata/blogger/client.py | Python | mit | 6,686 | 0.005085 | #!/usr/bin/env python
#
# Copyright (C) 2009 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwarg | s)
GetBlogComments = get_blog_comments
def get_blog_archive(self, blog_id, auth_token=None, **kwargs):
return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token,
**kwargs)
GetBlogArchive = get_blog_archive
def add_post(self, blog_id, title, body, labels=None, draft=... |
seatme/nucleon.amqp | nucleon/amqp/encoding.py | Python | lgpl-3.0 | 1,062 | 0.001883 | from .spec import BASIC_PROPS_SET, encode_basic_properties
def encode_message(frame, headers, body, frame_size):
"""Encode message headers and body as a sequence of frames."""
for f in frame.encode():
yield f
props, headers = split_headers(headers, BASIC_PROPS_SET)
if headers:
props['h... | eld ( | 0x03, payload)
|
indro/t2c | apps/external_apps/django_openid/admin.py | Python | mit | 658 | 0.009119 | from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib import | admin
from django.contrib.admin.sites import NotRegistered
from models import UserOpenidAssociation
class OpenIDInline(admin.StackedInline):
model = UserOpenidAssociation
class UserAdminWithOpenIDs(UserAdmin):
inlines = [OpenIDInline]
# Add OpenIDs to the user admin, but only if User has been registered
tr... | (Nonce)
#admin.site.register(Association)
|
instana/python-sensor | tests/apps/grpc_server/__init__.py | Python | mit | 709 | 0.002821 | # (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2019
import os
import sys
import time
import threading
if 'GEVENT_TEST' not in os.environ and 'CASSANDRA_TEST' not in os.environ and sys.version_info >= (3, 5, 3):
# Background RPC application
#
# Spawn the background RPC app that the tests will ... | tests.apps.grpc_server
from .stan_server import StanServicer
stan_servicer = StanServicer()
rpc_server_thread = threading.Thread(target=stan_servicer.start_server)
rpc_server_thread.daemon = True
rpc_server_thread.name = "Background RPC app"
print("Starting background RPC app...")
rpc_s | erver_thread.start()
time.sleep(1) |
genome/flow-core | flow/shell_command/fork/commands/service.py | Python | agpl-3.0 | 747 | 0.001339 | from flow.commands.service import ServiceCommand
from flow.configuration.inject.broker import BrokerConfiguration
from flow.configuration.inject.redis_conf import RedisConfiguration
from flow.configuration.inject.service_locator import ServiceLocatorConfiguration
from flow.shell_command | .fork.handler import ForkShellCommandMessageHandler
import logging
LOG = logging.getLogger(__name__)
class ForkShellCommand(ServiceCommand):
| injector_modules = [
BrokerConfiguration,
RedisConfiguration,
ServiceLocatorConfiguration,
]
def _setup(self, *args, **kwargs):
self.handlers = [self.injector.get(ForkShellCommandMessageHandler)]
return ServiceCommand._setup(self, *args, **kwargs)
|
uni2u/neutron | neutron/plugins/openvswitch/common/config.py | Python | apache-2.0 | 4,210 | 0 | # Copyright 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | IP packet carrying GRE/VXLAN tunnel.")),
cfg.BoolOpt('enable_distributed_routing', default=False,
help=_("Make the l2 agent run in DVR mode.")),
]
cfg.CONF.register_opts(ovs_opts, "OVS")
cfg.CONF.register_opts(agent_opts, "AGENT")
config.regist | er_agent_state_opts_helper(cfg.CONF)
config.register_root_helper(cfg.CONF)
|
LaoZhongGu/kbengine | kbe/src/lib/python/Tools/i18n/msgfmt.py | Python | lgpl-3.0 | 7,051 | 0.002979 | #! /usr/bin/env python3
# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
G... | on.", file=sys.stderr)
return
for filename in args:
make(filen | ame, outfile)
if __name__ == '__main__':
main()
|
fafhrd91/mdl | mdl/registry.py | Python | apache-2.0 | 3,760 | 0 | from __future__ import absolute_import
import zope.interface.interface
from zope.interface.adapter import AdapterLookup as _AdapterLookup
from zope.interface.adapter import AdapterRegistry as _AdapterRegistry
from zope.interface.registry import Components, ComponentLookupError
__all__ = ('Registry',)
NO_CONTRACTS =... | terface, name, default)
def install(self, use_contracts=False):
zope.interface.interface.adapter_hooks.append(self._adapter_hook)
if use_contracts:
self.enable_contracts()
def uninstall(self):
if self._adapter_hook in | zope.interface.interface.adapter_hooks:
zope.interface.interface.adapter_hooks.remove(self._adapter_hook)
def queryAdapter(self, object, interface, name=u'', default=None):
if isinstance(object, (tuple, list)):
adapter = self.adapters.queryMultiAdapter(
object, inte... |
luiscberrocal/django-test-tools | tests/mixins.py | Python | mit | 993 | 0.001007 | import json
import os
class TestFixtureMixin(object):
def get_json_data(self, filename):
import environ
full_path = (environ.Path(__file__) - 1).root
fixture_path = None
max_levels = 4
current_level = 1
while fixture_path is None:
new_path = '{}{}{}'.fo... |
fixture_path = new_path
else:
full_path = os.path.split(full_path)[0]
if current_level == max_levels:
break
current_ | level += 1
if fixture_path is None:
started_at = (environ.Path(__file__) - 1).root
raise ValueError('Could not find fixtures folder in {}'.format(started_at))
json_filename = '{}{}{}'.format(fixture_path, os.sep, filename)
with open(json_filename, 'r', encoding='utf-8') ... |
albertz/music-player | mac/pyobjc-framework-Cocoa/PyObjCTest/test_nsmetadata.py | Python | bsd-2-clause | 2,524 | 0.003566 | from Foundation import *
from PyObjCTools.TestSupport import *
try:
unicode
except NameError:
unicode = str
class TestNSMetaData (TestCase):
def testConstants(self):
self.assertIsInstance(NSMetadataQueryDidStartGatheringNotification, unicode)
self.assertIsInstance(NSMetadataQueryGatheringP... | emIsDownloadingKey, unicode)
self.assertIsInstance(NSMetadataUbiquitousItemIsUploadedKey, unicode)
| self.assertIsInstance(NSMetadataUbiquitousItemIsUploadingKey, unicode)
self.assertIsInstance(NSMetadataUbiquitousItemPercentDownloadedKey, unicode)
self.assertIsInstance(NSMetadataUbiquitousItemPercentUploadedKey, unicode)
def testMethods(self):
self.assertResultIsBOOL(NSMetadataQuery.st... |
fbradyirl/home-assistant | homeassistant/components/rest/binary_sensor.py | Python | apache-2.0 | 4,542 | 0.000881 | """Support for RESTful binary sensors."""
import logging
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES_SCHEMA,
PLATFORM_SCHEMA,
BinarySensorDevice,
)
from homeassistant.const import (
CONF_AUTHENTICA... | ry_info=None):
"""Set up the REST binary sensor."""
name = config.get(CONF_NAME)
resource = config.get(CONF_RESOURCE)
method = config.get(CONF_METHOD)
payload = config.get(CONF_PAYLOAD)
verify_ssl = config.get(CONF_VERIFY_SSL)
ti | meout = config.get(CONF_TIMEOUT)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
headers = config.get(CONF_HEADERS)
device_class = config.get(CONF_DEVICE_CLASS)
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass =... |
pyaiot/pyaiot | utils/mqtt/mqtt-test-node.py | Python | bsd-3-clause | 5,525 | 0 | import json
import logging
import asyncio
import random
import socket
from hbmqtt.client import MQTTClient, ClientException
from hbmqtt.mqtt.constants import QOS_1
logging.basicConfig(format='%(asctime)s - %(name)14s - '
'%(levelname)5s - %(message)s')
logger = logging.getLogger("mqtt_test_... | from gateway")
# Blocked here until a message is received
message = await mqtt_client.deliver_message()
except ClientException as ce:
logger.error("Client exception: {}".format(ce))
| break
except Exception as exc:
logger.error("General exception: {}".format(exc))
break
packet = message.publish_packet
topic_name = packet.variable_header.topic_name
data = packet.payload.data.decode()
logger.debug("Received message from gateway: {} ... |
BD2KGenomics/toil-old | src/toil/batchSystems/combinedBatchSystem.py | Python | mit | 4,039 | 0.013122 | #!/usr/bin/env python
#Copyright (C) 2011 by Benedict Paten (benedictpaten@gmail.com)
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rig... | #copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY... | MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN... |
naelstrof/PugBot-Discord-Django | botapi/apache/override.py | Python | mit | 66 | 0 | f | rom botapi.settings import | *
DEBUG = True
ALLOWED_HOSTS = ['*']
|
asmi92/odu-acm | raffleslave.py | Python | mit | 1,668 | 0.020983 | import tweepy
from pymongo import MongoClient
class RaffleSlave:
"The class responsbile for a single raffle, a new instance for each individual raffle"
Params = None
api = None
alive = True
def __init__(self, hashtag, max, id, owner ):
self.Params = {}
self.Params['max'] = max
... | uth )
def update(self):
public_tweets = self.api.search( '@'+self.Params['owner']+' #'+self.Params['hashtag'] )
client = MongoClient()
db = client.raftl
tweetcollection = db.tweets
followers = self.api.followers_ids(self.Params['owner'])
for tweet in public_tweets:... | tweetcollection.update_one( {'_id':tweet.id}, {'$set': {'_id':tweet.id, 'user_id':tweet.author.id, 'following':tweet.author.id in followers,'raffle_id':self.Params['_id'], 'body':tweet.text, 'username':tweet.author.screen_name, 'profile_img':tweet.author.profile_image_url_https } }, True )
#tweetco... |
redhatrises/freeipa | ipaclient/remote_plugins/2_164/passwd.py | Python | gpl-3.0 | 2,428 | 0.000824 | #
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
# pylint: disable=unused-import
import six
from . import Command, Method, Object
from ipalib import api, parameters, output
from ipalib.parameters import DefaultFrom
from ipalib.plugable import Registry
from ipalib.text import _
from ipapython.dn ... |
if six. | PY3:
unicode = str
__doc__ = _("""
Set a user's password
If someone other than a user changes that user's password (e.g., Helpdesk
resets it) then the password will need to be changed the first time it
is used. This is so the end-user is the only one who knows the password.
The IPA password policy controls how o... |
lavalamp-/ws-backend-community | lib/sqlalchemy/models/auth.py | Python | gpl-3.0 | 178 | 0 | # -*- coding: utf-8 -*-
from __future__ impo | rt absolute_import
import rest.models
from .base import from_django_model
WsAuthGroup = from_django_model(rest.models.WsAut | hGroup)
|
FaustineMaffre/GossipProblem-PDDL-generator | neggoalsparser/parser.py | Python | mit | 3,303 | 0.003633 | """ Parser for the negative goals.
Allows to parse sets of the form, e.g., {i-j-k : i!=j & j!=k & i!=k} U
{i,j : i<3 & j<=3}, meaning that i should not know whether j knows the secret
of k, for i, j, k distinct, and that i should not know the secret of j for
either i = 1, 2 and j = 1, 2, 3.
Also allows instantiated neg... | eg2 import *
import re
""" Description of the grammar of negative goals.
Comp ::= = | != | <= | >= | < | >
Int ::= <integer>
AgtName ::= <lower-case letter> | AgtName<lower-case letter> | AgtName<digit>
Cst ::= AgtName Com | p AgtName | AgtName Comp Int
Csts ::= Cst | Csts & Csts
Agts ::= AgtName | Agts-Agts
AgtsInst ::= Int | AgtsInst-AgtsInst
AgtsInsts ::= AgtsInst | AgtsInsts, AgtsInsts
Set ::= {Agts : Csts} | {AgtsInsts}
Sets ::= Set | Sets U Sets
"""
""" Comparison operator.
"""
class Comp(str):
grammar = re.compile(r'(=|!=|<=|>... |
prontointern/django-contact-form | django_contact_form_project/contacts/tests/test_views.py | Python | mit | 14,146 | 0.000141 | from mock import patch
from django.test import TestCase
from django.core.urlresolvers import reverse
from ..models import Contact
class ContactViewTest(TestCase):
def setUp(self):
self.url = reverse('contact')
self.response = self.client.get(self.url)
def test_contact_view_is_accessible(sel... | 'Smith',
'email': 'john@smith.com'
}
response = self.client.post(
| self.url,
data=data
)
self.assertRedirects(
response,
'/thankyou/?firstname=John',
status_code=302,
target_status_code=200
)
@patch('contacts.views.GeoIP')
def test_redirected_page_should_contain_firstname(self, mock):
... |
SimonDevon/simple-python-shapes | name-draw1.py | Python | mit | 605 | 0.006612 | import turtle
import random
# Let's create our turtle and call him Simon!
simon = turtle.Turtle()
# We'll set the background to black
turtle.bgcolor("black")
# This is our list of colours
colors = ["red", "green", "blue"]
# We need to ask the user their name
name = turtle.tex | tinput("Name", "What is your name?")
simon.penup()
for number in range(30): # We'll draw the name 30 times
| simon.forward(number * 10)
simon.write(name, font=("Arial", 12, "bold")) # This writes the name and chooses a font
simon.right(92)
simon.pencolor(random.choice(colors)) # This chooses a random colour
|
manjaro/thus | thus/misc/validation.py | Python | gpl-3.0 | 5,581 | 0.000896 | # -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-
# Miscellaneous validation of user-entered data
#
# Copyright (C) 2005 Junta de Andalucía
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd.
# Copyright (C) 2015 Manjaro (http://manjaro.org)
#
# Validation library.
# Created by Antonio... | f a proposed user name.
@return empty list (valid) or list of:
- C{NAME_LENGTH} wrong length.
- C{NAME_BADCHAR} contains invalid characters.
- C{NAME_BADHYPHEN} starts or ends with a hyphen.
- C{NAME_BADDOTS} contains consecutive/initial/final dots."""
impor... | (name) < 1 or len(name) > 40:
result.add(NAME_LENGTH)
regex = re.compile(r'^[a-z0-9.\-]+$')
if not regex.search(name):
result.add(NAME_BADCHAR)
if name.startswith('-') or name.endswith('-'):
result.add(NAME_BADHYPHEN)
if '.' in name:
result.add(NAME_BADDOTS)
return ... |
googleads/googleads-adxseller-examples | python/v2.0/generate_report.py | Python | apache-2.0 | 2,740 | 0.006204 | #!/usr/bin/python
# coding: utf-8
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file e | xcept 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... |
TIY-Durham/TIY-Overflow | api/overflow/urls.py | Python | gpl-3.0 | 1,416 | 0.000706 | """overflow URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
# from rest_framework import routers
from rest_framework_nested import routers
from stackoverflow import views
router = routers.SimpleRouter()
r... | tions', views.QuestionViewSet)
router.register(r'users', views.UserViewSet)
questions_router = routers.NestedSimpleRouter(router, r'questions', lookup='question')
questions_router.register(r'answers', views.AnswerViewSet)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router... |
ytanay/thinglang | thinglang/parser/statements/break_statement.py | Python | mit | 770 | 0.003896 | from thinglang.compiler.opcodes import OpcodeJump
from thinglang.parser.blocks.conditional import Conditional
from thinglang.parser.blocks.loop import Loop
from thinglang.parser.nodes import BaseNode
class BreakStatement(BaseNode):
"""
Jumps to the end of the currently executing loop or conditional
"""
... | def compile(self, context): # TODO: assert no children
container = self.ascend(Loop)
if not container:
raise Exception('Cannot break outside of | loop') # TODO: should be StructureError
context.append(OpcodeJump(context.jump_out[container]), self.source_ref)
|
khalibartan/pgmpy | pgmpy/factors/discrete/__init__.py | Python | mit | 236 | 0 | from .Disc | reteFactor import State, DiscreteFactor
from .CPD import TabularCPD
from .JointProbabilityDistribution import JointProbabilityDistribution
__all__ = ['TabularCPD',
'DiscreteFactor',
'State'
| ]
|
utarsuno/urbtek | nexus_django/nexus_front_end/apps.py | Python | apache-2.0 | 103 | 0 | from django.apps | import AppConfig
class NexusFrontEndConfig(AppConfig):
name = 'nexus_fro | nt_end'
|
sysadminmatmoz/ingadhoc | sale_exceptions_ignore_approve/__openerp__.py | Python | agpl-3.0 | 1,775 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | r',
'license': 'AGPL-3',
'summary': 'Allow to define purchase prices on different currencies using\
replenishment cost field',
"description": """
Sale Exceptions Ingore Approve Directly
=======================================
When Ignoring a sale Exception, approve directly the sale order
""",
"dep... | ption_confirm_view.xml',
'views/sale_view.xml',
],
'demo': [
],
'test': [
],
"installable": True,
'auto_install': False,
'application': False,
}
|
PressLabs/silver | silver/tests/unit/test_invoice.py | Python | apache-2.0 | 8,323 | 0.00036 | # Copyright (c) 2015 Presslabs SRL
#
# 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 writ... | assert invoice in queryset
def test_invoice_overdue_queryset(self):
invoices = InvoiceFactory.create_batch(3)
invoices[0].due_date = date.today() - timedelta(days=1)
invoices[0].issue()
invoices[1].due_date = date.today() - timedelta(days=3)
invoice | s[1].issue()
invoices[2].due_date = date.today() - timedelta(days=31)
invoices[2].issue()
invoices[2].pay()
queryset = Invoice.objects.overdue()
assert queryset.count() == 2
for invoice in invoices[:2]:
assert invoice in queryset
def test_invoice_overd... |
msullivan/advent-of-code | 2021/14balt.py | Python | mit | 1,674 | 0 | #!/usr/bin/env python3
"""
Find characters deep in the expanded string, for fun.
"""
import sys
from collections import Counter
def real_step(s, rules):
out = ""
for i in range(len(s)):
out += s[i]
k = s[i:i+2]
if k in rules:
out += rules[k]
return out
def step(cn... | ]] += v
return sum(lcnt.values())
def get_char(s, idx, iters, rules):
for i in range(iters):
h = len(s) // 2
first = s[:h+1]
sz = size(first, iters - i, rules)
if idx < sz:
s = real_step(first, rules)
else:
s = real_step(s[h:], rules)
... | in data[2:])
# Make sure it works
t = s
for i in range(4):
t = real_step(t, rules)
for idx in range(len(t)):
c = get_char(s, idx, 4, rules)
assert t[idx] == c
# find some random characters deep into it
print(size(s, 40, rules))
start = 7311752324710
out = ""
... |
damiendr/callipy | setup.py | Python | bsd-2-clause | 1,056 | 0.004735 | #!/usr/bin/env python
from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
readme = path.join(here, 'README.md')
try: |
from pypandoc import convert
long_description = convert(readme, 'rst')
except ImportError:
print("warning: pypandoc module not found, could not convert Markdown to RST")
with open(readme, 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='callipy',
description='Calli... |
author_email='damien.drix+pypi@gmail.com',
url='https://github.com/damiendr/callipy',
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: IPython',
],
py_modules=['callipy'],
install_requires=[
"runipy",
"ipython",
],
)
|
landlab/landlab | landlab/components/profiler/profiler.py | Python | mit | 13,854 | 0.000217 | # coding: utf8
# ! /usr/env/python
"""profiler.py component to create profiles with user-defined endpoints."""
from collections import OrderedDict
import numpy as np
from matplotlib import cm, colors, pyplot as plt
from landlab.components.profiler.base_profiler import _BaseProfiler
class Profiler(_BaseProfiler):
... | ile is | processed by segment. Segments are bound by successive
endpoints. The cumulative distance along the profile is accumulated by
iteratively adding segment lengths.
"""
self._data_struct = OrderedDict()
grid = self._grid
endnodes = self._end_nodes
cum_dist = 0
... |
alessiamarcolini/deepstreet | utils/format_validation_filenames_util.py | Python | mit | 408 | 0.002451 | import os
with open("validation_classes.csv", "r") as f:
rows = f.readlines()
rows = rows[1:-1]
rows = [x for x in rows if x != "\n"]
path = "dataset/val/"
for row i | n rows:
rsplit = row.split(";")
filename = rsplit[0]
c = int(rsplit[1])
new_filename = format(c,'05d') + "_" + filename
if os.path.exists(path + filename):
os.rename(path + filename, path + new_filename) | |
devfirefly/PyFlax | Tween.py | Python | mit | 4,128 | 0.03125 | import math
def linear(x):
return x
def quad(x):
return x*x
def quadout(x):
return 1 -quad(x)
def cubic(x):
return x*x*x
def cubicout(x):
return 1 - cubic(x)
def quint(x):
return x*x*x*x
def quintout(x):
return 1-quint(x)
def sine(x):
return -math.cos(p * (math.pi * .5)) + 1
def sineout(... | e":sine,
"sine-out":sineout,
"cosine":cosine,
"cosine-out":cosineout,
}
def findDistance(x,y):
if not x or not y:
return 0
else:
return max(x,y)-min(x,y)
class single:
def __init__(self,time,item,exp,mode="linear"):
self.progress = 0
self.rate = time > 0 and 1 ... | = item
self.current = item
self.diff = exp-item
self.mode = mode
self.exp = exp
self.done = False
self.delay = 0
self.initt = 0
def get(self):
return self.current
def update(self,dt):
self.progress = self.progress + self.rate * ... |
hxsf/OnlineJudge | problem/views.py | Python | mit | 12,819 | 0.001668 | # coding=utf-8
import zipfile
import re
import os
import hashlib
import json
import logging
from django.shortcuts import render
from django.db.models import Q, Count
from django.core.paginator import Paginator
from rest_framework.views import APIView
from django.conf import settings
from account.models import SUPER... | le_name) is not None
def post(self, request):
if "file" not in request.FILES:
return error_response(u"文件上传失败")
f = request.FILES["file"]
tmp | _zip = "/tmp/" + rand_str() + ".zip"
try:
with open(tmp_zip, "wb") as test_case_zip:
for chunk in f:
test_case_zip.write(chunk)
except IOError as e:
logger.error(e)
return error_response(u"上传失败")
test_case_file = zipfile.Zi... |
xmbcrios/xmbcrios.repository | script.module.urlresolver/lib/urlresolver/plugins/limevideo.py | Python | gpl-2.0 | 3,459 | 0.005204 | '''
Limevideo urlresolver plugin
Copyright (C) 2013 Vinnydude
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 ... | e] = value
data.update(captcha_lib.do_captcha(html))
html = self.net.http_POST(url, data).content
sPattern = '<script type=(?:"|\')text/javascript(?:"|\')>(eval\('
sPa | ttern += 'function\(p,a,c,k,e,d\)(?!.+player_ads.+).+np_vid.+?)'
sPattern += '\s+?</script>'
r = re.search(sPattern, html, re.DOTALL + re.IGNORECASE)
if r:
sJavascript = r.group(1)
sUnpacked = jsunpack.unpack(sJavascript)
sPattern = '<embed id="np_vid"type="vi... |
quxiaolong1504/dpark | tests/test_serialize.py | Python | bsd-3-clause | 590 | 0.008475 | import unittest
from dpark.serialize import dump_closure, load_c | losure
class TestSerialize(unitte | st.TestCase):
def testNameError(self):
def foo():
print x
dumped_func = dump_closure(foo)
func = load_closure(dumped_func)
self.assertRaises(NameError, func)
x = 10
def testNoneAsFreeVar(self):
y = None
x = 10
... |
cjaymes/pyscap | src/scap/model/xs/ExtensionType.py | Python | gpl-3.0 | 2,037 | 0.003927 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | : None},
{'tag_name': 'attributeGroup', 'list': 'tags', 'class': 'AttributeGroupType', 'min': 0, 'max': None},
{'tag_name': 'anyAttribute', 'list': 'tags', 'class': 'WildcardType', 'min': 0},
],
'attributes': {
| 'base': {'type': 'QNameType', 'required': True},
}
}
def get_defs(self, schema, top_level):
logger.debug('Base: ' + self.base)
# TODO unable to map xmlns because ET doesn't retain it
base_ns, base_name = [self.base.partition(':')[i] for i in [0,2]]
top_level.set_s... |
djtaylor/cloudscape-DEPRECATED | python/cloudscape/engine/api/core/request.py | Python | gpl-3.0 | 15,200 | 0.010724 | import os
import re
import json
import importlib
# Django Libraries
from django.http import HttpResponse, HttpResponseServerError
# CloudScape Libraries
from cloudscape.common import config
from cloudscape.common import logger
from cloudscape.common.vars import T_BASE
from cloudscape.engine.api.base import APIBase
fr... | if not 'action' in self.request:
return self._req_error('Request body requires an <action> parameter for endpoint pathing')
self.action = self.request['action']
# Get the request path
self.path = re.compile | ('^\/(.*$)').sub(r'\g<1>', self.request_raw.META['PATH_INFO'])
# Set the request endpoint
self.endpoint = '%s/%s' % (self.path, self.action)
# Map the path to a module, class, and API name
self.handler_obj = EndpointMapper(self.endpoint, self.method).handler()
if no... |
darren-wang/ks3 | keystone/server/eventlet.py | Python | apache-2.0 | 5,193 | 0.001541 |
# Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | h(self, launcher):
self.server.listen()
if self.workers > 1:
# Use multi-process launcher
launcher.launch_service(self.server, self.workers)
else:
# Use single process launcher
launcher.launch_service(self.server)
def create_server(conf, name, ho... | port,
keepalive=CONF.eventlet_server.tcp_keepalive,
keepidle=CONF.eventlet_server.tcp_keepidle)
if CONF.eventlet_server_ssl.enable:
server.set_ssl(CONF.eventlet_server_ssl.certfile,
CONF.eventlet_server_ssl.keyfile,
... |
apaksoy/automatetheboringstuff | practice projects/chap 08/multiclipboard with deletion chap 8/mcbd.py | Python | mit | 2,608 | 0.003451 | #! python3
'''
mcbd.py - Saves and loads pieces of text from/to the clipboard to/from a
shelf type file.
Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword.
python3 mcbd.py <keyword> - loads to clipboard for keyword.
python3 mcbd.py list - loads all keywords to clipboard.
... | ords.
'''))
mcbShelf = shelve.open('mcb') # file created if not already existing
# save or delete specified keywords
if len(sys.argv) == 3:
if sys.argv[1].lower() == 'save':
mcbShelf[sys.argv[2]] = pyperclip.paste()
print('clipboard saved under keyword:', sys.argv[2])
elif sys.argv[1].... | argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbShelf.keys())))
print('all keywords copied to clipboard')
elif sys.argv[1].lower() == 'delete':
mcbShelf.clear()
print('all keywords deleted')
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
... |
ostree/plaso | plaso/lib/utils.py | Python | apache-2.0 | 3,494 | 0.013165 | # -*- coding: utf-8 -*-
"""This file contains utility functions."""
import logging
import re
# Illegal Unicode characters for XML.
ILLEGAL_XML_RE = re.compile(
ur'[\x00-\x08\x0b-\x1f\x7f-\x84\x86-\x9f'
ur'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]')
def IsText(bytes_in, encoding=None):
"""Examine the bytes... | re-enabling or making a better determination.
#try:
# _ = bytes_in.decode('utf-16-le')
# return True
#except UnicodeDecodeError:
# pass
if encoding:
try:
_ = bytes_in.decode(encoding)
return True
except UnicodeDecodeError:
pass
except LookupError:
logging.error(
... | codeString(string):
"""Converts the string to Unicode if necessary."""
if not isinstance(string, unicode):
return str(string).decode('utf8', 'ignore')
return string
def GetInodeValue(inode_raw):
"""Read in a 'raw' inode value and try to convert it into an integer.
Args:
inode_raw: A string or an in... |
harmy/kbengine | kbe/res/scripts/common/Lib/sre_constants.py | Python | lgpl-3.0 | 7,444 | 0.002284 | #
# Secret Labs' Regular Expression Engine
#
# various symbols used by the regular expression engine.
# run this script to update the _sre include files!
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal su... | I_BOUNDARY,
AT_NON_BOUNDARY: AT_UNI_NON_BOUNDARY
}
CH_LOCALE = {
CATEGORY_DIGIT: CATEGORY_DIGIT,
CATEGORY_NOT_DIGIT: CATEGORY_NOT_DIGIT,
CATEGORY_SPACE: CATEGORY_SPACE,
CATEGORY_NOT_SPACE: CATEGORY_NOT_SPACE,
CATEGORY_WORD: CATEGORY_LOC_WORD,
CATEGORY_NOT_WORD: CATEGORY_LOC_NOT_WO... | CODE = {
CATEGORY_DIGIT: CATEGORY_UNI_DIGIT,
CATEGORY_NOT_DIGIT: CATEGORY_UNI_NOT_DIGIT,
CATEGORY_SPACE: CATEGORY_UNI_SPACE,
CATEGORY_NOT_SPACE: CATEGORY_UNI_NOT_SPACE,
CATEGORY_WORD: CATEGORY_UNI_WORD,
CATEGORY_NOT_WORD: CATEGORY_UNI_NOT_WORD,
CATEGORY_LINEBREAK: CATEGORY_UNI_LINEBRE... |
miguelgrinberg/heat | heat/engine/clients/os/manila.py | Python | apache-2.0 | 5,040 | 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
# ... | or generate an exception otherwise
"""
search_result_by_id = [res for res in resource_list
if res.id == id_or_name]
| if search_result_by_id:
return search_result_by_id[0]
else:
# try to find resource by name
search_result_by_name = [res for res in resource_list
if res.name == id_or_name]
match_count = len(search_result_by_name)
... |
emop/webrobot | hello_baidu/libs/actions.py | Python | gpl-2.0 | 725 | 0.01931 |
class BaiduSearch(object):
def __init__(self):
pass
|
def __call__(self, client, api, **kw):
"""
client --
client
api --
"""
client.driver.get("http://www.baidu.com")
|
input = client.e("#kw")
input.clear()
input.send_keys(kw['keyword'])
submit = client.e("#su")
submit.click()
#path = client.real_path("screen.png")
client.screenshot_as_file("screen.png")
result_list = client.es(".resu... |
aivuk/formcreator | formcreator/blocks/__init__.py | Python | bsd-2-clause | 647 | 0.003091 | import os
from flask import render_template
from markdown import markdown
__all__ = ["DirContents", "Doc"]
class | DirContents(object) | :
def __init__(self, dir, name=''):
self.dir = dir
if name != '':
self.name = name
else:
self.name = dir
def get_contents(self):
if not os.path.isdir(self.dir):
os.mkdir(self.dir)
return os.listdir(self.dir)
def html(self):
... |
tadhg-ohiggins/regulations-parser | doc2xml.py | Python | cc0-1.0 | 5,854 | 0.001025 | """ doc2xml.py
Converts docx files representing a proposed rule into the type of XML we'd
expect from the Federal Register.
Executing: python doc2xml.py file.docx
Writes XML to stdout
Installation:
* Install libxml2 via a package manager
* pip install -e git+https://github.com/savoirfairelinux/python-docx... | stead, it won't
| work
* Only processes the preamble data, not the CFR changes
""" # noqa
from __future__ import print_function
import re
import sys
from itertools import tee
from lxml import etree
import docx
h2_re = re.compile('[A-Z]\.')
h3_re = re.compile('\d\d?\.')
def text_subel(root, tag, text, **attrs):
"""U... |
CIRCL/AIL-framework | update/v2.2/Update.py | Python | agpl-3.0 | 4,172 | 0.006951 | #!/usr/bin/env python3
# -*-coding:UTF-8 -*
import os
import re
import sys
import time
import redis
import datetime
sys.path.append(os.path.join(os.environ['AIL_BIN'], 'packages'))
import Item
import Term
sys.path.append(os.path.join(os.environ['AIL_BIN'], 'lib/'))
import ConfigLoader
def rreplace(s, old, new, occ... | gLoader.ConfigLoader()
r_serv_term_stats = config_loader.get_redis_conn("ARDB_Trending")
r_serv_ | termfreq = config_loader.get_redis_conn("ARDB_TermFreq")
config_loader = None
r_serv_term_stats.flushdb()
#convert all regex:
all_regex = r_serv_termfreq.smembers('TrackedRegexSet')
for regex in all_regex:
tags = list( r_serv_termfreq.smembers('TrackedNotificationTags_{}'.format(regex)) )
... |
dictation-toolbox/aenea | server/linux_wayland/qwerty.py | Python | lgpl-3.0 | 1,666 | 0.042017 | from abstractKeyboardMapping import AbstractKeyboardMapping
import evdev
class Qwerty(AbstractKeyboardMapping):
def __init__(self):
super(AbstractKeyboardMapping, self).__init__()
def solo(self):
return { "!" : [evdev.ecodes.KEY_LEFTSHIFT, evdev.ecodes.KEY_1],
"@" : [evdev.ecodes.KEY_LEFTSHIFT, evdev... | "&" : [evdev.ecodes.KEY_LEFTSHIFT, evd | ev.ecodes.KEY_7],
"*" : [evdev.ecodes.KEY_LEFTSHIFT, evdev.ecodes.KEY_8],
"(" : [evdev.ecodes.KEY_LEFTSHIFT, evdev.ecodes.KEY_9],
")" : [evdev.ecodes.KEY_LEFTSHIFT, evdev.ecodes.KEY_0],
"_" : [evdev.ecodes.KEY_LEFTSHIFT, evdev.ecodes.KEY_MINUS],
"+" : [evdev.ecodes... |
blondegeek/pymatgen | pymatgen/apps/borg/hive.py | Python | mit | 15,762 | 0.000444 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import abc
import os
import glob
import logging
import json
import warnings
from monty.io import zopen
from pymatgen.io.vasp.inputs import Incar, Potcar, Poscar
from pymatgen.io.vasp.outputs import Vasprun, O... | pyright 2012, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Mar 18, 2012"
logger = logging.getLogger(__name__)
class AbstractDrone(MSONable, metaclass=abc.ABCMeta):
"""
Abstract drone class that defines the various methods that must b... | of Python"s
multiprocessing, the intermediate data representations has to be in the
form of python primitives. So all objects that drones work with must be
MSONable. All drones must also implement the standard MSONable as_dict() and
from_dict API.
"""
@abc.abstractmethod
def assimilate(self... |
cyrozap/BBB-Network-Ammeter | server.py | Python | isc | 5,648 | 0.011863 | #!/usr/bin/env python
#
# BBB-Network-Ammeter
#
# Copyright (c) 2016, Forest Crossman <cyrozap@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copi... | ,
name="currentSensor",
sampleInterval= | "10",
uuid="0",
)
Description = etree.SubElement(Device, "Description",
manufacturer="RPI MILL",
)
DataItems_0 = etree.SubElement(Device, "DataItems")
DataItem_0 = etree.SubElement(DataItems_0, "DataItem",
category="EVENT",
id="avail",
type="MACHINE_ON",
)... |
ATIX-AG/foreman-ansible-modules | plugins/doc_fragments/foreman.py | Python | gpl-3.0 | 9,183 | 0.001198 | # (c) 2019, Evgeni Golov <evgeni@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | elements: str
'''
ENTITY_STATE = '''
options:
state:
description:
- State of the entity
default: present
choices:
- present
- absent
type: str
'''
ENTITY_STATE_WITH_DEFAULTS = '''
options:
state:
description:
- State of the entity
- C(present_with_defau... | present_with_defaults
- absent
type: str
'''
HOST_OPTIONS = '''
options:
compute_resource:
description: Compute resource name
required: false
type: str
compute_profile:
description: Compute profile name
required: false
type: str
domain:
description: Domain name
requi... |
abezuglov/ANN | Storm-Surge/code/ilt_multi_gpu_feed.py | Python | gpl-3.0 | 12,586 | 0.014063 | from __future__ import print_function
import numpy as np
import os
import sys
import time
import tensorflow as tf
import load_datasets as ld
import datetime as dt
import ilt_two_layers as ilt
from sklearn.metrics import mean_squared_error
import tensorflow.python.client
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.... | _data_sets()
with tf.Graph().as_default(), tf.device('/cpu:0'):
# Prepare placeholders for inputs and expected outputs
x = tf. | placeholder(tf.float32, [None, FLAGS.input_vars], name='x-input') # Note: these are normalized inputs
y_ = tf.placeholder(tf.float32, [None, FLAGS.output_vars], name = 'y-input')
# Create variables for input and output data moments and initialize them with train datasets' moments
input_means = ... |
SlicingDice/slicingdice-python | pyslicer/client.py | Python | mit | 12,918 | 0.000077 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 The Simbiose Ventures Developers
#
# 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... | url=url,
json_data=ujson.dumps(data),
req_type="post",
key_level=1)
def count_entity(self, query):
"""Make a count entity query
Keyword arguments:
query -- A dictionary in the Slicing Dice query
"""
url = SlicingDice.B... | urces.QUERY_COUNT_ENTITY
return self._count_query_wrapper(url, query)
def count_entity_total(self, dimensions=None):
"""Make a count entity total query
Keyword arguments:
dimensions -- A dictionary containing the dimensions in which
the total query will be perform... |
oliver/meld | vc/cdv.py | Python | gpl-2.0 | 1,787 | 0.012311 | ### Copyright (C) 2009 Vincent Legoll <vincent.legoll@gmail.com>
### Redistribution and use in source and binary forms, with or without
### modification, are permitted provided that the following conditions
### are met:
###
### 1. Redistributions of source code must retain the above copyright
### notice, this list... | S
### OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
### IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
### INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, B | UT
### NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
### DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
### THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
### (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
### THIS SOFTWAR... |
zakandrewking/cobrapy | cobra/util/solver.py | Python | lgpl-2.1 | 15,435 | 0 | # -*- coding: utf-8 -*-
"""Additional helper functions for the optlang solvers.
All functions integrate well with the context manager, meaning that
all operations defined here are automatically reverted when used in a
`with model:` block.
The functions defined here together with the existing model functions should
a... | reverse_value.direction
context(reset)
def interface_to_str(interface):
"""Give a string representation for an optlang interface.
Parameters
----------
interface : string, ModuleType
Full name of the interface in optlang or cobra representation.
For instance 'optlang.glp | k_interface' or 'optlang-glpk'.
Returns
-------
string
The name of the interface as a string
"""
if isinstance(interface, ModuleType):
interface = interface.__name__
return re.sub(r"optlang.|.interface", "", interface)
def get_solver_name(mip=False, qp=False):
"""Select a s... |
OpenLinkedSocialData/ocd | OCD.py | Python | unlicense | 24,833 | 0.021655 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import cPickle as pickle, time, string
from SPARQLWrapper import SPARQLWrapper, JSON
import rdflib as r, pygraphviz as gv
import pylab as pl
# variaveis principais:
# classes (kk), props,
# vizinhanca_ (de classes)
T=time.time()
U=r.URIRef
def fazQuery(query):
NOW=time.tim... | A.add_edge(cl_,label_)
e=A.get_edge(cl_,label_)
e.attr["label"]=elabel
e.attr["color"]=color
e.attr["penwidth"]=2
A.draw(" | imgs/OCD.png",prog="twopi",args="-Granksep=4")
A.draw("imgs/OCD2.png",prog="dot",args="-Granksep=.4 -Gsize='1000,1000'")
print("Wrote geral")
# 4.5) qualificar literais
## ok.
# 5) Observando as triplas, observar hierarquias e conceitos especificos do namespace,
# como commentBody e userName. Ver README.md.
G(ocd.Pro... |
hachard/Cra-Magnet | flask/lib/python3.5/site-packages/flask_babel/speaklater.py | Python | gpl-3.0 | 1,713 | 0.000584 | # -*- coding: utf-8 -*-
from flask_babel._compat import text_type
class LazyString(object):
def __init__(self, func, *args, **kwargs):
sel | f._func = | func
self._args = args
self._kwargs = kwargs
def __getattr__(self, attr):
string = text_type(self)
if hasattr(string, attr):
return getattr(string, attr)
raise AttributeError(attr)
def __str__(self):
return text_type(self._func(*self._args, **self._... |
yarikoptic/Fail2Ban-Old-SVNGIT | server/datetemplate.py | Python | gpl-2.0 | 5,047 | 0.033902 | # -*- coding: utf-8 -*-
# This file is part of Fail2Ban.
#
# Fail2Ban 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.
#
# Fail2Ban is d... | ABLE["Sep"] = []
TABLE["Oct"] = ["Okt"]
TABLE["Nov"] = []
TABLE["Dec"] = [u"Déc", "Dez"]
def __init__(self):
DateTemplate.__init__(self)
self.__pattern = ""
def setPattern(self, pattern):
self.__pattern = pattern.strip()
def getPattern(self):
return self.__pattern
#@staticmethod
def convertLoca... | n DateStrptime.TABLE:
for m in DateStrptime.TABLE[t]:
if date.find(m) >= 0:
return date.replace(m, t)
return date
convertLocale = staticmethod(convertLocale)
def getDate(self, line):
date = None
dateMatch = self.matchDate(line)
if dateMatch:
try:
# Try first with 'C' locale
date = lis... |
lucienfostier/gaffer | python/GafferUITest/MessageWidgetTest.py | Python | bsd-3-clause | 4,866 | 0.044595 | ##########################################################################
#
# Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | .Msg.L | evel.Info ), info )
self.assertEqual( widget.messageCount( IECore.Msg.Level.Warning ), warning )
self.assertEqual( widget.messageCount( IECore.Msg.Level.Error ), error )
self.assertEqual( widget.messageCount(), debug + info + warning + error )
def testMessages( self ) :
w = GafferUI.MessageWidget()
self.as... |
vitan/blaze | blaze/expr/reductions.py | Python | bsd-3-clause | 6,478 | 0.001698 | from __future__ import absolute_import, division, print_function
import toolz
from toolz import first
import datashape
from datashape import Record, dshape, DataShape
from datashape import coretypes as ct
from datashape.predicates import isscalar, iscollection
from .core import common_subexpression
from .expressions ... | ol
class Reduction(Expr):
""" A c | olumn-wise reduction
Blaze supports the same class of reductions as NumPy and Pandas.
sum, min, max, any, all, mean, var, std, count, nunique
Examples
--------
>>> t = Symbol('t', 'var * {name: string, amount: int, id: int}')
>>> e = t['amount'].sum()
>>> data = [['Alice', 100, 1],
... |
akoebbe/sweetiepi | sweetiepi/clocks/choices.py | Python | mit | 1,719 | 0.000582 | from django.utils.translation import ugettext_lazy as _
DIAL_CHOICES = (
('none', _('None')),
('din 41091.1', _('Dial with minute and hour markers (DIN 41091, Sect. 1)')),
('din 41091.3', _('Dial with hour markers (DIN 41091, Sect. 3)')),
('din 41091.4', _('Dial with hour numerals (DIN 41091, Part 4)')... | ,
('swiss', _('Blunt, javelin-shaped hand (Austria)')),
)
SECOND_HAND_CHOICES = (
('none', _('Without second h | and')),
('din 41071.1', _('Javelin-shaped hand (DIN 41071, Sect. 1)')),
('din 41071.2', _('Perforated pointer hand (DIN 41071, Sect. 2)')),
('german', _('Modern perforated pointer hand (German Rail)')),
('swiss', _('Disc-end hand (Switzerland)')),
)
MINUTE_HAND_MOVEMENT_CHOICES = (
('stepping', _('... |
md1024/rams | uber/decorators.py | Python | agpl-3.0 | 18,151 | 0.003251 | from uber.common import *
def swallow_exceptions(func):
"""
Don't allow ANY | Exceptions to be raised from this.
Use this ONLY where it's absolutely needed, such as dealing with locking functionality.
WARNING: DO NOT USE THIS UNLESS YOU KNOW WHAT YOU'RE DOING :)
"""
@wraps(func)
def swallow_exception(*args, **kwargs):
try:
return func(*args, **kwargs)
... | we're going to ignore it and continue.", exc_info=True)
return swallow_exception
def log_pageview(func):
@wraps(func)
def with_check(*args, **kwargs):
with sa.Session() as session:
try:
attendee = session.admin_account(cherrypy.session['account_id'])
except... |
stoewer/nix-demo | utils/plotting.py | Python | bsd-3-clause | 12,201 | 0.002951 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import numpy as np
import scipy.signal as sp
import random
import nix
import matplotlib.pyplot as plt
COLORS_BLUE_AND_RED = (
'dodgerblue', 'red'
)
COLORS_BLUE_GRADIENT = (
"#034980", "#055DA1", "#1B70E0", "#3786... | return self.__cols * self.__lines
@property
def subplot_data(self):
re | turn self.__subplot_data
@property
def defaultcolors(self):
return self.__defaultcolors
@property
def last_figure(self):
assert self.__last_figure is not None, "No figure available (method plot has to be called at least once)"
return self.__last_figure
# methods
def s... |
lead-ratings/django-bulk-update | tests/fixtures.py | Python | mit | 4,775 | 0.000209 | from datetime import date, time, timedelta
from decimal import Decimal
import itertools
from django.utils import timezone
from six.moves import xrange
from .models import Person
def get_fixtures(n=None):
"""
Returns `n` dictionaries of `Person` objects.
If `n` is not specified it defaults to 6.
"... | text', 'url': 'google.com',
'height': Decimal('1.59'), 'date_time': _now,
'date': _date, 'time': | _time, 'float_height': 2 ** 2,
'image': 'dummy.jpeg', 'data': {},
},
{
'big_age': 9999999999, 'comma_separated_age': '1,100,3,5',
'age': 35, 'positive_age': 1111, 'positive_small_age': 500,
'small_age': 110, 'certified': True, 'null_certified': None,
... |
appop/bitcoin | qa/rpc-tests/bip9-softforks.py | Python | mit | 10,528 | 0.004084 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The nealcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP 9 soft forks.
Connect to a single node.
regtest lock-in with 108/144 block signalling
activa... | f.height += 1
return test_blocks
def get_bip9_status(self, key):
info = self.nodes[0].getblockchaininfo()
return info['bip9_softforks'][key]
def test_BIP(self, bipName, activated_version, in | validate, invalidatePostSignature, bitno):
assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
assert_equal(self.get_bip9_status(bipName)['since'], 0)
# generate some coins for later
self.coinbase_blocks = self.nodes[0].generate(2)
self.height = 3 # height of the n... |
genius1611/Keystone | keystone/controllers/tenant.py | Python | apache-2.0 | 1,975 | 0.002532 | from keystone import utils
from keystone.common import wsgi
import keystone.config as config
from keystone.logic.types.tenant import Tenant
from . import get_marker_limit_and_url
class TenantController(wsgi.Controller):
"""Controller for Tenant related operations"""
def __init__(self, options, is_service_ope... | y_name(
utils.get_auth_token(req),
tenant_name)
return utils.send_result(200, req, tenant)
else:
marker, limit, url = get_marker_limit_and_url(req)
tenants = config.SE | RVICE.get_tenants(utils.get_auth_token(req),
marker, limit, url, self.is_service_operation)
return utils.send_result(200, req, tenants)
@utils.wrap_error
def get_tenant(self, req, tenant_id):
tenant = config.SERVICE.get_tenant(utils.get_auth_token(req),
tenant_id... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/logilab/__init__.py | Python | agpl-3.0 | 155 | 0 | """generated | file, don't modify or your data will be lost"""
try:
__import__('pkg_resources').declare_namespace(__name__)
ex | cept ImportError:
pass
|
tpbarron/pytorch-ppo | main.py | Python | mit | 9,755 | 0.003383 | import argparse
import sys
import math
from collections import namedtuple
from itertools import count
import gym
import numpy as np
import scipy.optimize
from gym import wrappers
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import tor... | ce.shape[0]
env.seed(args.seed)
torch.manual_seed(args.seed)
if args.use_joint_pol_val:
ac_net = ActorCritic(num_inputs, num_actions)
opt_ac = optim.Adam(ac_net.parameters(), lr=0.001)
else:
policy_net = Policy(num_inputs, num_actions)
value_net = Value(num_inputs)
opt_policy = optim.Adam(policy | _net.parameters(), lr=0.001)
opt_value = optim.Adam(value_net.parameters(), lr=0.001)
def select_action(state):
state = torch.from_numpy(state).unsqueeze(0)
action_mean, _, action_std = policy_net(Variable(state))
action = torch.normal(action_mean, action_std)
return action
def select_action_actor... |
kaedroho/wagtail | scripts/nightly/upload.py | Python | bsd-3-clause | 615 | 0.001626 | import json
import pathlib
import sys
import boto3
dist_folder = pathlib.Path.cwd() / 'dist'
try:
f = next(dist_folder.glob('*.whl'))
except StopIteration:
print("No .whl files found in ./dist!")
sys.exit()
print("Uploading", f.name)
s3 = boto3.client('s3')
s3.upload_file(str(f), 'releases.wagtail.io',... | lic-read'})
print("Updating latest.json")
boto3.resource( | 's3').Object('releases.wagtail.io', 'nightly/latest.json').put(
ACL='public-read',
Body=json.dumps({
"url": 'https://releases.wagtail.io/nightly/dist/' + f.name,
})
)
|
olafhauk/mne-python | mne/datasets/hf_sef/hf_sef.py | Python | bsd-3-clause | 3,751 | 0 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Authors: Jussi Nurminen <jnu@iki.fi>
# License: BSD Style.
import tarfile
import os.path as op
import os
from ...utils import _fetch_file, verbose, _check_option
from ..utils import _get_path, logger, _do_path_update
@verbose
def data_path(dataset='evoked', path=None... | .
path : None | str
Where to look for the HF-SEF data storing location.
If None, the environment variable or config parameter
``MNE_DATASETS_HF_SEF_PATH`` is used. If it doesn't exist, the
"~/mne_data" directory is used. If the HF-SEF dataset
is not found under the given path... | aded to the specified folder.
force_update : bool
Force update of the dataset even if a local copy exists.
update_path : bool | None
If True, set the MNE_DATASETS_HF_SEF_PATH in mne-python
config to the given path. If None, the user is prompted.
%(verbose)s
Returns
-------
... |
ruohoruotsi/Wavelet-Tree-Synth | edward-examples/beta_bernoulli_map.py | Python | gpl-2.0 | 1,013 | 0.002962 | #!/usr/bin/env python
"""
A simple coin flipping example. The model is written in TensorFlow.
Inspired by Stan's toy example.
Probability model
Prior: Beta
Likelihood: Bernoulli
Inference: Maximum a posteriori
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_f... | , 1, 0, 0, 0, 0, 0, 0, 0, 1])}
params = tf.sigmoid(tf.Variable(tf.random_normal([1])))
inference = ed.MAP(model, data, params=params)
inference.run(n_iter=100, n_print=10) | |
cryptoprojects/ultimateonlinecash | share/rpcuser/rpcuser.py | Python | mit | 1,125 | 0.005333 | #!/usr/bin/env python2
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(s... | argv[1]
#This uses os.urandom() underneath
cryptogen = SystemRandom()
#Create 16 byte hex salt
salt_sequence = [cryptogen.randrange(256) for i in range(16)]
hexseq = list(map(hex, salt_sequence))
salt = "".join([x[2:] for x in hexseq])
#Create 32 byte b64 password
password = base64.urlsafe_b64encode(os.urandom(32))
... | salt, 'utf-8'), bytearray(password, 'utf-8'), digestmod)
result = m.hexdigest()
print("String to be appended to ultimateonlinecash.conf:")
print("rpcauth="+username+":"+salt+"$"+result)
print("Your password:\n"+password)
|
richasinha/redis-OS-project | src/setRedis.py | Python | bsd-3-clause | 595 | 0.006723 | import time
from subprocess import *
PATH = "/home/richie_rich/OSProj/redis-OS-project/src/redis-cli"
p1 = Popen([PATH], shell=True, stdin=PIPE)
p1.communicate(input="FLUSHALL")
strength = 1000000
rangeVal = strength + 1
string = "set key"
string1 = | ""
count = 0
for i in xrange(1,rangeVal):
count = count + 1
string1 = string1 + string + str(i) + " val" + str(i) + "\n"
if (i % 1000) == 0 :
p1 = Popen([PATH], shell=True, stdin=PIP | E)
p1.communicate(input=string1)
string = "set key"
string1 = ""
print string1
print "Inserted %d items" %(count)
|
andreasfaerber/p2pool-feathercoin | p2pool/web.py | Python | gpl-3.0 | 25,473 | 0.00687 | from __future__ import division
import errno
import json
import os
import sys
import time
import traceback
from twisted.internet import defer, reactor
from twisted.python import log
from twisted.web import resource, static
import p2pool
from bitcoin import data as bitcoin_data
from . import data as p2pool_data, p2p
... | - my_stale_prop) if my_stale_prop is not None else 0, # 0 because we don't have any shares anyway
),
my_share_counts_in_last_hour=dict(
shares=my_share_count,
unstale_shares=my_unstale_count,
stale_shares=my_stale_count,
orphan_sta... | proportions_in_last_hour=dict(
stale=my_stale_prop,
orphan_stale=my_orphan_count/my_share_count if my_share_count != 0 else None,
dead_stale=my_doa_count/my_share_count if my_share_count != 0 else None,
),
miner_hash_rates=miner_hash_rates,
... |
richshaffer/tornado-suds | tornado_suds/bindings/rpc.py | Python | lgpl-3.0 | 3,181 | 0.002829 | # 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 ... | replycontent(self, method, body):
return body | [0].children
def method(self, method):
"""
Get the document root. For I{rpc/(literal|encoded)}, this is the
name of the method qualifed by the schema tns.
@param method: A service method.
@type method: I{service.Method}
@return: A root element.
@rtyp... |
jaseg/python-lmap | testfnord.py | Python | bsd-2-clause | 490 | 0.028571 | #!/usr/bin/env python3
from lmap import ldap
from getpass import getpass
i | mport threading
pw = getpass()
def bind_fnord(num):
def do_teh_action():
ld = ldap.ldap('ldap://emmi.physik-pool.tu-berlin.de/')
ld.simple_bind('uid=jaseg,ou=people,ou=pcpool,ou=physik,o=tu-berlin,c=de', pw)
print(num, len(ld.search('ou=people,ou=pcpool,ou=physik,o=tu-berlin,c=de', filter='uid=jaseg')))
retur... | (i))
t.start()
|
passByReference/webcrawler | proj2/proj2/pipelines.py | Python | apache-2.0 | 285 | 0 | # -*- coding: | utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class Proj2Pipeline(object):
def process_item(self, item, spider):
return | item
|
wd15/corr | corr-api/config.py | Python | mit | 436 | 0 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
WTF_CSRF_ENABLED = T | rue
SECRET_KEY = '33stanlake#'
DEBUG = True
APP_TITLE = 'Cloud of Reproducible Records API'
VERSION = '0.1-dev | '
MONGODB_SETTINGS = {
'db': 'corr-production',
'host': '0.0.0.0',
'port': 27017
}
# STORMPATH_API_KEY_FILE = '~/.stormpath/apiKey.properties'
# STORMPATH_APPLICATION = 'sumatra-cloud'
# STORMPATH_REDIRECT_URL = '/dashboard'
|
googleapis/python-dialogflow-cx | google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py | Python | apache-2.0 | 7,215 | 0.001663 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
| **kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
... |
googlefonts/gftools | Lib/gftools/fix.py | Python | apache-2.0 | 28,567 | 0.001505 | """
Functions to fix fonts so they conform to the Google Fonts
specification:
https://github.com/googlefonts/gf-docs/tree/main/Spec
"""
from fontTools.misc.fixedTools import otRound
from fontTools.ttLib import TTFont, newTable, getTableModule
from fontTools.ttLib.tables import ttProgram
from fontTools.ttLib.tables._c_m... | ext((a for a in fvar.axes if a.axisTag == "wght"), None)
wght_min = int(wght_axis.minValue)
wght_max = int(wght_axis.maxValue)
nametable = ttFont["name"] |
def gen_instances(is_ital |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/ns/nsratecontrol.py | Python | apache-2.0 | 5,380 | 0.036059 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | ) :
ur""" Use this API to fetch all the nsratecontrol resources that are configured on netscaler.
"""
try :
if not name :
obj = nsratecontrol()
response = obj.get_resources(client, option_)
return response
except Exception as e :
raise e
| class nsratecontrol_response(base_response) :
def __init__(self, length=1) :
self.nsratecontrol = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.nsratecontrol = [nsratecontrol() for _ in range(length)]
|
goddardl/gaffer | python/GafferTest/TypedObjectPlugTest.py | Python | bsd-3-clause | 8,984 | 0.059996 | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | ENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE... | TY OF SUCH DAMAGE.
#
##########################################################################
import unittest
import IECore
import Gaffer
import GafferTest
class TypedObjectPlugTest( GafferTest.TestCase ) :
def testSerialisation( self ) :
s = Gaffer.ScriptNode()
s["n"] = Gaffer.Node()
s["n"]["t"] = Gaffe... |
AkihiroSuda/earthquake | docker/eq-init.py | Python | apache-2.0 | 1,499 | 0.008005 | #!/usr/bin/python
"""
Init script for Earthquake Docker Image (osrg/earthquake)
Supported Env vars:
- EQ_DOCKER_PRIVILEGED
"""
import os
import prctl
import subprocess
import sys
def log(s):
print 'INIT: %s' % s
def is_privileged_mode():
has_env = os.getenv('EQ_DOCKER_PRIVILEGED')
has_cap = prctl.cap_pe... | log('Exiting with status %d..(%s)' % (rc, elem))
sys.exit(rc)
def run_command_and_ | exit(l):
log('Starting command: %s' % l)
rc = subprocess.call(l)
log('Exiting with status %d..(%s)' % (rc, l))
sys.exit(rc)
def get_remaining_args():
return sys.argv[1:]
if __name__ == '__main__':
daemons = [
['service', 'mongodb', 'start']
]
run_daemons(daemons)
com = ... |
sfalkner/pySMAC | pysmac/utils/state_merge.py | Python | agpl-3.0 | 11,573 | 0.009937 | import os
import glob
import operator
import errno
import filecmp
import shutil
import numpy
from .smac_output_readers import *
def find_largest_file (glob_pattern):
""" Function to find the largest file matching a glob pattern.
Old SMAC version keep several versions of files as back-ups. This
helper ... | n in rars:
# get the local configuration and instance id
lcid, liid = int(run[0])-1, int(run[1])-1
if liid in ignored_instance_ids:
continue
# translate them into the global ones
gcid = configurations[confs[lcid]]['index']
giid = ... | liid][0]]['index']
# check for duplicates and skip if necessary
if (gcid, giid) in runs_and_results:
if drop_duplicates:
#print('dropped duplicate: configuration {} on instace {}'.format( |
ampron/pyMTRX | pyMTRX/scripts/notebook_sheet.py | Python | gpl-3.0 | 12,420 | 0.008132 | #!/usr/bin/python
# -*- encoding: UTF-8 -*-
'''MATRIX Log File Maker
Version: 2
This script will create a csv file that will be a table of settings for all
STM data recorded from the Omicron MATRIX software.
List of classes: -none-
List of functions:
main
'''
# built-in modules
im... | for fn in sts_files:
curves = ex.import_spectra(os.path.join(cwd, fn))
for crv in curves:
STS_entries.append( make_spectrum_entry(crv, debug=debug) )
# END for
IMG_entries.sort(key=lambda tup: tup[0])
STS_entries.sort(key=lambda tup: tup[0])
N_opened = len(IMG_entries) ... | |
rueckstiess/mtools | mtools/mlaunch/mlaunch.py | Python | apache-2.0 | 96,965 | 0.000423 | #!/usr/bin/env python3
import argparse
import functools
import json
import os
import re
import signal
import socket
import ssl
import subprocess
import sys
import threading
import time
import warnings
from collections import defaultdict
from operator import itemgetter
import psutil
from mtools.util import OrderedDict... | ame.
"""
# set up argument parsing in run, so that subsequent calls
# to run can call different sub-commands
self.argparser = argparse.ArgumentParser()
self.argparser.add_argument('--version' | , action='version',
version=f'''mtools version {__version__} || Python {sys.version}''')
self.argparser.add_argument('--no-progressbar', action='store_true',
default=False,
help='disables progress bar')
... |
gigglearrows/anniesbot | pajbot/models/setting.py | Python | mit | 2,197 | 0 | import logging
from collections import UserDict
from pajbot.models.db import DBManager, Base
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.mysql import TEXT
log = logging.getLogger('pajbot')
class Setting(Base):
__tablename__ = 'tb_settings'
id = Column(Integer, primary_key=True)... | g(128))
value = Column(TEXT)
type = Column(String(32))
def __init__(self, setting, value, type):
self.id = None
self.setting = setting
self.value = value
self.type = type
| def parse_value(self):
try:
if self.type == 'int':
return int(self.value)
elif self.type == 'string':
return self.value
elif self.type == 'list':
return self.value.split(',')
elif self.type == 'bool':
... |
NetworkManager/NetworkManager-ci | features/steps/commands.py | Python | gpl-3.0 | 19,422 | 0.003398 | import json
import os
import pexpect
import re
import time
from behave import step
import nmci
@step(u'Autocomplete "{cmd}" in bash a | nd execute')
def autocomplete_command(context, cmd):
bash = context.pexpect_spawn("bash")
bash.send(cmd)
bash.send('\t')
time.sleep(1)
bash.send('\r\n')
time.sleep(1)
bash.sendeof()
@step(u'Check RSS writable memory in noted value "{i2}" differs from "{i1}" less than "{dif}"')
def check_rs... | ext, pmap_raw):
# total = 0
# for line in pmap_raw.split("\n"):
# vals = line.split()
# if (len(vals) > 2):
# total += int(vals[2])
# return total
#
# sum2 = int(sum_rss_writable_memory(context, context.noted[i2]))
# sum1 = int(sum_rss_writable... |
sloanyang/aquantic | Tools/Scripts/webkitpy/port/mac_unittest.py | Python | gpl-2.0 | 12,566 | 0.003342 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | seline_path, search_paths)
self.assertEqual(port.baseline_path(), port._webkit_baseline_path(baseline_path))
self.assertEqual(port.baseline_search_path(), absolute_search_paths)
def test_baseline_search_path(self):
# Note that we don't need total coverage here, just path coverage, since thi... | nowleopard', 'mac-snowleopard', ['mac-snowleopard', 'mac-lion', 'mac-mountainlion', 'mac'])
self._assert_search_path('mac-lion', 'mac-lion', ['mac-lion', 'mac-mountainlion', 'mac'])
self._assert_search_path('mac-mountainlion', 'mac-mountainlion', ['mac-mountainlion', 'mac'])
self._assert_search_... |
thaim/ansible | lib/ansible/modules/network/exos/exos_facts.py | Python | mit | 5,863 | 0.000682 | #!/usr/bin/python
#
# (c) 2018 Extreme Networks Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | subset:
- '!all'
- '!min'
gather_network_resource | :
- lldp_global
- name: Gather lldp global resource and minimal legacy facts
exos_facts:
gather_subset: min
gather_network_resource: lldp_global
"""
RETURN = """
ansible_net_gather_subset:
description: The list of fact subsets collected from the device
returned: always
type: list
ansi... |
tkf/railgun | tests/check_memory_leak.py | Python | mit | 1,554 | 0.000644 | from __future__ import print_function
import sys
import numpy
from arrayaccess import gene_class_ArrayAccess
from test_arrayaccess import LIST_CDT, LIST_NUM
def main(iter_num, list_num, calloc):
clibname = 'arrayaccess.so'
ArrayAc | cess = gene_class_ArrayAccess(clibname, len(list_num), LIST_CDT)
ArrayAccess._calloc_ = calloc
if iter_num <= 10:
printnow = range(iter_num)
else:
printnow = numpy.linspace(
0, iter_num, num=10, endpoint=False).astype(int)
num_d | ict = dict(zip(ArrayAccess.num_names, list_num)) # {num_i: 6, ...}
assert ArrayAccess._calloc_ is bool(calloc)
print('[*/%d]:' % iter_num, end=' ')
sys.stdout.flush()
for i in range(iter_num):
ArrayAccess(**num_dict)
if i in printnow:
print(i, end=' ')
sys.stdou... |
BrambleLLC/HackAZ-2016 | server/webapp/models.py | Python | mit | 1,957 | 0.006643 | from __init__ import redis_db
from werkzeug.security import generate_password_hash, check_password_hash
from os import urandom
from base64 import b64encode
class User(object):
def __init__(self):
self.username = "" # required
self.password_hash = "" # required
self.phone_number = "" # req... | salt_length=32)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def write_to_db(self):
user_dict = {"password_hash": self.password_hash, "phone_number": self.phone_number,
"secret_key": self.secret_key, "emergency_contact": self.eme... | elf.username + ":contacts", *self.contacts)
def deauthenticate(self):
self.secret_key = b64encode(urandom(64)).decode("utf-8")
@classmethod
def get_from_db(cls, username):
user_dict = redis_db.hmget(username, ["password_hash", "phone_number", "secret_key", "emergency_contact"])
fet... |
MediaKraken/MediaKraken_Deployment | source/common/common_network_steam.py | Python | gpl-3.0 | 1,746 | 0.000573 | """
Copyright (C) 2018 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
... | t even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License version 2 for more details.
You should have received a copy of the GNU General Public | License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
"""
from steam import SteamID
from bs4 import BeautifulSoup
from . import common_network
# https://developer.valvesoftware.com/wiki/Steam_Web_API
class C... |
cgwire/zou | zou/app/blueprints/projects/__init__.py | Python | agpl-3.0 | 3,136 | 0.000319 | from flask import Blueprint
from zou.app.utils.api import configure_api_from_blueprint
from .resources import (
AllProjectsResource,
OpenProjectsResource,
ProductionTeamResource,
ProductionTeamRemoveResource,
ProductionAssetTypeResource,
ProductionAssetTypeRemoveResource,
ProductionTaskType... | "/data/projects/<project_id>/settings/task-types",
ProductionTaskTypeResource,
),
(
"/data/projects/<project_id>/settings/task-types/<task_type_id>",
ProductionTaskTypeRemoveResource,
),
(
"/data/projects/<project_id>/settings/task-status",
ProductionTaskSt... | id>",
ProductionTaskStatusRemoveResource,
),
(
"/data/projects/<project_id>/metadata-descriptors",
ProductionMetadataDescriptorsResource,
),
(
"/data/projects/<project_id>/metadata-descriptors/<descriptor_id>",
ProductionMetadataDescriptorResource,
),
("/d... |
Crop-R/django-mediagenerator | mediagenerator/management/commands/generatemedia.py | Python | bsd-3-clause | 349 | 0.005731 | from ...api | import generate_media, prepare_media
from django.core.management.base | import BaseCommand
class Command(BaseCommand):
help = 'Combines and compresses your media files and saves them in _generated_media.'
requires_model_validation = False
def handle(self, *args, **options):
prepare_media()
generate_media()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.