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 |
|---|---|---|---|---|---|---|---|---|
repotvsupertuga/tvsupertuga.repository | plugin.video.youtube/resources/lib/youtube_plugin/kodion/impl/abstract_system_version.py | Python | gpl-2.0 | 978 | 0.001022 | __author__ = 'bromix'
class AbstractSystemVersion(object):
def __init__(self, version, releasename, appname):
if not isinstance(version, tuple):
self._version = (0, 0, 0, 0)
else:
self._version = version
if not releasename or not isinstance(releasename, basestring)... | self._appname = 'UNKNOWN'
else:
self._appname = appname
def __str__(self):
return | unicode(self).encode('utf-8')
def __unicode__(self):
obj_str = "%s (%s-%s)" % (self._releasename, self._appname, '.'.join(map(str, self._version)))
return obj_str
def get_release_name(self):
return self._releasename
def get_version(self):
return self._version
def get... |
PrairieLearn/PrairieLearn | elements/pl-file-editor/pl-file-editor.py | Python | agpl-3.0 | 6,608 | 0.002119 | import prairielearn as pl
import lxml.html
import chevron
import base64
import hashlib
import os
from text_unidecode import unidecode
EDITOR_CONFIG_FUNCTION_DEFAULT = None
ACE_MODE_DEFAULT = None
ACE_THEME_DEFAULT = None
SOURCE_FILE_NAME_DEFAULT = None
MIN_LINES_DEFAULT = None
MAX_LINES_DEFAULT = None
AUTO_RESIZE_DEF... | nes', 'max-lines', 'auto-resize', 'preview', 'focus', 'directory', 'normalize-to-ascii']
pl.check_attribs(element, required_attribs, optio | nal_attribs)
source_file_name = pl.get_string_attrib(element, 'source-file-name', SOURCE_FILE_NAME_DEFAULT)
file_name = pl.get_string_attrib(element, 'file-name')
if '_required_file_names' not in data['params']:
data['params']['_required_file_names'] = []
elif file_name in data['params']['_requ... |
ListFranz/picamera | picamera/renderers.py | Python | bsd-3-clause | 26,507 | 0.000641 | # vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Python camera library for the Rasperry-Pi camera module
# Copyright (c) 2013-2015 Dave Jones <dave@waveform.org.uk>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# ... | l.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_DISPLAYREGION,
ct.sizeof(mmal.MMAL_DISPLAYREGION_T)
))
mmal_check(
mmal.mmal_port_parameter_get(self.renderer[0].input[0], mp.hdr),
prefix="Failed to get layer")
return mp.layer
def _se... | alid range |
thaim/ansible | lib/ansible/module_utils/network/iosxr/providers/module.py | Python | mit | 2,108 | 0.001423 | #
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import | Connection
from ansible.module_utils.network.iosxr.providers import providers
from ansible.module_utils._text import to_text
class NetworkModule(AnsibleModule):
fail_on_missing_provider = True
def __init__(self, connection=None, *args, **kwargs):
super(NetworkModule, self).__init__(*args, **kwargs)
... | ef provider(self):
if not hasattr(self, '_provider'):
capabilities = self.from_json(self.connection.get_capabilities())
network_os = capabilities['device_info']['network_os']
network_api = capabilities['network_api']
if network_api == 'cliconf':
... |
jricardo27/travelhelper | travelhelper/apps/core/templatetags/core_util.py | Python | bsd-3-clause | 840 | 0 | """
Utility tags for templates
"""
from __future__ import absolute_import
from django.db.models import Model
from django.forms import ModelForm
from django.template import Library
register = Library()
# pylint:disable=protected-access
# allow access to _meta
@register.filter
def verbose | _name(value):
"""
Return an object's verbose name
"""
if hasattr(value, 'verbose_name'):
return value.verbose_name
model = None
if isinstance(value, ModelForm):
model = value._meta.model
elif isinstance(value, Model):
model = value
assert model, "Unknown type '%... | urns verbose_name for a field.
"""
return instance._meta.get_field(field_name).verbose_name
|
maximz/recal | course_selection/migrations/0019_auto_20150903_0458.py | Python | mit | 809 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0018_auto_20150830_0319'),
]
operations = [
migrations.AlterUniqueTogether(
name='friend_rel... | migrations.RemoveField(
model_name='friend_relationship',
name='to_user',
),
migrations.RemoveField(
model_name='nice_user',
name='friends',
),
migrat | ions.DeleteModel(
name='Friend_Relationship',
),
]
|
maximecb/gym-minigrid | run_tests.py | Python | apache-2.0 | 4,174 | 0 | #!/usr/bin/env python3
import random
import numpy as np
import gym
from gym_minigrid.register import env_list
from gym_minigrid.minigrid import Grid, OBJECT_TO_IDX
# Test specifically importing a specific environment
from gym_minigrid.envs import DoorKeyEnv
# Test importing wrappers
from gym_minigrid.wrappers import... | ward >= env.reward_range[0], | reward
assert reward <= env.reward_range[1], reward
if done:
num_episodes += 1
env.reset()
env.render('rgb_array')
# Test the close method
env.close()
env = gym.make(env_name)
env = ReseedWrapper(env)
for _ in range(10):
env.reset()
... |
manipopopo/tensorflow | tensorflow/contrib/distribute/python/step_fn.py | Python | apache-2.0 | 4,263 | 0.004222 | # Copyright 2018 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... | nd finalize ops.
class StandardInputStep(Step):
"""Step with a standard implementation | of input handling.
Args:
dataset_fn: a function that returns a tf.data Dataset that produces the
input for the model.
"""
def __init__(self, dataset_fn, distribution):
super(StandardInputStep, self).__init__(distribution)
self._distributed_input = distribution.distribute_dataset(dataset_fn)
... |
trysrv/GitHub.Uploader.CuiCmd.201706231541 | web/service/github/api/v3/authentication/OAuthTokenFromDatabaseAuthentication.py | Python | cc0-1.0 | 2,011 | 0.005456 | #!python3
#encoding:utf-8
from abc import ABCMeta, abstractmethod
from web.service.github.api.v3.authentication.OAuthAuthentication import OAuthAuthentication
class OAuthTokenFromDatabaseAuthentication(OAuthAuthentication):
def __init__(self, db, username):
self.__db = db
self.__username = username
... | sinstance(scopes, list) and 0 < len(scopes):
sql = sql + " AND ("
for s in scopes:
sql = sql + "(',' || Scopes || ',') LIKE '%,{0},%'".format(s) + " OR "
sql = sql.rstrip(" OR ")
sql = sql + ')'
# print(scopes)
# print(sql)
res = self... | n res:
# print(r)
ret = r
if None is ret:
raise Exception('指定されたScope {scopes} のうち少なくとも1つを持ったTokenが存在しません。: username={username}'.format(scopes=scopes, username=self.__username))
# このときTokenを生成するAPIを使うにはパスワードが必要。Basic認証でないと使えない
self.__token = ret['AccessToke... |
opendatateam/udata | udata/app.py | Python | agpl-3.0 | 6,961 | 0.000144 | import bson
import datetime
import logging
import os
import importlib
import types
from os.path import abspath, join, dirname, isfile, exists
from flask import (
Flask, abort, g, send_from_directory, json, Blueprint as BaseBlueprint,
make_response
)
from flask_caching import Cache
from flask_wtf.csrf import ... | _app = ProxyFix(app.wsgi_app)
init_logging(app)
register_extensions(app)
return app
def standalone(app):
'''Factory for an all in one application'''
from udata import api, core, frontend
core.init_app(app)
frontend.init_app( | app)
api.init_app(app)
register_features(app)
return app
def register_extensions(app):
from udata import (
models, routing, tasks, mail, i18n, auth, search, sitemap,
sentry
)
tasks.init_app(app)
i18n.init_app(app)
models.init_app(app)
routing.init_app(app)
aut... |
Ameriks/velo.lv | velo/registration/migrations/0008_companyparticipant_bike_brand.py | Python | gpl-3.0 | 668 | 0.001499 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-12-18 09:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20181218_0905'),
('registration',... | ions = [
migrations.AddField(
model_name='companyparticipant',
name='bike_brand',
field=models.ForeignKey(blank=True, null=True, on_delete=django. | db.models.deletion.CASCADE, related_name='+', to='core.Choices', verbose_name='Velo Zīmols'),
),
]
|
stoq/stoqdrivers | stoqdrivers/printers/capabilities.py | Python | lgpl-2.1 | 4,905 | 0.00265 | # -*- Mode: Python; coding: iso-8859-1 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Stoqdrivers
# Copyright (C) 2005 Async Open Source <http://www.async.com.br>
# All rights reserved
#
# 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
# ... | lf.max_len or float('inf')):
raise CapabilityError("the value can't be greater than %d "
"characters" % self.max_len)
elif len(value) < (self.min_len or float('-inf')):
raise CapabilityError("the value can't be | less than %d "
"characters" % self.min_len)
return
elif not (self.max_size and self.min_size):
return
if not isinstance(value, (float, int)):
raise CapabilityError("the value must be float, integer or long")
if value > (... |
isitornot/common | isitornot/rest_utils.py | Python | gpl-3.0 | 710 | 0.002817 | from functools import wraps
import json
import jsonschema
from sanic import exceptions
def validate_json(schema_file=None):
schema = json.load(open(schema_file))
def factory(f):
@wraps(f)
def decorated(self, request, *args, **karg | s):
| try:
jsonschema.validate(request.json, schema)
except json.JSONDecodeError as err:
raise exceptions.InvalidUsage("Invalid JSON") from err
except jsonschema.ValidationError as err:
raise exceptions.SanicException("JSON does not match schema", status... |
dikujepsen/OpenTran | v1.0/src/framework/rewriter.py | Python | mit | 39,294 | 0.00738 | import copy
import os
from visitor import *
from stringstream import *
class Rewriter(NodeVisitor):
""" Class for rewriting of the original AST. Includes:
1. the initial small rewritings,
2. transformation into our representation,
3. transforming from our representation to C-executable code,
4. cre... | dditional cl_mem variables that we add
# when we to perform Constant Memory transformation
self.ConstantMem = dict()
# Name swap in relation to [local memory]
self.LocalSwap = dict()
# Extra things that we add to ids [local memory]
self.Add = dict()
# Holds... |
self.Includes = list()
# Holds the ast for a function that returns the kernelstring
self.KernelStringStream = list()
# Holds a list of which loops we will unroll
self.UnrollLoops = list()
# True is SetDefine were called.
self.DefinesAreMade = False
# List... |
VirusTotal/content | Packs/FeedMitreAttackv2/Integrations/FeedMitreAttackv2/test_data/mitre_test_data.py | Python | mit | 33,575 | 0.004468 | ATTACK_PATTERN = {
'response': {
"id": "attack-pattern--01a5a209-b94c-450b-b7f9-946497d91055",
"name": "ATTACK_PATTERN 1",
"type": "attack-pattern",
"modified": "2020-05-13T22:50:51.258Z",
"created": "2017-05-31T21:30:44.329Z",
"description": "Adversaries may abuse Wi... | ATTERN 1'},
{'T1047': 'ATTACK_PATTERN 1'})
}
STIX_ATTACK_PATTERN = {
'response': {
"id": "attack-pattern--01a5a209-b94c-450b-b7f9-946497d91055",
"name": "ATTACK_PATTERN 1",
"type": "attack-pattern",
"modified": "2020-05-13T22:50:51.258Z",
"created": "2017-0... | e_platforms": [
"Windows"
],
"external_references": [
{
"url": "https://attack.mitre.org/techniques/T1047",
"source_name": "mitre-attack",
"external_id": "T1047"
},
{
"description": "Wikipedia... |
phoxicle/timboektu | timboektu/books/views.py | Python | mit | 4,914 | 0.010989 | from models import Post, PostForm, Department
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render, redirect
from django.template.loader import render_to_string
import os
from django.core.mail import send_mail
from django.core.p... | ail.html', {'post': p, 'mailto': mailto })
def edit(request, post_hash):
p = get_object_or_404(Post, hash=post_hash)
# Update
if request.method == 'POST':
form = PostForm(request.POST, instanc | e=p)
if form.is_valid():
p.set_isbn_int()
p.save()
return HttpResponseRedirect(reverse('timboektu.books.views.detail', kwargs={'post_id': p.id}))
# Edit
else:
form = PostForm(instance=p)
return render(request, 'edit.html', {
'form' : form,
... |
johnnywell/snowman | api/permissions.py | Python | mit | 595 | 0 | from rest_fram | ework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edi | t it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return... |
misaelnieto/lfs_downloads | runtests.py | Python | bsd-3-clause | 412 | 0 | #!/ | usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ['DJANGO_SETTINGS_MODULE'] = 'lfs_downloads.tests._settings'
import django
from django.conf import settings
from django.test.utils import get_runner
django.setup()
TestRunner = get_runner(settings)
test_runner = T... | n_tests(["tests"])
sys.exit(bool(failures))
|
miguelgrinberg/heat | heat/engine/resources/scheduler_hints.py | Python | apache-2.0 | 1,805 | 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
# ... |
class SchedulerHintsMixin(object):
'''
Utility class to encapsulate Scheduler Hint related logic shared
between resources.
'''
HEAT_ROOT_STACK_ID = 'heat_root_stack_id'
HEAT_STACK_ID = 'heat_stack_id'
HEAT_STACK_NAME = 'heat_stack_name'
HEAT_PATH_IN_STACK = 'heat_path_in_stack'
HEA... | cheduler_hints):
'''Augment scheduler hints with supplemental content.'''
if cfg.CONF.stack_scheduler_hints:
if scheduler_hints is None:
scheduler_hints = {}
scheduler_hints[self.HEAT_ROOT_STACK_ID] = \
self.stack.root_stack_id()
schedu... |
michaelbradley91/GameUtility | GameUtility/mjb/dev/game_utility/input_listeners/keyboard_listener.py | Python | mit | 2,293 | 0.008722 | '''
Created on 16 May 2014
@author: michael
'''
import mjb.dev.game_utility.graphics.screen as screen, pygame.locals
class KeyboardListener(object):
'''
The keyboard listener will receive all key up and key down events that it registers for.
There are many keys, so you are asked to register for specific ... | s):
'''
Called when a key is pressed for the first time (only once - not continually while held)
@param key: the key that was pushed down
@param key_modifiers: any modifiers (shift etc) pressed when the key was pressed
'''
pass
def key_up(self, key, key_modifiers... | modifiers: any modifiers (shift etc) pressed while the key was released
'''
pass
|
elzaggo/pydoop | examples/pydoop_script/scripts/caseswitch.py | Python | apache-2.0 | 1,200 | 0 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2018 CRS4.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | pty string when running this example.
"""
def mapper(_ | , record, writer, conf):
if conf['caseswitch.case'] == 'upper':
value = record.upper()
elif conf['caseswitch.case'] == 'lower':
value = record.lower()
else:
raise RuntimeError(
"Invalid caseswitch value %s" % conf['caseswitch.case']
)
writer.emit("", value)
|
rmodrak/seisflows | seisflows/workflow/test_preprocess.py | Python | bsd-2-clause | 5,497 | 0 | #
# This is Seisflows
#
# See LICENCE file
#
###############################################################################
# Import system modules
import sys
import traceback
from glob import glob
from os.path import abspath, basename, dirname, exists
# Import Numpy
import numpy as np
# Local imports
from seisflow... | , nt, dt))
filename = PATH.WORKDIR+'/'+'output_misfit'
np.savetxt(filename, rsd)
print ''
def test_adjoint(self, dat, syn):
nt, dt, _ = preprocess.get_time_scheme(syn)
| nn, _ = preprocess.get_network_size(syn)
adj = syn
for ii in range(nn):
adj[ii].data = preprocess.adjoint(syn[ii].data, dat[ii].data, nt,
dt)
self.save(adj, 'output_adjoint')
print ''
def save(self, data, filename):
... |
KarrLab/kinetic_datanator | datanator/data_source/modomics.py | Python | mit | 13,680 | 0.004753 | """ Use BpForms to gather rRNA and tRNA modification information from
`MODOMICS <https://iimcb.genesilico.pl/modomics/>`.
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2020-04-23
:Copyright: 2019, Karr Lab
:License: MIT
"""
import bpforms
import bs4
import csv
import os
import requests
import requests_cache
class ... | et('19U')
modomics_short_code_to_monomer['ˆ'] = bpforms.rna_alphabet.monomers.get('00A')
modomics_short_code_to_monomer['gluQtRNA'] = bpforms.rna_alphabet.monomers.get('105G')
modomics_short_code_to_monomer['m22G'] = bpforms.rna_alphabet.monomers.get('22G' | )
# modomics_short_code_to_monomer[';'] = bpforms.rna_alphabet.monomers.get('?G')
# modomics_short_code_to_monomer['<'] = bpforms.rna_alphabet.monomers.get('?C')
# output directory
out_dir = os.path.dirname(__file__)
# create cache for web queries
cache_name = os.path.j... |
wavelets/hebel | hebel/pycuda_ops/softmax.py | Python | gpl-2.0 | 2,475 | 0.003232 | # Copyright (C) 2013 Hannes Bretschneider
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distribut... | rn max_dim
def softmax(mat, tmp=None):
if tmp is None:
tmp = gpuarray.empty_like(mat)
L = logsumexp(mat, tmp)
add_vec_to_mat(mat, L, target=tmp, substract=True)
exp_func.prepared_async_call(t | mp._grid, tmp._block, None,
tmp.gpudata, tmp.gpudata,
tmp.mem_size)
return tmp
def cross_entropy(x, y):
loss = y * cumath.log(x + eps)
nan_to_zeros(loss, loss)
loss = -gpuarray.sum(loss)
return float(loss.get())
def cross_entropy_lo... |
acsone/social | mail_edit/__openerp__.py | Python | agpl-3.0 | 764 | 0 | # -*- coding: utf-8 -*-
# | © 2016 Sunflower IT (http://sunflowerweb.nl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Message Edit",
"summary": "Adds an option to edit mail to different partners",
"version": "8.0.1.0.0",
"category": "Social Network",
"website": "https://sunflowerweb.nl",
"au... | web",
],
"data": [
"security/mail_edit_security.xml",
"views/assets.xml",
"views/compose_message.xml",
"views/res_request_link.xml",
],
"qweb": [
"static/src/xml/mail_edit.xml",
],
}
|
alexlovelltroy/django-avatar | avatar/settings.py | Python | bsd-3-clause | 1,436 | 0.003482 | from django.conf import settings
try:
from PIL import Image
dir(Image) # Placate PyFlakes
except ImportError:
import Image
AVATAR_DEFAULT_SIZE = getattr(settings, 'AVATAR_DEFAULT_SIZE', 80)
AUTO_GENERATE_AVATAR_SIZES = getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (AVATAR_DEFAULT_SIZE,))
AVATAR_RESIZE_M... | _ALLOWED_FILE_EXTS', None)
AVATAR_CACHE_TIMEOUT = getattr(settings, 'AVATAR_CA | CHE_TIMEOUT', 60*60)
AVATAR_CLEAN_REMOVED = getattr(settings, 'AVATAR_CLEAN_REMOVED', False)
|
jawilson/home-assistant | homeassistant/components/maxcube/__init__.py | Python | apache-2.0 | 3,289 | 0.000304 | """Support for the MAX! Cube LAN Gateway."""
import logging
from socket import timeout
from threading import Lock
import time
from maxcube.cube import MaxCube
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SCAN_INTERVAL
import homeassistant.helpers.config_validation as cv
from hom... | notification_id=NOTIFICATION_ID,
)
connection_failed += 1
if connection_failed >= len(gateways):
return False
load_platform(hass, "climate", DOMAIN, {}, config)
load_platform(hass, "binary_sensor", DOMAIN, {}, config)
return True
class MaxCubeHandle:
"""Keep the... | "
self.cube = cube
self.cube.use_persistent_connection = scan_interval <= 300 # seconds
self.scan_interval = scan_interval
self.mutex = Lock()
self._updatets = time.monotonic()
def update(self):
"""Pull the latest data from the MAX! Cube."""
# Acquire mutex ... |
nacc/autotest | client/virt/tests/trans_hugepage_swapping.py | Python | gpl-2.0 | 4,326 | 0.00208 | import logging, os, re
from autotest.client.shared import error
from autotest.client import utils
from autotest.client.virt import virt_utils, virt_test_utils
from autotest.client.virt import virt_env_process
@error.context_aware
def run_trans_hugepage_swapping(test, params, env):
"""
KVM khugepage user side ... | otal - free):
count = total / hugepage_size
tmpfs_size = total
else:
count = free / hugepage_size
tmpfs_size = free
if swap_size <= 0:
logging.warning("Host does not have swap enabled")
session = None
try:
if not os... | _path)
utils.run("mount -t tmpfs -o size=%sM none %s" % (tmpfs_size,
mem_path))
# Set the memory size of vm
# To ignore the oom killer set it to the free swap size
vm = env.get_vm(params.get("main_vm"))
... |
v-iam/azure-sdk-for-python | azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/catalog/models/usql_index.py | Python | mit | 3,147 | 0.000636 | # coding=utf-8
# -------------------------------------------------------------------------- |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated. |
# --------------------------------------------------------------------------
from msrest.serialization import Model
class USqlIndex(Model):
"""A Data Lake Analytics catalog U-SQL table index item.
:param name: the name of the index in the table.
:type name: str
:param index_keys: the list of direct... |
klahnakoski/Bugzilla-ETL | vendor/mo_logs/__init__.py | Python | mpl-2.0 | 19,331 | 0.003621 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from __f... | ozLog import StructuredLogger_usingMozLog
return StructuredLogger_usingMozLog(STDOUT, coalesce(settings.app_name, settings.appname))
if settings.log_type == "stream" or settings.stream:
| from mo_logs.log_usingThreadedStream import StructuredLogger_usingThreadedStream
return StructuredLogger_usingThreadedStream(settings.stream)
if settings.log_type == "elasticsearch" or settings.stream:
from mo_logs.log_usingElasticSearch import StructuredLogger_usingElasticSea... |
bhargavz/py-twitter-sentiment-analysis | common/AsyncTimer.py | Python | mit | 3,481 | 0.016087 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# FILE: AsyncTimer.py
# DATE: April, 2012
#
# A timer that will automatically launch timed queries for
# asynchronous web service queries based on Base. The timer
# will support some randomness
#
# Copyright by Author. All rights reserved. Not for reuse without
... | # watch for it to start running
| time.sleep(5)
else:
time.sleep(wt)
self.ticks += 1
if( self.do_print ):
print "<%s-%d:%f>"%(self.name,self.ticks,wt)
return
##
#
def start_thread(self, d=True):
self.daemon = d
self.r... |
dmsurti/mayavi | mayavi/preferences/preference_manager_view.py | Python | bsd-3-clause | 2,553 | 0.001567 | """
A view for the Mayavi preferences outside of Envisage.
"""
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Standard library imports
from os.path import join
# Enthought library imports.
from traits.api import List
from apptools.pre... | ences_node import PreferencesNode
# Local imports.
from mayavi.preferences.mayavi_preferences_page import \
MayaviRootPreferencesPage, MayaviMlabPreferencesPage
f | rom mayavi.preferences.preference_manager import \
preference_manager
################################################################################
# `PreferenceManagerView` class
################################################################################
class PreferenceManagerView(PreferencesManager):
... |
mate-desktop/pluma | plugins/snippets/snippets/SubstitutionParser.py | Python | gpl-2.0 | 5,925 | 0.005401 | # Pluma snippets plugin
# Copyright (C) 2006-2007 Jesse van den Kieboom <jesse@icecrew.nl>
# Copyright (C) 2012-2021 MATE Developers
#
# 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 Foun... | ) and self.groups[group]) or ''
for modifier in modifiers:
if self.modifiers.has_key(modifier):
result = self.modifiers[modifier](result)
return result
def _match_group(self, tokens):
| match = re.match('\\\\%s' % self.REG_GROUP, tokens)
if not match:
return None, tokens
return self._substitute(match.group(1) or match.group(2), match.group(3) or ''), tokens[match.end():]
def _escape(self, tokens, terminator):
# Try to match a group
result, token... |
IntelLabs/hpat | examples/series/series_idxmin.py | Python | bsd-2-clause | 1,752 | 0 | # *****************************************************************************
# Copyright (c) 2020, Intel Corporation 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 sou... | TED 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 O | UT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
import numpy as np
import pandas as pd
from numba import njit
@njit
def series_idxmin():
s = pd.Series([4, np.nan, 2, 1], index=['A', 'B', 'C', 'D']... |
tipsi/aiozk | aiozk/recipes/double_barrier.py | Python | mit | 2,390 | 0 | import asyncio
import logging
from aiozk import exc, WatchEvent, Deadline
from .sequential import SequentialRecipe
log = logging.getLogger(__name__)
class DoubleBarrier(SequentialRecipe):
ZNODE_LABEL = 'worker'
def __init__(self, base_path, min_participants):
super().__init__(base_path)
se... | h=True)
await self.create_unique_znode(self.ZNODE_LABEL)
if exists:
return
try:
_, participants = await self.analyze_siblings()
if len(participants) >= self.min_participants:
await self.create_znode(self.sentinel_path)
return... | rier_lifted, deadline.timeout)
else:
await barrier_lifted
except asyncio.TimeoutError:
raise exc.TimeoutError
except Exception:
await self.delete_unique_znode_retry(self.ZNODE_LABEL)
raise
async def leave(self, timeout=... |
golismero/golismero | thirdparty_libs/num2words/lang_EN_GB.py | Python | gpl-2.0 | 1,930 | 0.00829 | # Copyright (c) 2003, Taro Ogawa. All Rights Reserved.
# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved.
# This library 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
# versi... | 01 USA
from __future__ | import unicode_literals
from .lang_EN import Num2Word_EN
class Num2Word_EN_GB(Num2Word_EN):
def to_currency(self, val, longval=True):
return self.to_splitnum(val, hightxt="pound/s", lowtxt="pence",
jointxt="and", longval=longval)
n2w = Num2Word_EN_GB()
to_card = n2w.... |
wittawatj/fsic-test | fsic/data.py | Python | mit | 23,442 | 0.006271 | __author__ = 'wittawat'
from abc import ABCMeta, abstractmethod
import math
import matplotlib.pyplot as plt
import numpy as np
import fsic.util as util
import matplotlib.pyplot as plt
import scipy.stats as stats
class PairedData(object):
"""Class representing paired data for independence testing
properties:
... | return self.pdata.dy()
class PSStraResample(PairedSource):
"""
A PairedSource which does a stratified subsampling. without replacement
from the specified PairedData.
The implementation is only approximately correctly.
"""
def __init__(self, pda | ta, pivot):
"""
pivot: a one-dimensional numpy array of the same size as pdata.sample_size()
indicating the class of each point.
"""
if len(pivot) != pdata.sample_size():
raise ValueError('pivot must have the same length as the data.')
self.pdata = pdata
... |
mrunge/horizon | openstack_dashboard/dashboards/project/databases/tests.py | Python | apache-2.0 | 14,619 | 0.000274 | # Copyright 2013 Mirantis Inc.
# Copyright 2013 Rackspace Hosting.
#
# 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
#
# Unles... | ttpRequest))\
.AndReturn(self.datastores.list())
# Mock datastore versions
api.trove.datastore_version_list(IsA(http.HttpRequest),
Is | A(str)).AndReturn(self.datastore_versions.list())
api.neutron.network_list(IsA(http.HttpRequest),
tenant_id=self.tenant.id,
shared=False).AndReturn(
self.networks.list()[:1])
api.neutron.network_list... |
SpaceKatt/CSPLN | apps/scaffolding/mac/web2py/web2py.app/Contents/Resources/lib/python2.7/matplotlib/mlab.py | Python | gpl-3.0 | 100,604 | 0.006024 | """
Numerical python functions written for compatability with MATLAB
commands with the same names.
MATLAB compatible functions
-------------------------------
:func:`cohere`
Coherence (normalized cross spectral density)
:func:`csd`
Cross spectral density uing Welch's average periodogram
:func:`detrend`
Remov... | ut scipy (and the far superior
scipy.integrate tools)
:meth:`contiguous_regions`
return the indices of the regions spanned by some logical mask
:meth:`cross_from_below`
return the indices where a 1D array crosses a threshold from below
:meth:`c | ross_from_above`
return the indices where a 1D array crosses a threshold from above
record array helper functions
-------------------------------
A collection of helper methods for numpyrecord arrays
.. _htmlonly:
See :ref:`misc-examples-index`
:meth:`rec2txt`
pretty print a record array
:meth:`rec2c... |
neuhausler/fboss | fboss/py/fboss/cli/commands/l2.py | Python | bsd-3-clause | 1,208 | 0 | #!/usr/bin/env python3
#
# Copyright (c) 2004-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same direct... | if port_data == entry.port:
if port_info.name:
port_data = port_info.name
print(tmpl.format(entry.ma | c, port_data, entry.vlanID))
|
tensorflow/neural-structured-learning | research/multi_representation_adversary/multi_representation_adversary/selectors.py | Python | apache-2.0 | 6,095 | 0.00443 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ast_update_epoch >= self.update_freq
def update(self, epoch, validation_losses):
"""Updates the strategy's state based on current validation los | ses.
Args:
epoch: Current epoch number.
validation_losses: A list of numbers, one for each representation.
"""
self._update(epoch, validation_losses)
self.last_update_epoch.assign(epoch)
# Log the counts since last update to the summary and reset the counts.
for i in range(self.num_... |
googleapis/python-tasks | samples/snippets/create_http_task.py | Python | apache-2.0 | 4,532 | 0.000662 | # Copyright 2019 Google LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | mport tasks_v2
from google.protobuf import tim | estamp_pb2, duration_pb2
import datetime
import json
# Create a client.
client = tasks_v2.CloudTasksClient()
# TODO(developer): Uncomment these lines and replace with your values.
# project = 'my-project-id'
# queue = 'my-queue'
# location = 'us-central1'
# url = 'https://example.c... |
matllubos/django-simple-utilities | utilities/forms/validators.py | Python | gpl-3.0 | 479 | 0.018789 | # coding: utf-8
from django.utils.translation import ugettext_lazy as _
class MultiFieldsValidator(object):
fields = ()
error_messages = {
'invalid' : _(u'Value is not valid.')
| }
def raise_error(self, form, error="invalid"):
for field in self.fields:
form._errors[field] = form.error_class([self.error_messages[error]])
def validate(self, cleaned_data, form):
return cleaned_da | ta
|
DayGitH/Python-Challenges | DailyProgrammer/20120521B.py | Python | mit | 790 | 0.002532 | """
Write a program that will allow the user to enter two characters. The program will validate the characters to make sure they are in the range '0' to '9'. The program will display their sum. The output should look like this.
INPUT .... OUTPUT
3 6 ........ 3 + 6 = 9
4 9 ........ 4 + 9 = 13
0 9 ........ 0 + 9 = 9
g 6 ... | ..... Invalid
7 h ........ Invalid
thanks to frenulem for the challenge at /r/dailyprogrammer_ideas .. please ignore the dots :D .. it was messing with the formatting actually
"""
def main():
print('Input values separated by spaces')
inp = input('> ')
inp = inp.split()
try:
print('{} = {}'.for... | (-1)
if __name__ == "__main__":
main()
|
adrianschroeter/kiwi | test/unit/iso_tools_cdrtools_test.py | Python | gpl-3.0 | 5,919 | 0 | from mock import patch, call
import mock
from collections import namedtuple
from .test_helper import raises, patch_open
from kiwi.iso_tools.cdrtools import IsoToolsCdrTools
from kiwi.exceptions import KiwiIsoToolError
class TestIsoToolsCdrTools(object):
@patch('platform.machine')
def setup(self, mock_machine... | s
):
mock_has_option_in_help.return_value = True
mock_getsize.return_value = 4096
mock_exists.return_value = True
self.iso_tool.add_efi_loader_parameters()
assert self.iso_tool.iso_loaders == [
'-eltorito-alt-boot', '-eltorito-platform', 'efi',
'-b', | 'boot/x86_64/efi',
'-no-emul-boot', '-joliet-long',
'-boot-load-size', '8'
]
@patch('os.path.exists')
@patch('os.path.getsize')
@patch('kiwi.iso_tools.cdrtools.CommandCapabilities.has_option_in_help')
def test_add_efi_loader_parameters_big_loader(
self, mock_has_... |
sanctuaryaddon/sanctuary | plugin.video.quantum/lib/comedy.py | Python | gpl-2.0 | 12,158 | 0.035203 | import sys, process
import urllib2,re,os,base64,xbmc,xbmcplugin,xbmcaddon,xbmcgui,urlparse,urllib
import urlresolver,yt
try:
import json
except:
import simplejson as json
from threading import Thread
BASE = 'http://www.couchtripper.com/forum2/page.php?page=3'
Sources = ['daclips','filehoot','allmyvideos','vids... | = FANART
if '.php' in url:
process.Menu(name,url,104,image,fanart,desc,'')
if mode == 'single':
process.Play(name,url,109,image,fanart,desc,'')
elif mode == 'playlist':
process.Menu(name,url,107,image,fanart,desc,'')
elif mode == 'watchseries':
... | ss.Menu(name,url,112,image,fanart,desc,name)
elif mode == 'normal':
process.Play(name,url,105,image,fanart,desc,'')
xbmcplugin.addSortMethod(addon_handle, xbmcplugin.SORT_METHOD_TITLE);
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def Search():
Dialog = xbmcgui.Dialog(... |
RIP95/kurisu-bot | addons/deuces/card.py | Python | mit | 5,195 | 0.000385 | class Card:
"""
Static class that handles cards. We represent cards as 32-bit integers, so
there is no object instantiation - they are just ints. Most of the bits are
used, and have a specific meaning. See below:
Card:
bitrank suit rank... | def int_to_str(card_int):
rank_int = Card.get_rank_int(card_int | )
suit_int = Card.get_suit_int(card_int)
return Card.STR_RANKS[rank_int] + Card.INT_SUIT_TO_CHAR_SUIT[suit_int]
@staticmethod
def get_rank_int(card_int):
return (card_int >> 8) & 0xF
@staticmethod
def get_suit_int(card_int):
return (card_int >> 12) & 0xF
@staticmet... |
VladMinzatu/surfer | test-webapp/webapp.py | Python | mit | 1,072 | 0.008396 | from bottle import route, get, post, run, static_file, request
import json
import socket
scores = {}
HOST, PORT = "localhost", 9999
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.bind((HOST, PORT))
socket_server.listen(10)
print('Waiting for connection from Spark Streaming...')
conn,... | )
@get('/items')
def get_scores():
items = [{'item':x, 'score':scores[x]} for x in scores]
return json.dumps(sorted(items, key=lambda x: -x['score']))
@post('/items')
def update_snapshot():
global scores
new_scores = json.loads(str(request.body.getvalue().decode("utf-8")))
for x in new_scores:
... | me + '\n','utf-8'))
run(host='localhost', port=8080)
|
ijat/Hotspot-PUTRA-Auto-login | PyInstaller-3.2/PyInstaller/hooks/hook-PyQt5.QtCore.py | Python | gpl-3.0 | 552 | 0.005435 | #-----------------------------------------------------------------------------
# Copyright (c) 2013-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... | PyInstaller.utils.hooks impo | rt qt_plugins_binaries
binaries = qt_plugins_binaries('codecs', namespace='PyQt5')
|
mozman/ezdxf | src/ezdxf/layouts/layouts.py | Python | mit | 14,153 | 0.000283 | # Copyright (c) 2011-2021, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING, Dict, Iterator, List, cast, Optional
import logging
from ezdxf.lldxf.const import DXFKeyError, DXFValueError, DXFInternalEzdxfError
from ezdxf.lldxf.const import (
MODEL_SPACE_R2000,
PAPER_SPACE_R2000,
TMP_PAP... | e}" already exist.')
dxfattribs = dict(dxfattribs or {}) # copy attribs
dxfattribs["owner"] = self._dxf_layouts.dxf.handle
dxfattribs.setdefault("taborder", len(self._layouts) + 1)
block_name = self.unique_paperspace_name()
layout = Paperspace.new(
name, block_name,... | oc, dxfattribs=dxfattribs
)
# Default extents are ok!
# Reset limits to (0, 0) and (paper width, paper height)
layout.reset_limits()
self._add_layout(name, layout)
return layout # type: ignore
@classmethod
def load(cls, doc: "Drawing") -> "Layouts":
"""C... |
sebastienbarbier/723e_server | seven23/models/transactions/migrations/0007_auto_20171015_0312.py | Python | mit | 335 | 0.002985 | # -*- coding: utf-8 -*-
# Generated by Django 1.10. | 5 on 2017-10-15 03:12
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('transactions', '0006_auto_201 | 70811_1131'),
]
operations = [
] |
css-lucas/GAT | gat/core/gsa/core/geojson.py | Python | mit | 820 | 0.006098 | import shapefile
from json import dumps
def convert(inputpath):
# read the shapefile
# reader = shapefile.Reader("network/street_crimes.shp")
reader = shapefile.Reader(inputpath)
fields = reader.fields[1:]
| field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
atr = dict(zip(field_names, sr.record))
geom = sr.shape.__geo_interface__
buffer.append(dict(type="Feature", \
geometry=geom, properties=atr))
# write the GeoJSO... | dumps({"type": "FeatureCollection", \
"features": buffer}, indent=2) + "\n")
geojson.close() |
Sir-Henry-Curtis/Ironworks | ironworks/__init__.py | Python | mit | 7,678 | 0.001433 | # -*- coding: utf-8 -*-
"""Ironworks module"""
import sys
import os
import subprocess
import threading
import wsgiserver
from Ironworks import app
from Logger import ironworksLogger
from apscheduler.scheduler import Scheduler
FULL_PATH = None
RUNDIR = None
ARGS = None
DAEMON = False
PIDFILE = None
VERBOSE = True
LOG_... | b
SCHEDULE.add_interval_job(checkGithub, hours=6)
SCHEDULE.start()
def start():
"""Start the actual server"""
if __INITIALIZED__:
#start_schedules()
if not DEVELOPMENT:
try:
logger.log('Starting IRONWORKS on %s:%i%s' % (HOST, PORT, WEBROOT), 'INFO')
... | pass
except KeyboardInterrupt:
stop()
else:
logger.log('Starting IRONWORKS development server on port: %i' % (PORT), 'INFO')
logger.log(' ##### IMPORTANT : WEBROOT DOES NOT WORK UNDER THE DEV SERVER #######', 'INFO')
app.run(debug=True, port=... |
audreyr/design | tests/test_clouds.py | Python | bsd-3-clause | 467 | 0.002141 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_clouds
--------------
Tests for `design.clouds` module.
"""
import imghdr
import os
import unitt | est
from design import clouds
class TestClouds(unittest.TestCase):
def test_draw_cloud(self):
| clouds.draw_cloud()
self.assertEqual(imghdr.what('cloud.png'), 'png')
@classmethod
def tearDownClass(cls):
os.remove('cloud.png')
if __name__ == '__main__':
unittest.main()
|
linsalrob/EdwardsLab | phage_clustering/bit_score.py | Python | mit | 3,193 | 0.002192 | """
"""
import os
import sys
import argparse
from roblib import bcolors, stream_blast_results
__author__ = 'Rob Edwards'
def self_bit_scores(blastf, verbose=False):
"""
Generate a dict of self:self bitscores
"""
ss = {}
for b in stream_blast_results(blastf, verbose):
if b.query == b.db:
... | s if we can!
if b.query in ss and b.db in ss | :
nb = b.bitscore / ((ss[b.query] + ss[b.db])/2)
else:
# if we can't do that, we cheat and normalize
# the bit score by twice
# the average length of the proteins
# i.e. the sum of the lengths
nb = b.bitscore / (b.query_length + b.subject_... |
codeka/website | handlers/main.py | Python | mit | 1,134 | 0.0097 | from flask import Response, render_template
from model import blog
from . import handlers
@handlers.route('/')
def index():
return render_template('index.html')
@han | dlers.route('/showcase')
def showcase():
return render_template('showcase.html')
@handlers.route('/picscan')
def picscan():
return render_template('picscan/index.html')
@handlers.route('/picscan/privacy-policy')
def picscan_privacy():
return render_template('picscan/privacy-policy.html')
@handlers.route('/s... | yearly"
})
for f in blog.listPosts():
post = blog.loadPost(f)
pages.append({
"url": ("//www.codeka.com/blog/%04d/%02d/%s" %
(post.posted.year, post.posted.month, post.slug)),
"lastmod": "%04d-%02d-%02d" % (post.updated.year, post.updated.month, post.updated.day),
... |
polosate/get_subscribes | db_migrate.py | Python | mit | 828 | 0.006039 | import imp
from migrate.versioning import a | pi
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
migration = SQLALCHEMY_MIGRATE_R | EPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1)
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec(old_model) in tmp_module.__dict__
script = api.make_update_script_for_model(SQLALCHEMY... |
cbrepo/celery | examples/httpexample/urls.py | Python | bsd-3-clause | 246 | 0.004065 | from django.c | onf.urls import *
import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^multiply/', views.multiply, name="multiply"),
| )
|
bflaven/BlogArticlesExamples | extending_streamlit_usage/001_nlp_spacy_python_realp/013_nlp_spacy_python.py | Python | mit | 2,127 | 0.009438 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
[path]
cd /Users/brunoflaven/Documents/01_work/blog_articles/extending_streamlit_usage/001_nlp_spacy_python_realp/
[file]
python 013_nlp_spacy_python.py
# source
Source: https://realpython.com/natural-language-processing-spacy-python/
"""
import spacy
from spacy... | in profile: https://fr.linkedin.com/in/brunoflaven. He is currently working for a Paris-base In France Media Monde (FMM) mostly on mobile applications (iOS and Android). He is currently P.O for a Backoffice project made with Symfony.'
'He also made few trainings to facili | tate the handling of the tools that he helps to make.'
)
complete_doc = nlp(complete_text)
def is_token_allowed(token):
'''
Only allow valid tokens which are not stop words
and punctuation symbols.
'''
# if (not token or not token.string.strip() or token.is_stop or token.is_punct):
... |
atareao/utext | src/utext/preferences_dialog.py | Python | gpl-3.0 | 17,473 | 0.000057 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of utext
#
# Copyright (C) 2012-2016 Lorenzo Carbonell
# lorenzo.carbonell.cerezo@gmail.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 Softw... | , see <http://www.gnu.org/licenses/>.
import gi
try:
gi.require_version('Gtk', '3.0')
gi.require_version('Pango', | '1.0')
except Exception as e:
print(e)
exit(1)
from gi.repository import Gtk
from gi.repository import Pango
import os
from .driveapi import DriveService
from .services import DropboxService
from .logindialog import LoginDialog
from . import comun
from .comun import _
from .configurator import Configuration
d... |
mclearc/beets | test/test_mediafile_basic.py | Python | mit | 12,027 | 0.004324 | # This file is part of beets.
# Copyright 2011, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... | message = field + ' modified incorrectly (changed to ' + \
repr(self.value) + ' but read ' + repr(got) + \
') when testing ' + os.path.basename(path)
if isinstance(self.value, float):
self.assertAlmo... | ther field was changed.
else:
# MPEG-4: ReplayGain not implented.
if 'm4a' in path and readfield.startswith('rg_'):
continue
# The value should be what it was originally most of the
# time.
... |
mesonbuild/meson | test cases/common/99 postconf/postconf.py | Python | apache-2.0 | 364 | 0 | #!/usr/bin/en | v python3
import os
template = '''#pragma once
#define THE_NUMBER {}
'''
input_file = os.path.join(os.environ[ | 'MESON_SOURCE_ROOT'], 'raw.dat')
output_file = os.path.join(os.environ['MESON_BUILD_ROOT'], 'generated.h')
with open(input_file) as f:
data = f.readline().strip()
with open(output_file, 'w') as f:
f.write(template.format(data))
|
suutari/shoop | shuup_tests/utils/test_patterns.py | Python | agpl-3.0 | 4,026 | 0 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from shuup.utils.patterns import _compile_pattern, P... | r):
range_pat = ctor("10-30,!20,40")
assert not range_pat.matches("5")
assert range_pat.matches("10")
assert not range_pat.matches("20")
assert range_pat.matches("30")
assert not range_pat.matches("35")
assert range_pat.matches("40")
assert not range_pat.matches("50")
@pyt | est.mark.parametrize("ctor", (Pattern, ReconstitutedPattern))
def test_wildcards(ctor):
wc_pat = ctor("1*,!11*")
assert wc_pat.matches("1000")
assert not wc_pat.matches("1100")
@pytest.mark.parametrize("ctor", (Pattern, ReconstitutedPattern))
def test_num_match(ctor):
num_pat = ctor("1-100")
asser... |
XENON1T/processing | montecarlo/fax_waveform/MidwayBatch.py | Python | apache-2.0 | 4,098 | 0.010249 | ####################################
## batch code for WF simulation
####################################
import sys, array, os, getpass
from subprocess import call
import subprocess as subp
import time
import math as math
from subprocess import Popen, PIPE
if len(sys.argv)<2:
print("========= Syntax ========")
... | subp.call("rm -r "+OutputPath, shell=True)
subp.call("mkdir -p "+OutputPath, shell=True)
# define filenames
SubmitFile = OutputPath+"/submit_"+ RunString + ".sh"
SubmitOutputFilename = OutputPath+"/submit_"+ RunString + ".log"
SubmitErrorFilename = OutputPath+"/submit_"+ RunString + ".log... | H --output="+SubmitOutputFilename+"' >> "+SubmitFile, shell=True)
subp.call("echo '#SBATCH --error="+SubmitErrorFilename+"' >> "+SubmitFile, shell=True)
subp.call("echo '#SBATCH --time=03:59:00' >> "+SubmitFile, shell=True)
subp.call("echo '#SBATCH --account=pi-lgrandi' >> "+SubmitFile, shell=True)
if I... |
guyromm/greencouriers | greencouriers/tests/functional/test_auth.py | Python | gpl-3.0 | 203 | 0.004926 | from greencouriers.tests import *
class TestAuth | Controller(TestController):
def test_index(self):
response = | self.app.get(url(controller='auth', action='index'))
# Test response...
|
access-missouri/am-django-project | am/legislative/management/__init__.py | Python | bsd-2-clause | 164 | 0.006098 | #!/usr/bin/env python |
# -*- coding: utf-8 -*-
from body_membership_copy import get_or_copy_body_membership_to_session, replicate_all_body_member | ships_into_session
|
VitalPet/hr | hr_employee_firstname/models/hr_employee.py | Python | agpl-3.0 | 4,126 | 0 | # | -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2010 - 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/... | blic 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 be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PA... |
OpenSourceActivismTech/call-power | tests/run.py | Python | agpl-3.0 | 684 | 0.002924 | import pytest
from dotenv import load_dotenv
from flask_testing import TestCase
if __name__ == '__main__' and __package__ is None:
load_dotenv()
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from call_server.app import create_app, db
from call_server.config ... | rn create_app(TestingConfig)
def setUp(self):
db.create_all()
def tearDown(self):
| db.session.remove()
db.drop_all()
if __name__ == '__main__':
pytest.main()
|
savfod/ptset | vec.py | Python | mit | 1,856 | 0 | import math
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vec(self.x + other.x, self.y + other.y)
def __abs__(self):
return math.sqrt(self.x**2 + self.y**2)
def coeff_prod(self, coeff):
return Vec(self.x * coeff, ... | return math.sqrt(self.x**2 + self.y**2 + self.z**2)
def coeff_prod(self, coeff):
return Vec(self.x * coeff, self.y * coeff, self.z * coeff)
def __sub__(self, other):
return self + other.coeff_prod(-1)
def __mul__(self, other):
# other is expected to be num. num*vec won't work
... | other):
# other is expected to be num. num*vec won't work
return self.coeff_prod(1 / other)
def __div__(self, other):
# other is expected to be num. num*vec won't work
return self.coeff_prod(1 / other)
def __str__(self):
return str(self.x) + " " + str(self.y) + " " + st... |
mayaculpa/wisp | wisp.py | Python | gpl-3.0 | 6,215 | 0.005953 | import RPi.GPIO as GPIO
import time
import subprocess
import datetime
import time
# Added to support voice command
import threading
import speech_recognition as sr
STATE_UNOCCUPIED = 0
STATE_OCCUPIED = 1
OCCUPIED_DISTANCE = 50
UNOCCUPIED_DURATION = 1200
def process_command(self, command):
if command.lower() == ... | _start) > UNOCCUPIED_DURATION:
say("goodbye.mp3")
state = STATE_UNOCCUPIED
logger.info("Workshop Unoccupied")
GPIO.cleanup()
'''Voice Commands
# Information Commands
Datetime - Gives the Date a | nd Time as audio
Status - Provides memory, disk, processor and network information
Project Report - Reports project name, number of images, videos and audio files in the current project
#Media-centric
Snap Webcam - Takes a picture with the webcam
Snap Picam - Takes a picture with the Picam
Roll... |
joshbrake/py-ic-imaging-control | pyicic/IC_Camera.py | Python | mit | 18,666 | 0.007447 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from builtins import object
from ctypes import *
import time
from .IC_GrabberDLL import IC_GrabberDLL
from .IC_Exception import IC_Exception
from .IC_Property import IC_Property
from . import IC_Struct... | ,
'RGB32',
'UYVY',
'Y16',
'NONE']
# c function type for frame callback
# outside of class so it can be called by unbound fu | nction
C_FRAME_READY_CALLBACK = CFUNCTYPE(None, GrabberHandlePtr, POINTER(c_ubyte), c_ulong, c_void_p)
class IC_Camera(object):
@property
def callback_registered(self):
return self._callback_registered
def __init__(self, unique_device_name):
self._unique_device_name = uniq... |
sxjscience/tvm | tests/python/relay/test_op_level1.py | Python | apache-2.0 | 18,600 | 0.00043 | # 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... | uses_gpu
def test_bias_add():
for dtype in ["float16", "float32"]:
xshape = (10, 2, 3, 4)
bshape = (2,)
rtol = 1e-2 if dtype == "float16" else 1e-5
x = relay.var("x", shape=xshape, dtype=dtype)
bias = relay.var("bias", dtype=dtype)
z = relay.nn.bias_add(x, bias)
... | == relay.TensorType(bshape, dtype)
func = relay.Function([x, bias], z)
x_data = np.random.uniform(size=xshape).astype(dtype)
y_data = np.random.uniform(size=bshape).astype(dtype)
ref_res = x_data + y_data.reshape((2, 1, 1))
for target, ctx in tvm.testing.enabled_targets():
... |
amanabt/DG_Maxwell | dg_maxwell/msh_parser.py | Python | gpl-3.0 | 8,277 | 0.011598 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.lines as lines
import gmshtranslator.gmshtranslator as gmsh
import arrayfire as af
af.set_backend('cpu')
af.set_device(0)
from dg_maxwell import msh_parser
from dg_maxwell import isoparam
from dg_maxwell import utils
def read_order... | physgrp, nodes):
return eletype == msh_handler.quadrangle_9_node
def save_element (eletag, eletype,
physgrp, node_tags):
temp_nodes = node_tags.copy()
for j, k in zip(np.arange (0,8,2), np.arange(4)):
node_tags[j] = temp... | s[k + 4]
# The node tag starts from 1, but now they will start from 0
# because the nodes array indices represent the node tag.
# Therefore (node_tags - 1) instead of (node_tags)
elements.append(node_tags - 1)
msh_handler.add_nodes_rule (is_node, save_node)
msh_hand... |
auneri/python-urx | urx/urrobot.py | Python | gpl-3.0 | 15,381 | 0.002276 | """
Python library to control an UR robot through its TCP/IP interface
Documentation from universal robots:
http://support.universal-robots.com/URRobot/RemoteAccess
"""
import logging
from urx import urrtmon
from urx import ursecmon
__author__ = "Olivier Roulet-Dubonnet"
__copyright__ = "Copyright 2011-2015, Sintef ... | def set_digital_out(self, output, val):
"""
set digit | al output. val is a bool
"""
if val in (True, 1):
val = "True"
else:
val = "False"
self.send_program('digital_out[%s]=%s' % (output, val))
def get_analog_inputs(self):
"""
get analog input
"""
return self.secmon.get_analog_inpu... |
ryandougherty/mwa-capstone | MWA_Tools/mwapy/config_local.py | Python | gpl-2.0 | 251 | 0.007968 | """ | Empty stub file that will import with no errors if the
PYTHON_PATH is set correctly.
This file is imported by mwaconfig.py, so most MWA python code should
import this. Use it to put global initialisation code in here, if any.
"" | "
pass
|
kaufman-lab/uw-radical | sensor_QC/PS_reference_scraper.py | Python | mit | 8,186 | 0.026753 | #--------------------------------------------------------------------------#
# Prior to r | unning:
# Download chromedriver.exe from https://sites.google.com/a/chromium.org/chromedriver/
# and save in Python27\Scripts. Make sure packages are installed and in the correct
# folder: likely something like "C:\Python27\ArcGIS10.1\Lib\site-packages\"
#----------------------------------------------------------------... | ime
import os
import shutil
from datetime import date
from dateutil.relativedelta import relativedelta
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
#-----------------------------------------------------------------------... |
PythonSanSebastian/ep-tools | tasks.py | Python | mit | 5,341 | 0.001872 | """
Invoke tasks to be run from the command line.
"""
import os.path as op
from invoke import task
from eptools.server_utils import epcon_fetch_p3db
from eptools.gspread_utils import get_api_key_file
from eptools.talks import check_schedule
from eptools.talks import fetch_talks_json as _fetch_talks
fr... | help='If enables will remove the tickets with '
'same owner/email.',
make_option('--raise',
help='If enabled will raise any er | ror that it may find.',
make_option('--ticket-id',
help='Will output the profile of the given ticket only.',
"""
return _fetch_profiles(out_filepath, conf=conf, status=status,
nondups=nondups, raise_=raise_, ticket_id=ticket_id)
@task
def fetch_talks_json... |
CCI-Tools/cate-core | cate/core/ds.py | Python | mit | 23,947 | 0.002088 | # The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# 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 wi... | rvers
from .cdm import get_lon_dim_name, get_lat_dim_name
from .types import PolygonLike, TimeRangeLike, VarNamesLike, ValidationError
from ..util.monitor import ChildMonitor
from ..util.monitor import Monitor
_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S"
__author__ = "Chris Bernat (Telespazio VEGA UK Ltd), ", \
... | an Fomferra (Brockmann Consult GmbH), " \
"Marco Zühlke (Brockmann Consult GmbH)"
URL_REGEX = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain
r'localhost|' # localhost...
r'\d{1,3}\.\d{... |
Irrialite/YouTune | youtune/urls.py | Python | bsd-3-clause | 3,081 | 0.001298 | from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import handler404, handler500
from django.contrib import admin
from youtune import settings
from youtune.account import views as account_views, models as account_models
from youtune.frontend import views as frontend_views
from youtune.a... | logout.html'}, name='logout'),
# Profile, account
url(r'^user/(?P<username>' +
account_models.USERNAME_REGEX +
')/$', frontend_views.UserView.as_view(),
name='profile'),
url(r'^account/$',
account_views.AccountChangeView.as_view(
), name='account'),
url(r'^accoun... | hange'),
url(r'^account/confirmation/$',
account_views.EmailConfirmationSendToken.as_view(),
name='email_confirmation_send_token'),
url(r'^account/confirmation/token/(?:(?P<confirmation_token>\w+)/)?$',
account_views.EmailConfirmationProcessToken.as_view(
), name='email_confirmat... |
ianmtaylor1/pacal | pacal/stats/noncentral_distr.py | Python | gpl-3.0 | 2,437 | 0.016414 | from numpy import sqrt
from pacal.standard_distr import NormalDistr, ChiSquareDistr
from pacal.distr i | mport Distr, SumDistr, DivDistr, InvDistr
from pacal.distr import sqrt as distr_sqrt
class NoncentralTDistr(DivDistr):
def __init__(self, df = 2, mu = | 0):
d1 = NormalDistr(mu, 1)
d2 = distr_sqrt(ChiSquareDistr(df) / df)
super(NoncentralTDistr, self).__init__(d1, d2)
self.df = df
self.mu = mu
def __str__(self):
return "NoncentralTDistr(df={0},mu={1})#{2}".format(self.df, self.mu, self.id())
def getName(self):
... |
andreasots/lrrbot | webserver.py | Python | apache-2.0 | 1,216 | 0.01727 | #!/usr/bin/env python3
from common import utils
utils.init_logging("webserver")
import common.time
import common.url
import www.utils
from common.config import config
from www.server import app
import www.index
import www.help
import www.notifications
import www.login
import www.archive
import www.commands
import ww... | env.globals["csrf_token"]
app.jinja_env.globals["mi | n"] = min
app.jinja_env.globals["max"] = max
app.jinja_env.globals["static_url"] = www.utils.static_url
app.jinja_env.globals["cycler"] = www.utils.CyclerExt
app.register_blueprint(www.api_v2.blueprint, url_prefix="/api/v2")
__all__ = ['app']
if __name__ == '__main__':
app.env = "development"
app.run(debug=True, t... |
cprakashagr/PythonClass | src/numpy-scipy/arrays.py | Python | mit | 1,259 | 0.049245 | import numpy as np
def main():
# Manual way to create Arrays
a = np.array([1,2,3]) # Creates a rank 1 array
print type(a) # Prints "<type 'numpy.ndarray'>"
print a.shape # (3,)
print a[0], a[1]
b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
print b.shape ... | # Prints "[[ 1. 1.]]"
c = np.full((2,2), 7) # Create a constant array
print c # Prints "[[ 7. 7.]
# [ 7. 7.]]"
d = np.eye | (2) # Create a 2x2 identity matrix
print d # Prints "[[ 1. 0.]
# [ 0. 1.]]"
e = np.random.random((2,2)) # Create an array filled with random values
print e # Might print "[[ 0.91940167 0.08143941]
# ... |
erh3cq/hyperspy | hyperspy/models/model2d.py | Python | gpl-3.0 | 9,161 | 0 | # -*- coding: utf-8 -*-
# Copyright 2007-2021 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... | r the full dataset.
See also
--------
Base Model
Model1D
Example
-------
"""
def __init__(self, signal2D, dictionary=None):
super(Model2D, self).__ini | t__()
self.signal = signal2D
self.axes_manager = self.signal.axes_manager
self._plot = None
self._position_widgets = {}
self._adjust_position_all = None
self._plot_components = False
self._suspend_update = False
self._model_line = None
self.xaxis, ... |
gnosek/oktawave-cli | oktawave/commands/ordb.py | Python | gpl-3.0 | 7,032 | 0.001849 | import click
from oktawave.api import CloneType, DICT as OktawaveConstants
from oktawave.commands.context import NamedItemParam, pass_context, OktawaveCliGroup, positional_option
from oktawave.commands.oci import clone_type_param, template_id_param, oci_class_param, subregion_param
from oktawave.commands.util import sh... | ve.exceptions import OktawaveORDBInvalidTemplateError
class ORDBParam(NamedItemParam):
name = 'ORDB instance name/id'
label = 'ORDB'
@classmethod
def list_items(cls, api):
for item in api.O | RDB_List():
yield item['id'], item['name']
def ordb_id_param(*args, **kwargs):
kwargs.setdefault('help', 'ORDB instance name or ID (as returned by ORDB List)')
kwargs.setdefault('type', ORDBParam())
return positional_option(*args, **kwargs)
def db_name_param(*args, **kwargs):
kwargs.setd... |
Cheaterman/kivy | examples/svg/main.py | Python | mit | 1,162 | 0 | import sys
from glob import glob
from os.path import join, dirname
from kivy.uix.scatter import Scatter
from kivy.app import App
from kivy.graphics.svg import Svg
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
Builder.load_string("""
<SvgWidget>:
do_r... | vg = Svg(filename)
self.size = svg.width, svg.height
class SvgApp(App):
def build(self):
self.root = FloatLayout()
filename | s = sys.argv[1:]
if not filenames:
filenames = glob(join(dirname(__file__), '*.svg'))
for filename in filenames:
svg = SvgWidget(filename, size_hint=(None, None))
self.root.add_widget(svg)
svg.scale = 5.
svg.center = Window.center
if __name_... |
ErnieAllen/qpid-dispatch | tests/system_tests_policy_oversize_basic.py | Python | apache-2.0 | 36,740 | 0.001932 | #
# 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... | s should violate maxMessageSize.
# Receiving any is an error.
self.error = "Received a message. Expected to receive no messages."
self.logger.log(self.error)
self._shut_down_test()
else:
self.n_rcvd += 1
self.accept(event.delivery)
... | if event.connection == self.sender_conn:
if event.connection.remote_condition is not None:
if event.connection.remote_condition.name == OVERSIZE_CONDITION_NAME and \
event.connection.remote_condition.description == OVERSIZE_CONDITION_DESC:
self.logger... |
CuonDeveloper/cuon | cuon_server/src/cuon/Reports/report_list_of_residue.py | Python | gpl-3.0 | 2,948 | 0.021724 | # -*- coding: utf-8 -*-
##Copyright (C) [2003-2004] [Jürgen Hamel, D-32584 Löhne]
##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 v... | ++++++++*'
self.dicResults['Info'] = dicExtraData
dicResult = oOrder.getResidue( dicUser )
#print "result by OrderListInvoices: ", dicResult
if dicResult not in ['NONE','ERROR']:
## for i in dicResult:
## for j in i.keys():
## if isinstance(... |
print "len of resultset list of residue", len(dicResult)
self.dicResults['listOfResidue'] = dicResult
#print self.dicResults
print 'ReportPat... |
yutiansut/QUANTAXIS | QUANTAXIS/QIFI/__init__.py | Python | mit | 123 | 0 | from QUANTAXIS.QIFI.QifiAccount impo | rt QIFI_Account
from QUANTAXIS.QIFI.QifiManager import QA_QIFIMANAGER, QA_Q | IFISMANAGER
|
SKIRT/PTS | core/config/launch_simulation.py | Python | agpl-3.0 | 2,437 | 0.004926 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... | al("parallel", "integer_pair", "parallelization scheme (processes, threads)", letter="p")
definition.add_optional("walltime", "duration", | "an estimate for the walltime of the simulation for the specified parallelization scheme")
definition.add_flag("data_parallel_local", "enable data parallelization for local execution", False)
definition.add_flag("data_parallel_remote", "set data parallelization for remote execution (None means automatic)", None)
# Che... |
dopuskh3/confluence-publisher | tests/test_publish.py | Python | mit | 5,417 | 0.001292 | from unittest import TestCase
import random
import os
from conf_publisher.confluence import Page
from conf_publisher.publish import Publisher
from conf_publisher.config import ConfigLoader
from conf_publisher.data_providers.sphinx_fjson_data_provider import SphinxFJsonDataProvider
class FakePagePublisher(object):
... | <a href="{}">Unused</a>
'''.format(page.title, page.unused_title)
self.tests_root = os.path.dirname(o | s.path.abspath(__file__))
self.data_provider = SphinxFJsonDataProvider(root_dir=self.tests_root, base_dir=self.config.base_dir)
self.page_manager = FakePagePublisher([page])
self.attachment_manager = FakeAttachmentPublisher()
def items(self):
return [self.config, self.data_provider,... |
ojengwa/grr | client/poolclient.py | Python | apache-2.0 | 4,657 | 0.012669 | #!/usr/bin/en | v python
# Copyright 2011 Google Inc. All Rights Reserved.
"""This is t | he GRR client for thread pools."""
import pickle
import threading
import time
import logging
from grr.client import client
# pylint: disable=unused-import
# Make sure we load the client plugins
from grr.client import client_plugins
# pylint: enable=unused-import
from grr.client import comms
from grr.client impor... |
TUB-Control/PaPI | papi/plugin/visual/HTMLViewer/HTMLViewer.py | Python | gpl-3.0 | 4,716 | 0.005303 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Technische Universität Berlin,
Fakultät IV - Elektrotechnik und Informatik,
Fachgebiet Regelungssysteme,
Einsteinufer 17, D-10587 Berlin, Germany
This file is part of PaPI.
PaPI is free software: you can redistribute it and/or modify
it under the term... | ameter(self, name, value):
# attetion: value is a string and need to be processed !
# if name == 'irgendeinParameter':
# do that .... with value
| pass
def cb_quit(self):
# do something before plugin will close, e.a. close connections ...
pass
def cb_get_plugin_configuration(self):
#
# Implement a own part of the config
# config is a hash of hass object
# config_parameter_name : {}
# config[c... |
marco-hoyer/cfn-sphere | src/unittest/python/util_tests.py | Python | apache-2.0 | 8,933 | 0.002575 | import tempfile
from git import InvalidGitRepositoryError
try:
from unittest2 import TestCase
from mock import patch, Mock
except ImportError:
from unittest import TestCase
from mock import patch, Mock
import textwrap
from datetime import datetime
from botocore.exceptions import ClientError
from dat... | urlopen_mock.return_value.info.return_value.get.return_value = ""
with self.assertRaises(CfnSphereException):
util.get_cfn_api_ | server_time()
def test_with_boto_retry_retries_method_call_for_throttling_exception(self):
count_func = Mock()
@util.with_boto_retry(max_retries=1, pause_time_multiplier=1)
def my_retried_method(count_func):
count_func()
exception = CfnSphereBotoError(
... |
AMDmi3/repology | repology/repoproc/serialization.py | Python | gpl-3.0 | 2,963 | 0.001012 | # Copyright (C) 2018-2020 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology 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 optio... | n packages:
self.packages.append(package)
self.total_packages += 1
if len(self.packages) >= self.chunk_size:
self._flush()
self._flush()
def get_num_packages(self) -> int:
return self.total_p | ackages
def _stream_deserialize(path: str) -> Iterator[Package]:
try:
with open(path, 'rb') as fd:
unpickler = pickle.Unpickler(fd)
count = unpickler.load()
for _ in range(count):
yield unpickler.load()
except Exception as e:
raise RuntimeEr... |
mosajjal/mitmproxy | examples/simple/modify_body_inject_iframe.py | Python | mit | 829 | 0 | # Usage: mitmdump -s "iframe_injector.py url"
# (this script works best with --anticache)
import sys
from bs4 import BeautifulSoup
class Injector:
def __init__(self, iframe_url):
self.iframe_url = iframe_url
def response(self, flow):
if flow.request.host in self.iframe_url:
return... | iframe = html.new_tag(
"iframe",
src=self.iframe_url,
frameborder=0,
height=0,
width=0)
html.body.insert(0, iframe)
flow.response.content = str(html).encode("utf8")
def start():
if len(sys.argv) != ... | injector.py url"')
return Injector(sys.argv[1])
|
kliput/onezone-gui | bamboos/docker/environment/worker.py | Python | mit | 10,675 | 0.000281 | """Author: Konrad Zemek, Michal Zmuda
Copyright (C) 2015 ACK CYFRONET AGH
This software is released under the MIT license cited in 'LICENSE.txt'
Brings up a set of worker nodes. They can create separate clusters.
Script is parametrised by worker type related configurator.
"""
import copy
import json
import os
from . ... | in
sys_config[app_name]['cm_nodes']]
# Set the cluster domain (needed for nodes to start)
sys_config[app_name][configurator.domain_env_name()] = cluster_domain(
instance, uid)
if 'cluster_worker' not in sys_config: |
sys_config['cluster_worker'] = dict()
sys_config['cluster_worker'][
'persistence_driver_module'] = _db_driver_module(cfg['db_driver'])
if 'vm.args' not in cfg['nodes']['node']:
cfg['nodes']['node']['vm.args'] = {}
vm_args = cfg['nodes']['node']['vm.args']
vm_args['name'] = work... |
UbuntuBudgie/budgie-extras | budgie-workspace-stopwatch/budgie-workspacestopwatch.py | Python | gpl-3.0 | 9,172 | 0.000327 | #! /usr/bin/python3
import os
import gi
gi.require_version('Budgie', '1.0')
gi.require_version('Wnck', '3.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Budgie, GObject, Gtk, Wnck, Gio, GLib
import time
import ast
"""
Budgie Workspace Timer
Author: Jacob Vlijm
Copyright © 2017-2022 Ubuntu Budgie Devel... | ingrid.attach(bottomright, 100, 100, 1, 1)
workspace_header = Gtk.Label()
workspace_header.set_text("Workspace")
self.maingrid.attach(workspace_header, 2, 1, 1, 1)
workspace_header.set_xalign(0)
time_header = Gtk.Label()
time_header.set_text("Time")
self.maingrid.... | self.set_widgetstyle(label, "label")
n = 2
for k in sorted(self.workspace_data.keys()):
if n - 2 == self.workspaces.index(currws):
bullet = Gtk.Label()
bullet.set_text("⮕ ")
self.maingrid.attach(bullet, 1, n, 1, 1)
entry = Gtk.Entry... |
ColinIanKing/autotest | client/base_sysinfo.py | Python | gpl-2.0 | 15,628 | 0.00224 | import os, shutil, re, glob, subprocess, logging, gzip
from autotest.client.shared import log, global_config, software_manager
from autotest.client import utils
GLOBAL_CONFIG = global_config.global_config
_LOG_INSTALLED_PACKAGES = GLOBAL_CONFIG.get_config_value('CLIENT',
... | mount", "hostname",
"uptime",
]
_DEFAULT_COMMANDS_TO_LOG_BEFORE_ITERATION = []
_DEFAULT_COMMANDS_TO_LOG_AFTER_ITERATION = []
_DEFAULT_FILES_TO_LOG_PER_TEST = []
_DEFAULT_FILES_TO_LOG_PER_BOOT = [
"/proc/pci", "/proc/meminfo", "/proc/slabinfo", "/proc/version",
"/proc/cpuinfo", "/proc/modules", "/proc/i... | itions",
]
_DEFAULT_FILES_TO_LOG_BEFORE_ITERATION = [
"/proc/schedstat", "/proc/meminfo", "/proc/slabinfo", "/proc/interrupts"
]
_DEFAULT_FILES_TO_LOG_AFTER_ITERATION = [
"/proc/schedstat", "/proc/meminfo", "/proc/slabinfo", "/proc/interrupts"
]
class loggable(object):
""" Abstract class for r... |
np1/mps-youtube | mps_youtube/commands/generate_playlist.py | Python | gpl-3.0 | 4,048 | 0.001235 | """
Playlist Generation
"""
from os import path
from random import choice
import string
import pafy
from .. import content, g, playlists, screen, util, listview
from ..playlist import Playlist
from . import command, search, album_search
@command(r'mkp\s*(.{1,100})')
def generate_playlist(sourcefile):
"""Gene... | (expanded_sourcefile):
g.message = util.F('mkp empty') % expanded_sourcefile
else:
queries = read_sourcefile(expanded_sourcefile)
| g.message = util.F('mkp parsed') % (len(queries), sourcefile)
if queries:
create_playlist(queries)
g.message = util.F('pl help')
g.content = content.playlists_display()
def read_sourcefile(filename):
"""Read each line as a query from filename"""
with open(filena... |
petterip/exam-archive | test/__main__.py | Python | mit | 958 | 0.004175 | # Run all test suites
| import unittest, os
from database_api_test_archive import *
from database_api_test_course import *
from database_api_test_exam import *
from database_api_test_teacher import *
from database_api_test_user import *
from rest_api_test_user import *
# List of test suites
db_suites = [unittest.TestLoader().loa | dTestsFromTestCase(ArchiveTestCase),
unittest.TestLoader().loadTestsFromTestCase(CourseTestCase),
unittest.TestLoader().loadTestsFromTestCase(ExamTestCase),
unittest.TestLoader().loadTestsFromTestCase(TeacherTestCase),
unittest.TestLoader().loadTestsFromTestCa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.