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 |
|---|---|---|---|---|---|---|---|---|
forkbong/qutebrowser | tests/unit/browser/webkit/test_webkitsettings.py | Python | gpl-3.0 | 1,119 | 0.000894 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2019-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
import pytest
pytest.importorskip('PyQt5.QtWebK... | t webkitsettings
def test_parsed_user_agent(qapp):
webkitsettings._init_user_agent()
parsed = webkitsettings.parsed_user_agent
assert parsed.upstream_browser_key == 'Version'
assert parsed.qt_key == 'Qt'
|
pyfa-org/eos | eos/source/manager.py | Python | lgpl-3.0 | 4,535 | 0.000441 | # ==============================================================================
# Copyright (C) 2011 Diego Duclos
# Copyright (C) 2011-2018 Anton Vorobyov
#
# This file is part of Eos.
#
# Eos is free software: you can redistribute it and/or mo | dify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundat | ion, either version 3 of the License, or
# (at your option) any later version.
#
# Eos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.... |
mhbu50/erpnext | erpnext/accounts/doctype/pos_profile/test_pos_profile.py | Python | gpl-3.0 | 4,539 | 0.022252 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors
# See license.txt
import unittest
import frappe
from erpnext.accounts.doctype.pos_profile.pos_profile import | get_child_nodes
from erpnext.stock.get_item_details import get_pos_profile
test_dependencies = ['Item']
class TestPOSProfile(unittest.TestCase):
def test_pos_profile(self):
ma | ke_pos_profile()
pos_profile = get_pos_profile("_Test Company") or {}
if pos_profile:
doc = frappe.get_doc("POS Profile", pos_profile.get("name"))
doc.append('item_groups', {'item_group': '_Test Item Group'})
doc.append('customer_groups', {'customer_group': '_Test Customer Group'})
doc.save()
items ... |
lauralwatkins/voronoi | voronoi/accretion.py | Python | bsd-2-clause | 4,862 | 0.007199 | #!/usr/bin/env python
# -----------------------------------------------------------------------------
# VORONOI.ACCRETION
# Laura L Watkins [lauralwatkins@gmail.com]
# - converted from IDL code by Michele Cappellari (bin2d_accretion)
# -----------------------------------------------------------------------------
from ... | n] = ind
# centroid of bin
xbar = x[currentb | in]
ybar = y[currentbin]
while True:
# stop if all pixels are binned
unbinned = where(clas == 0)[0]
if unbinned.size == 0: break
# find unbinned pixel closest to centroid of current bin
dist = (x[unbinned]-xba... |
getsentry/freight | freight/api/serializer/app.py | Python | apache-2.0 | 785 | 0.002548 | from freight.models import App, Repository
from .base import Serializer
from .manager import add
@add(App)
class AppSerializer(Serializer):
def serialize(self, item, attrs):
env_map = {}
for env, env_data in list(item.environments.items()):
env_map[env] = {"defaultRef": env_data.get("... | "}
if item.repository_id:
repo = (
Repository.query.filter(Repository.id == item.repository_id).first().url
| )
else:
repo = None
return {
"id": str(item.id),
"name": item.name,
"environments": env_map,
"repository": repo,
}
|
sim642/weechat | doc/docgen.py | Python | gpl-3.0 | 33,442 | 0 | #!/usr/bin/env python3
#
# Copyright (C) 2008-2020 Sébastien Helleu <flashcode@flashtux.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your opti... | 'ja_JP',
'pl_PL',
)
# all commands/options/.. of following plugins will produce a file
# non-listed plugins will be ignored
# value: "c" = plugin may have many commands
# "o" = write config options for plugin
# if plugin is listed without "c", that means plugin has only one command
# /name (where "name" i... | plugin)
# Note: we consider core is a plugin called "weechat"
PLUGIN_LIST = {
'sec': 'o',
'weechat': 'co',
'alias': '',
'buflist': 'co',
'charset': 'o',
'exec': 'o',
'fifo': 'o',
'fset': 'o',
'irc': 'co',
'logger': 'o',
'relay': 'o',
'script': 'o',
'perl': 'o',
'p... |
josephsuh/extra-specs | nova/scheduler/filters/compute_filter.py | Python | apache-2.0 | 5,058 | 0.000989 | # Copyright (c) 2011 OpenStack, 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 requi... | imitations
# under the License.
from nova import log as logging
from nova.scheduler import filters
from nova import utils
from types import *
LOG = logging.getLogger(__name__)
class ComputeFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work wi | th InstanceType records."""
def _satisfies_extra_specs(self, capabilities, instance_type):
"""Check that the capabilities provided by the compute service
satisfy the extra specs associated with the instance type"""
if 'extra_specs' not in instance_type:
return True
# NO... |
deepmind/trfl | trfl/sequence_ops_test.py | Python | apache-2.0 | 17,471 | 0.008071 | # Copyright 2018 The trfl 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 applicable law... | 7.3)
Args:
rewards: a list containing rewards.
pcontinues: a list containing discounts.
state_values: a list containing boostrapped state values.
start: position at which the n-Step return has to be evaluated.
n: number of steps over which rewards are summed before adding respective
boost... | step_backup(rewards, pcontinues, state_values, start, t)
weight = (1 - lambda_) * (lambda_ ** (t - 1))
accumulator += + value * weight
value = get_n_step_backup(rewards, pcontinues, state_values, start, n)
weight = lambda_ ** (n - 1)
accumulator += value * weight
return accumulator
def get_complex_n_s... |
hoffie/ripple | ripple/filters/tag.py | Python | mit | 925 | 0.002162 | from functools import partial
def build_tag_filter(args):
"""
Returns a filter which selects entries with all of the given
tags only.
@param list(str) args, e.g. ["+tag1", "unrelated"]
@return (callable filter, list remaining_args)
"""
remaining_args = []
tags = set()
for arg in ar... | tags
@return generator[Entry]
"""
for | entry in entries:
skip = False
for wanted_tag in tags:
if wanted_tag.lower() not in entry.get_tags():
skip = True
break
if not skip:
yield entry
|
JianmingXia/StudyTest | PythonPro/demo/operator.py | Python | mit | 3,004 | 0.006605 | #coding=utf-8
#运算符
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "1 - 变量 a 在给定的列表中 list 中"
else:
print "1 - 变量 a 不在给定的列表中 list 中"
if ( b not in list ):
print "2 - 变量 b 不在给定的列表中 list 中"
else:
print "2 - 变量 b 在给定的列表中 list 中"
# 修改变量 a 的值
a = 2
if ( a in list ):
print "3 - 变量 a 在给定的列表中 l... | t "1 - 变量 a 和 b 有一个不为 true"
#
# if ( a or b ):
# print "2 - 变量 a 和 b 都为 true,或其中一个变量为 true"
# else:
# print "2 - 变量 a 和 b 都不为 true"
#
# # 修改变量 a 的值
# a = 0
# if ( a and b ):
# print "3 - 变量 a 和 b 都为 true"
# else:
# print "3 - 变量 a 和 b 有一个不为 true"
#
# if ( a or b ):
# print "4 - 变量 a 和 b 都为 true,或其中一个变量为 ... | rue"
# a = 60 # 60 = 0011 1100
# b = 13 # 13 = 0000 1101
# c = 0
#
# c = a & b; # 12 = 0000 1100
# print "1 - c =", c
#
# c = a | b; # 61 = 0011 1101
# print "2 - c =", c
#
# c = a ^ b; # 49 = 0011 0001
# print "3 - c =", c
#
# c = ~a; # -61 = 1100 0011
# print "4 -... |
sebchalmers/DynOPFlow | DynOPFlow.py | Python | gpl-2.0 | 55,808 | 0.031071 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 20:18:08 2012
@author:
Sebastien Gros
Assistant Professor
Department of Signals and Systems
Chalmers University of Technology
SE-412 96 Göteborg, SWEDEN
grosse@chalmers.se
Python/casADi Module:
NMPC for Dynamic Optimal Power Flow and Power Dispatch
Requires the in... | if (X.size > 0):
listFuncInput.append(X)
else:
listFuncInput = [X]
if hasattr(self,'ExtParameters'):
listFuncInput.append(sel | f.ExtParameters)
Func = SXFunction(listFuncInput,[Expr])
Func.init()
return Func
def setConstraints(self, Const, Terminal = False):
if (self._frozen == True):
print "Plant already added to the grid, call ignored"
return
... |
theguardian/LazyLibrarian_Old | lazylibrarian/database.py | Python | gpl-3.0 | 2,650 | 0.005283 | from __future__ import with_statement
import os
import sqlite3
import threading
import time
import lazylibrarian
from lazylibrarian import logger
d | b_lock = threading.Lock()
def dbFilename(filename="lazylibrarian.db"):
return os.path.join(lazylibrarian.DATADIR, filename)
class DBConnection:
def __init__(self, filename="lazylibrarian.db"):
self.filename = filename
self.connection = sqlite3.connect(dbFilename(filename), 20)
self. | connection.row_factory = sqlite3.Row
def action(self, query, args=None):
with db_lock:
if query == None:
return
sqlResult = None
attempt = 0
while attempt < 5:
try:
if args == None:
... |
clemenshage/grslra | experiments/6_grslra/forecasting_lti/forecasting_lti.py | Python | mit | 959 | 0.005214 | from grslra import testdata
from grslra.grslra_online import grslra_online
from grslra.structures import Hankel
from grslra.scaling import Scaling
import numpy as np
# The goal of this experiment is to identify an LTI system and to predict its impulse response in an online manner
PROFILE = 0
if PROFILE:
import cP... | x_0, U, Y = testdata.testdata_lti_outliers(N + N_f, m, k, rho=0.0)
scaling = Scaling(centering=True)
p = 0.1
mu= 1e-4
hankel | = Hankel(m, m + N_f)
params_cg_U = {"t_init": 0.01}
grslra_params = {"VERBOSE": 1, "PRINT": 0}
if PROFILE:
profile = cProfile.Profile()
profile.enable()
x = x_0[:N]
l_grslra, angles, t = grslra_online(x, hankel, k, p, mu, N_f, params=grslra_params, params_cg_U=params_cg_U, scaling=scaling)
if PROFILE:
p... |
avian2/spectrumwars | controller/spectrumwars/testbed/simulation.py | Python | gpl-3.0 | 3,927 | 0.0219 | # Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si
#
# Written by Tomaz Solc, tomaz.solc@ijs.si
#
# This work has been partially funded by the European Community through the
# 7th Framework Programme project CREW (FP7-ICT-2009-258301).
#
# This program is free software: you can redistribute ... | 0
def _get_radio(self):
r = Radio(self.i, self._dispatcher, self.send_delay)
self.radios.append(r)
self.i += 1
return r
def _dispatcher(self, addr, bindata, frequency, bandwidth):
now = self.time()
has_collision = (now - self.channels[frequency]) > self.send_delay
self.channels[frequency] = now
... | goes
# through while the later ones fail. this is different
# than in reality: all should fail. But this would
# be complicated to implement in practice.
for radio in self.radios:
radio._recv(addr, bindata, frequency, bandwidth)
else:
log.debug("packet collision detected on channel %d" % (frequenc... |
michalliu/OpenWrt-Firefly-Libraries | staging_dir/host/lib/scons-2.3.1/SCons/Tool/mingw.py | Python | gpl-2.0 | 6,551 | 0.006259 | """SCons.Tool.gcc
Tool-specific initialization for MinGW (http://www.mingw.org/)
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, ... | SHLIBPREFIX', 'SHLIBSUFFIX',
'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
# Now add file nodes to target list
target.append(env.fs.File(targetStrings))
return (target, source)
shlib_action = SCons.Action.Action(shlib_genera | tor, generator=1)
res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
res_builder = SCons.Builder.Builder(action=res_action, suffix='.o',
source_scanner=SCons.Tool.SourceFileScanner)
SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan)
def generate(env):
m... |
yousseb/meld | meld/undo.py | Python | gpl-2.0 | 9,330 | 0 | # Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2010-2011 Kai Willadsen <kai.willadsen@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 Software Foundation, either version 2 ... | self.actions[self.next_redo:] = []
self.actions.append(action)
self.next_redo += 1
if not could_undo:
self.emit('can-undo', 1)
if could_redo:
self.emit('can-redo', 0)
else:
self.group.add_action(action)
def u... | ises an AssertionError if the sequence is not undoable.
"""
assert self.next_redo > 0
self.busy = True
buf = self.actions[self.next_redo - 1].buffer
if self.checkpointed(buf):
self.emit('checkpointed', buf, False)
could_redo = self.can_redo()
self.next... |
mbox/django | django/db/backends/mysql/base.py | Python | bsd-3-clause | 23,435 | 0.002688 | """
MySQL database backend for Django.
Requires MySQLdb: http://sourceforge.net/proje | cts/mysql-python
"""
from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
try:
import MySQLdb as Database
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
# We want v... | test.
version = Database.version_info
if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and
(len(version) < 5 or version[3] != 'final' or version[4] < 2))):
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Databas... |
zapcoop/vertex | vertex_api/contacts/rules/phonenumber.py | Python | agpl-3.0 | 202 | 0 | import rules
@rules.predicate
def is_phone_number_owner(person, phone_nu | mber):
if phone_number:
return person == phone_number.person
else:
return person.phone_nu | mbers.exists()
|
bsmedberg/socorro | socorro/unittest/external/elasticsearch/unittestbase.py | Python | mpl-2.0 | 1,754 | 0.00171 | # 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/.
import mock
import os
from configman import ConfigurationManager
from socorro.external.elasticsearch import crashstora... | """
def get_config_context(self, es_index=None):
mock_logging = mock.Mock()
storage_config = \
crashstorage.ElasticSearchCrashStorage.get_required_config()
middleware_config = MiddlewareApp.get_required_config()
middleware_config.add_option('logger', default=mock_loggi... | 'resource.elasticsearch.elasticsearch_default_index': 'socorro_integration_test',
'resource.elasticsearch.elasticsearch_index': 'socorro_integration_test',
'resource.elasticsearch.backoff_delays': [1],
'resource.elasticsearch.elasticsearch_timeout': 5,
'resource.postgres... |
vleo/vleo-notebook | testPyQT/testNewWindow.py | Python | gpl-3.0 | 695 | 0.002878 | from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QDialog): # any super class is okay
def __init__(self, parent=None):
super(MyWindow, se | lf).__init__(parent)
self.button = QtGui.QPushButton('Press')
layout = QtGui.QHBoxLayout()
layout.addWidget(self.button)
self.setLayout(layout)
self.button.clicked.connect(self.create_child)
def create_child(self):
# here put the code that creates the new window and s... | ain__':
# QApplication created only here.
app = QtGui.QApplication([])
window = MyWindow()
window.show()
app.exec_()
|
huyphan/pyyawhois | yawhois/scanner/whois_ati_tn.py | Python | mit | 674 | 0.002967 | from .base import ScannerBase
class WhoisAtiTnScanner(ScannerBase):
def __init__(self, *args):
super(WhoisAtiTnScanner, self).__init__(*args)
| self._tokenizer += [
'skip_empty_line',
'scan_available',
'scan_disclaimer',
'scan_keyvalue'
]
def scan_available(self):
if self._input.skip("^Domain (.+) not found"):
self._ast['status:available' | ] = True
return True
def scan_disclaimer(self):
if self._input.match("All rights reserved"):
self._ast['field:disclaimer'] = "\n".join(self._scan_lines_to_array("(.+)\n"))
return True
|
Drvanon/Game | venv/lib/python3.3/site-packages/jinja2/__init__.py | Python | apache-2.0 | 2,270 | 0 | # -*- coding: utf-8 -*-
"""
jinja2
~~~~~~
Jinja2 is a template engine written in pure Python. It provides a
Django inspired non-XML syntax but supports inline expressions and
an optional sandboxed environment.
Nutshell
--------
Here a small example of a Jinja2 template::
{% ... | eptions import TemplateError, UndefinedError, \
TemplateNotFound, TemplatesNotFound, TemplateSyntaxE | rror, \
TemplateAssertionError
# decorators and public utilities
from jinja2.filters import environmentfilter, contextfilter, \
evalcontextfilter
from jinja2.utils import Markup, escape, clear_caches, \
environmentfunction, evalcontextfunction, contextfunction, \
is_undefined
__all__ = [
'Envi... |
Franky333/crazyflie-clients-python | src/cfclient/ui/main.py | Python | gpl-2.0 | 33,136 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 20... | faces)
self.scanner.start()
# Create and start the Input Reader
self._statusbar_label = QLabel("No input-device found, insert one to"
" fly.")
self.statusBar().addWidget(self._statusbar_label)
self.joystickReader = JoystickReader()
... | ice, exclusive=True)
# TODO: Need to reload configs
# ConfigManager().conf_needs_reload.add_callback(self._reload_configs)
self.cf.connection_failed.add_callback(
self.connectionFailedSignal.emit)
self.connectionFailedSignal.connect(self._connection_failed)
self._i... |
darkryder/django | tests/admin_views/tests.py | Python | bsd-3-clause | 282,294 | 0.002807 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import json
import os
import re
import unittest
from django.contrib.admin import AdminSite, ModelAdmin
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.models import ADDITION, DELETION, LogEntry
from... | ontent</p>', date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1
)
cls.p1 = PrePop | ulatedPost.objects.create(title='A Long Title', published=True, slug='a-long-title')
cls.color1 = Color.objects.create(value='Red', warm=True)
cls.color2 = Color.objects.create(value='Orange', warm=True)
cls.color3 = Color.objects.create(value='Blue', warm=False)
cls.color4 = Color.objec... |
x2Ident/x2Ident_test | mitmproxy/test/pathod/test_log.py | Python | gpl-3.0 | 507 | 0.001972 | from pathod import log
from netlib.exceptions import TcpDisconnect
impo | rt six
class DummyIO(six.StringIO):
def start_log(self, *args, **kwargs):
pass
def get_log(self, *args, **kwargs):
return ""
def test_disconnect():
outf = DummyIO()
rw = DummyIO()
l = log.ConnectionLogger(outf, False, True, rw, rw)
try:
with l.ctx()... | lg:
lg("Test")
except TcpDisconnect:
pass
assert "Test" in outf.getvalue()
|
MTgeophysics/mtpy | mtpy/modeling/pek1dclasses.py | Python | gpl-3.0 | 30,903 | 0.000647 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 05 13:55:13 2014
@author: Alison Kirkby
"""
import mtpy.core.edi as mtedi
import os
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as si
import mtpy.utils.exceptions as MTex
import mtpy.utils.calculator as MTcc
import mt... | .keys()):
if hasattr(self, key):
setattr(self, key, input_parameters[key])
# default working directory is epath if it is specified, otherwise
# current directory
if self.working_directory is None:
if self.edipath is not None:
self.working_... | data(self):
"""
create data to write to an input file
"""
# read edi file to edi object
self.edi_object = mtedi.Edi(self.edipath)
# define z
zr = np.real(self.edi_object.Z.z)
# sign of imaginary component needs to be reversed for the pek1d
# inv... |
amchoukir/ycmd | ycmd/completers/objc/hook.py | Python | gpl-3.0 | 957 | 0.007315 | #!/usr/bin/env python
#
# Copyright (C) 2011, 2012 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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
# (... | nse
# along with YouCom | pleteMe. If not, see <http://www.gnu.org/licenses/>.
import ycm_core
from ycmd.completers.cpp.clang_completer import ClangCompleter
def GetCompleter( user_options ):
if ycm_core.HasClangSupport():
return ClangCompleter( user_options )
else:
return None
|
adityacs/ansible | lib/ansible/modules/windows/win_unzip.py | Python | gpl-3.0 | 3,901 | 0.002051 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Phil Schwartz <schwartzmx@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | e unzips a .zip file and recursively decompresses the contained .gz files and removes all unneeded compressed files after completion.
- name: Unzip ApplicationLogs.zip and decompress all GZipped log files
hosts: all
gather_facts: false
tasks:
- name: Recursively decompress GZ files in ApplicationLogs.zip
... | recurse: yes
rm: true
# Install PSCX to use for extracting a gz file
- name: Grab PSCX msi
win_get_url:
url: http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=pscx&DownloadId=923562&FileTime=130585918034470000&Build=20959
dest: C:\pscx.msi
- name: Install PSCX
win_msi:
pat... |
thiagopnobre/knn | K-NN.py | Python | mit | 3,173 | 0.023462 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import shuffle
from copy import deepcopy
"""
Implementa o algoritmo K-NN
"""
def construir_matriz | (arquivo):
"""
Gera uma matriz de números reais, a part | ir de um arquivo, onde cada linha da matriz representa uma linha do arquivo
"""
return [map(float, linha.strip().split(',')) for linha in arquivo.readlines()]
def distancia_euclidiana(lista1, lista2):
"""
Calcula a distancia euclidiana entre a lista 1 e a lista 2
"""
#Intercala os elementos da lista 1 co... |
rgerkin/pyNeuroML | pyneuroml/neuron/__init__.py | Python | lgpl-3.0 | 2,783 | 0.013654 | '''
A package of utilities for exporting NEURON models to NeuroML 2 & for analysing/comparing NEURON models to NeuroML versions
Will use some some utilities from https://github.com/OpenSourceBrain/NEURONShowcase
'''
from pyneuroml.pynml import validate_neuroml1
from pyneuroml.pynml import validate_neuroml2
from py... | "mview.hoc")
h('objref mv')
h('mv = new ModelView()')
h.load_file("%s/mview_neuroml1.hoc"%(os.path.dirname(__file__)))
| h('objref mvnml1')
h('mvnml1 = new ModelViewNeuroML1(mv)')
h.mvnml1.exportNeuroML(nml1_file_name, level)
if validate:
validate_neuroml1(nml1_file_name)
|
thaim/ansible | test/units/modules/remote_management/lxca/test_lxca_nodes.py | Python | mit | 4,734 | 0.00338 | import json
import pytest
from units.compat import mock
from ansible.modules.remote_management.lxca import lxca_nodes
from ansible.module_utils.remote_management.lxca.common import setup_conn
from ansible.module_utils.remote_management.lxca.common import close_conn
@pytest.fixture(scope='module')
@mock.patch("ansibl... | ert 'missing required arguments' in results['msg']
@mock.patch("ansible.module_utils.remote_management.lxca.common.setup_conn", autospec=True)
@mock.patch("ansible.modules.remote_management.lxca.lxca_nodes.execute_module", autospec=True)
@mock.patch("ansible.modules.remote_management.lxca.lxca_nodes.Ansibl... | uired=True),
login_password=dict(required=True, no_log=True),
command_options=dict(default='nodes', choices=['nodes', 'nodes_by_uuid',
'nodes_by_chassis_uuid',
'nodes_status_mana... |
iivic/BoiseStateX | common/djangoapps/student/models.py | Python | agpl-3.0 | 77,328 | 0.002121 | """
Models for User Information (students, staff, etc)
Migration Notes
If you make changes to this model, be sure to create an appropriate migration
file and check it in at the same time as your model changes. To do that,
1. Go to the edx-platform dir
2. ./manage.py lms schemamigration student --auto description_of_... | import ugettext_lazy as _
from django.conf import settings
from django.utils import timez | one
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.db import models, IntegrityError, transaction
from django.db.models import Count
from django.db.models.signals import pre_save, post_s... |
passy/twentiment-api | twentiment_api/api.py | Python | bsd-3-clause | 1,049 | 0 | """
Blueprint i | mplementing the API wrapper.
:author: 2012, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
from flask import Blueprint, request
from .client import Client, ClientError
from .utils import JSONError
api = Blueprint("api", __name__, url_prefix="/v1")
class GuessResponse(object):
def __init__(self, score):
... | lf.score > 0:
return 'positive'
else:
return 'neutral'
def to_json(self):
return {'score': self.score,
'label': self.label}
@api.route('/guess', methods=['GET'])
def guess():
message = request.args['message']
client = Client.from_config()
try:
... |
lento/cortex | test/IECoreRI/DspyTest.py | Python | bsd-3-clause | 4,126 | 0.046049 | ##########################################################################
#
# Copyright (c) 2010-2013, 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:
#
# * Redis... | Y, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
from __future__ import with_statement
import o... | IECoreRI
class DspyTest( IECoreRI.TestCase ) :
def testRenderDirectToImagePrimitive( self ) :
r = IECoreRI.Renderer( "" )
# write one image direct to memory
r.display( "test", "ie", "rgba",
{
"driverType" : IECore.StringData( "ImageDisplayDriver" ),
"handle" : IECore.StringData( "myLovelyS... |
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam | bin/pyFoamPVSnapshot.py | Python | gpl-2.0 | 121 | 0.008264 | #! /usr/bin/env python
from PyFoam.Ap | plications.ChangePython import changePython
changePython("pvpython","PVSnapshot") | |
weylin/CloudBot | cloudbot/util/async_util.py | Python | gpl-3.0 | 2,026 | 0.001481 | """
Wraps various asyncio functions
"""
import asyncio
import sys
from functools import partial
from cloudbot.util.func_utils import call_with_args
def wrap_future(fut, *, loop=None):
"""
Wraps asyncio.async()/asyncio.ensure_future() depending on the python version
:param fut: The awaitable, future, or ... | dsafe(coro, loop)
def create_future(loop=None):
if loop is None:
loop = asyncio.get_event_loop()
if sys.version_info < (3, 5, 2) | :
return asyncio.Future(loop=loop)
return loop.create_future()
|
jumoconnect/openjumo | jumodjango/donation/forms.py | Python | mit | 6,407 | 0.007336 | from django.contrib.localflavor.us.us_states import STATE_CHOICES
from django.core.exceptions import ValidationError
from django import forms
from django.forms.util import ErrorList
from etc.country_field import COUNTRIES
from etc.credit_card_fields import CreditCardField, ExpiryDateField, VerificationValueField
#from ... | "max_value":"The maximum donation amount is $20,000.",})
jumo_amount = forms.DecimalField(label="Optional tip for Jumo", required=True, min_value=0.0)
name_on_card = forms.CharField(label="Name On Card", max_length=60, required=True)
card_number = CreditCardField(label="Credit Card Num... | |
tomming233/blog | app/templatetags/paginate_tags.py | Python | mit | 2,741 | 0.003163 | from django import template
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
register = template.Library()
# 这是定义模板标签要用到的
@register.simple_tag(takes_context=True)
def paginate(context, object_list, page_count):
# context是Context 对象,object_list是你要分页的对象,page_count表示每页的数量
left = 3
rig... | context['article_list'] = object_list
context['pages'] = pages # 页码列表
context['last_page'] = paginator.num_pages
context['first_page'] = 1
# 用于判断是否加入省略号
try:
context['page_first'] = pages[0]
context['page_last'] = pages[-1] + 1
except Inde | xError:
context['page_first'] = 1
context['page_last'] = 2
return ''
#
# def get_left(current_page, left, num_pages):
# """
# 辅助函数,获取当前页码的值得左边两个页码值,要注意一些细节,比如不够两个那么最左取到2
# ,为了方便处理,包含当前页码值,比如当前页码值为5,那么pages = [3,4,5]
# """
# if current_page == 1:
# return []
# elif c... |
deepfire/partus | swank.py | Python | gpl-3.0 | 141,360 | 0.012868 | ##### :: swank.lisp
###
### This file defines the "Swank" TCP server for Emacs to talk to. The
### code in this file is purely portable "Common Lisp". We do require a
### smattering of non-portable functions in order to write the server,
### so we have defined them in `swank-backend.lisp' and implemented
### them separ... |
"Canonical package names to use instead of shortest name/nickname."
setq("_auto_abbreviate_dotted_packages_", t)
"Abbreviate dott | ed package names to their last component if T."
default_server_port = 4005
"The default TCP port for the server (when started manually)."
setq("_swank_debug_p_", t)
"When true, print extra debugging information."
### SLDB customized pprint dispatch table: swank.lisp:95
##
## CLHS 22.1.3.4, and CLHS 22.1.3.6 do not s... |
jawilson/home-assistant | homeassistant/components/smartthings/config_flow.py | Python | apache-2.0 | 9,298 | 0.001291 | """Config flow to configure SmartThings."""
from http import HTTPStatus
import logging
from aiohttp import ClientResponseError
from pysmartthings import APIResponseError, AppOAuth, SmartThings
from pysmartthings.installedapp import format_install_url
import voluptuous as vol
from homeassistant import config_entries
f... | app_id, self.location_id))
return await self.async_step_authorize()
async def async_step_authorize(self, user_input=None):
"""Wait for the user to authorize the app installati | on."""
user_input = {} if user_input is None else user_input
self.installed_app_id = user_input.get(CONF_INSTALLED_APP_ID)
self.refresh_token = user_input.get(CONF_REFRESH_TOKEN)
if self.installed_app_id is None:
# Launch the external setup URL
url = format_instal... |
Johannes-Sahlmann/linearfit | setup.py | Python | lgpl-3.0 | 1,662 | 0.008424 | #!/usr/bin/env python
import os
import sys
import re
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import find_packages
try:
from setuptools impor | t setup
setup
except ImportError:
from distutils.core import setup
setup
linearfitVersion = '0.1.11'
setup(
name="linearfit",
description="python package that implements a general least-squares fit of a linear model using numpy matrix inversion",
version=linearfitVersion,
author="Johannes Sahlma... | license="LGPLv3+",
# long_description="\n"+open("README.rst").read() + "\n\n" + "Changelog\n" + "---------\n\n" + open("HISTORY.rst").read(),
long_description="python package that implements a general least-squares fit of a linear model using numpy matrix inversion",
packages = find_packages(),
... |
terrycain/aioboto3 | aioboto3/resources/factory.py | Python | apache-2.0 | 10,415 | 0.000288 | import logging
from boto3.resources.factory import ResourceFactory
from boto3.resources.model import ResourceModel
from boto3.resources.base import ResourceMeta
from boto3.docs import docstring
from boto3.exceptions import ResourceLoadException
from boto3.resources.factory import build_identifiers
from functools impor... | cached value if possible. If not, then
# it first checks to see if it CAN be loaded (raise if not), then
# calls the load before returning the value.
async def property_loader(self):
if self.meta.data is None:
if hasattr(self, 'load'):
await self.... | oad method'.format(
self.__class__.__name__))
return self.meta.data.get(name)
property_loader.__name__ = str(snake_cased)
property_loader.__doc__ = docstring.AttributeDocstring(
service_name=service_context.service_name,
resource_name=res... |
be-cloud-be/horizon-addons | server/addons/website_membership/controllers/main.py | Python | agpl-3.0 | 9,678 | 0.004546 | # -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website.models.website import unslug
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT
from openerp.tools.translate import _
import time
import werkzeug.urls
... | p_by and memberships
membership_ids = product_obj.search(cr, uid, [('membership', '=', True)], order="website_sequence", context=context)
memberships = product_obj.browse(cr, uid, m | embership_ids, context=context)
# make sure we don't access to lines with unpublished membershipts
line_domain.append(('membership_id', 'in', membership_ids))
limit = self._references_per_page
offset = limit * (page - 1)
count_members = 0
membership_line_ids = []
... |
WimpyAnalytics/django-markitup | tests/urls.py | Python | bsd-3-clause | 177 | 0.00565 | from __future__ import u | nicode_literals
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'^markitup/', include | ('markitup.urls')),
)
|
pytorch/fairseq | fairseq/data/audio/feature_transforms/__init__.py | Python | mit | 2,611 | 0.000383 | import importlib
import os
from abc import ABC, abstractmethod
from typing import Dict, Optional
class AudioFeatureTransform(ABC):
@classmethod
@abstractmethod
def from_config_dict(cls, config: Optional[Dict] = None):
pass
AUDIO_FEATURE_TRANSFORM_REGISTRY = {}
AUDIO_FEATURE_TRANSFORM_CLASS_NAMES... | file.startswith("." | )
and (file.endswith(".py") or os.path.isdir(path))
):
name = file[: file.find(".py")] if file.endswith(".py") else file
importlib.import_module("fairseq.data.audio.feature_transforms." + name)
class CompositeAudioFeatureTransform(AudioFeatureTransform):
@classmethod
def from_confi... |
auntieNeo/asterisk-testsuite | tests/bridge/atxfer_nominal/transfer.py | Python | gpl-2.0 | 4,667 | 0.001714 | #!/usr/bin/env python
'''
Copyright (C) 2013, Digium, Inc.
Matt Jordan <mjordan@digium.com>
This program is free software, distributed under the terms of
the GNU General Public License Version 2.
'''
import sys
import logging
sys.path.append("lib/python")
from version import AsteriskVersion
LOGGER = logging.getLogg... | er(self._handle_ami_connect)
else:
self.test_object.register_feature_end_observer(self._handle_feature_end)
if (Transfer.__singleton_instance == None):
Transfer.__singleton_instance = self
def _handle_ami_connect(self, ami):
''' Handle AMI connect events '''
... | nsfer', self._handle_attended_transfer)
def _handle_feature_start(self, test_object, feature):
''' Callback for the BridgeTestCase feature detected event
Keyword Arguments:
test_object The BridgeTestCase object
feature The specific feature that was executed
'''
LOGG... |
lukas-hetzenecker/home-assistant | homeassistant/components/sonos/helpers.py | Python | apache-2.0 | 1,540 | 0.001948 | """Helper methods for common tasks."""
from __future__ import annotations
from collections.abc import Callable
import functools as ft
import logging
from typing import Any
from soco.exceptions import SoCoException, SoCoUPnPException
from homeassistant.exceptions import HomeAssistantError
UID_PREFIX = "RINCON_"
UID_... | llable:
"""Filter out specified UPnP errors and raise exceptions for service calls."""
def decorator(funct: Callable) -> Callable:
"""Decorate functions."""
@ft.wraps(funct)
def wrapper(*args: Any, **kwargs: Any) -> Any:
| """Wrap for all soco UPnP exception."""
try:
return funct(*args, **kwargs)
except (OSError, SoCoException, SoCoUPnPException) as err:
error_code = getattr(err, "error_code", None)
function = funct.__name__
if errorcodes and er... |
3nids/QGIS | tests/testdata/not_a_processing_script.py | Python | gpl-2.0 | 36 | 0 | # -*- coding: utf | -8 -*-
p | rint('a')
|
citp/BlockSci | test/blockscipy/test_chain.py | Python | gpl-3.0 | 3,478 | 0 | import os
import pytest
import blocksci
from util import correct_timestamp
def test_chain_sanity(chain):
assert 110 < len(chain)
def test_chain(chain, regtest):
assert 0 < chain.address_count(blocksci.address_type.pubkey)
assert 0 < chain.address_count(blocksci.address_type.pubkeyhash)
assert 0 < ch... | tx(chain, json_data, regtest):
height = json_data["address-p2wsh-spend-2-height"]
block_regression(chain[height], regtest)
def block | _regression(block, regtest):
print(block.to_list(), file=regtest)
print(block.base_size, file=regtest)
print(block.bits, file=regtest)
print(block.coinbase_param, file=regtest)
print(block.coinbase_tx, file=regtest)
print(block.fee, file=regtest)
print(block.hash, file=regtest)
print(blo... |
ForumDev/djangocms-flexslider | flexslider/cms_app.py | Python | mit | 317 | 0.012618 | from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
#class FlexSlidersApp(CMSApp):
# name = _("FlexSlider")
# urls = ["f | lexslider.urls"]
# app_name = "flexslid | er"
#
#apphook_pool.register(FlexSlidersApp) # register your app
|
f-prettyland/angr | angr/simos/userland.py | Python | bsd-2-clause | 4,085 | 0.003672 |
import logging
from ..calling_conventions import SYSCALL_CC
from ..errors import AngrUnsupportedSyscallError
from ..procedures import SIM_PROCEDURES as P
from .simos import SimOS
_l = logging.getLogger('angr.simos.userland')
class SimUserland(SimOS):
"""
This is a base class for any SimOS that wants to sup... | ct to provide addresses for syscalls. Syscalls will be emulated as a jump to one of these
addresses, where a SimProcedure from the syscall library provided at construction time will be executed.
"""
def __init__(self, project, syscall_library=None, **kwargs):
super(SimUserland, self).__init__(projec... | oject(self):
super(SimUserland, self).configure_project()
self.kernel_base = self.project.loader.kernel_object.mapped_base
def syscall(self, state, allow_unsupported=True):
"""
Given a state, return the procedure corresponding to the current syscall.
This procedure will have... |
Tinkerforge/brickv | src/brickv/bindings/bricklet_silent_stepper_v2.py | Python | gpl-2.0 | 57,690 | 0.004802 | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2022-01-18. #
# #
# Python Bindings Version 2.1.29 #
# ... | D_PHASE_AB = 3
OVER_TEMPERATURE_NONE = 0
OVER_TEMPERATURE_WARNING = 1
OVER_TEMPERATURE_LIMIT = 2
| STATE_STOP = 1
STATE_ACCELERATION = 2
STATE_RUN = 3
STATE_DEACCELERATION = 4
STATE_DIRECTION_CHANGE_TO_FORWARD = 5
STATE_DIRECTION_CHANGE_TO_BACKWARD = 6
GPIO_ACTION_NONE = 0
GPIO_ACTION_NORMAL_STOP_RISING_EDGE = 1
GPIO_ACTION_NORMAL_STOP_FALLING_EDGE = 2
GPIO_ACTION_FULL_BRAKE_RIS... |
ralphbean/ansible | v2/ansible/errors/__init__.py | Python | gpl-3.0 | 7,154 | 0.004753 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | show_content
if obj and isinstance(obj, AnsibleBaseYAMLObject):
extended_error = self._get_extended_error()
if extended_error:
self.message = 'ERROR! %s\n\n%s' % (message, extended_error)
else:
self.message = 'ERROR! %s' % message
def __str__(sel... | umber):
'''
Returns the line in the file which coresponds to the reported error
location, as well as the line preceding it (if the error did not
occur on the first line), to provide context to the error.
'''
target_line = ''
prev_line = ''
with open(file... |
mvcisback/py-blustl | magnum/test_mpc.py | Python | bsd-3-clause | 231 | 0 | import funcy as fn
from magnum.mpc import echo_en | v_mpc
def test_mpc_smoke():
from magnum.examples.feasible_example import feasible_example as g
results = li | st(fn.take(10, echo_env_mpc(g)))
assert len(results) == 10
|
xbmcmegapack/plugin.video.megapack.dev | resources/lib/menus/home_tvshows_realitytv.py | Python | gpl-3.0 | 1,096 | 0.001828 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@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 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 ... | ou should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Tvshows_RealityTV():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(d... |
ayarshabeer/drf_shop | products/migrations/0001_initial.py | Python | mit | 5,291 | 0.003591 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-02 14:37
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.hstore
from django.db import migrations, models
import django.db.models.deletion
from django.contrib.postgres.operations import HStoreEx... |
('created_on', models.DateTimeField(auto_now_add=True)),
('updated_on', models.DateTimeField(auto_now=True)),
('active', models.BooleanField(default=True)),
('attributes', django.contrib.postgres.fields.hstore.HS | toreField()),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Product')),
],
),
]
|
dsoprea/RandomUtility | python/text_prompts.py | Python | gpl-2.0 | 3,614 | 0.005257 | ###############################################################################
# Copyright (C) 2013 Dustin Oprea #
# License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher #
# #
... | and answer == ''):
i += 1
if i >= 3:
raise PromptAbortException((id_, label_text))
print("\nPlease enter something.\n")
continue
elif is_required is False and is_abort is True:
answe | r = default_value
return (with_nl, answer)
def text_prompts(prompts):
"""Ask for a series of text responses from user. We expect a dictionary
where the keys are the identifiers used in the resultant dictionary, and
the values are tuples of (label_text, is_required, default_value).
""... |
jeremiahyan/odoo | addons/mail/wizard/__init__.py | Python | gpl-3.0 | 393 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright | and licensing details.
from . import base_module_uninstall
from . import base_partner_merge_automatic_wizard
from | . import mail_blacklist_remove
from . import mail_compose_message
from . import mail_resend_cancel
from . import mail_resend_message
from . import mail_template_preview
from . import mail_wizard_invite
|
cherry-wb/qemu-dbaf | scripts/tracetool/__init__.py | Python | gpl-2.0 | 7,431 | 0.0035 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Machinery f | or generating tracing-related intermediate files.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012-2014, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanh... | ol.format
import tracetool.backend
def error_write(*lines):
"""Write a set of error lines."""
sys.stderr.writelines("\n".join(lines) + "\n")
def error(*lines):
"""Write a set of error lines and exit."""
error_write(*lines)
sys.exit(1)
def out(*lines, **kwargs):
"""Write a set of output line... |
jorik041/parallel-ssh | psshlib/askpass_client.py | Python | bsd-3-clause | 3,462 | 0.002889 | #!/usr/bin/env python
# -*- Mode: python -*-
# Copyright (c) 2009, Andrew McNabb
"""Implementation of SSH_ASKPASS to get a password to ssh from pssh.
The password is read from the socket specified by the environment variable
PSSH_ASKPASS_SOCKET. The other end of this socket is pssh.
The ssh man page discusses SSH_... | sys.exit(1)
else:
sys.stderr.write('Er | ror: pssh-askpass called without a prompt.\n')
sys.exit(1)
address = os.getenv('PSSH_ASKPASS_SOCKET')
if not address:
sys.stderr.write(textwrap.fill("pssh error: SSH requested a password."
" Please create SSH keys or use the -A option to provide a"
" password."))... |
h2oai/h2o-3 | h2o-py/tests/testdir_algos/automl/pyunit_automl_regression.py | Python | apache-2.0 | 1,901 | 0.007891 | from __future__ import print_function
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.automl import H2OAutoML
from tests import pyunit_utils as pu
from _automl_utils import import_dataset
def test_default_automl_with_regression_task():
... | eaderboard.nrows))]
for mn in model_names:
m = h2o.get_model(mn)
dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None
print("{}: distribution = {}".format(mn, dist))
except:
h2o.rapids("(setpropert... | test_workaround_for_distribution,
])
|
metiscus/pychess | lib/pychess/Savers/pgn.py | Python | gpl-3.0 | 17,853 | 0.006049 | # -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import re
from datetime import date
from pychess.compat import basestring, StringIO
from pychess.System import conf
from pychess.System.Log import log
from pychess.Utils.Board i... | ial game move, or initial | variation move
mvcount = "%d..." % (ply//2)
elif node.prev.children:
# move after real(not [%foo bar]) comment
need_mvcoun |
h2oai/sparkling-water | py/examples/tests/H2OContextWithoutExplicitStop.py | Python | apache-2.0 | 204 | 0 | from pysparkling import *
from pyspark.sql import SparkSession
# Initiate SparkSession
spark = SparkS | ession.builder.appName("App name").getOrCrea | te()
# Initiate H2OContext
hc = H2OContext.getOrCreate()
|
mbedmicro/pyOCD | scripts/generate_command_help.py | Python | apache-2.0 | 4,524 | 0.005084 | #!/usr/bin/env python3
import textwrap
import pyocd.commands.commands
import pyocd.commands.values
from pyocd.commands.base import (
ALL_COMMANDS,
CommandBase,
ValueBase,
)
ACCESS_DESC = {
'r': "read-only",
"w": "write-only",
"rw": "read-write",
}
GROUP_DOCS = {
'b... | y useful for low-level debugging of debug infrastructure on a new chip.",
'symbols': | "These commands require an ELF to be set.",
}
def gen_command(info):
names = info['names']
usage = info['usage']
help = info['help']
extra_help = info.get('extra_help')
print("""<tr><td>""")
name_docs = []
for name in names:
name_docs.append(f"""<a href="#{names[0]}"><tt>{name}<... |
ZeroPage/zp-library | init.py | Python | bsd-3-clause | 964 | 0.001037 | from datetime import datetime
import webapp2
from models.classes import *
INIT_GROUP_ADMIN = 'admin'
INIT_GROUP_USER = 'user'
INIT_GROUP_PENDING = 'pending'
INIT_GROUP_ANONYMOUS = 'anonymous'
INIT_EXTRA_LAST_INIT = 'last_init'
class MainPage(webapp2.RequestHandler):
def get(self):
Group(
id=... | IN,
book_view=True,
book_edit=True,
book_borrow=True
).put()
Group(
id=INIT_GROUP_PENDING,
book_view=True
).put()
Group(
id=INIT_GROUP_USER,
book_view=True,
book_borrow=True
).put()
... | value=str(datetime.now())
).put()
self.response.write('complete.')
APPLICATION = webapp2.WSGIApplication([
('.*', MainPage)
])
|
jgresula/jagpdf | code/tools/external/python/pygccxml/parser/synopsis_scanner.py | Python | mit | 1,649 | 0.027896 | # Copyright 2004 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import os
import types
import pprint
import | warnings
from Synopsis import AST
from pygccxml import | utils
from pygccxml.declarations import *
class scanner_t( AST.Visitor, object ):
def __init__(self, ast, decl_factory ):
self.logger = utils.loggers.cxx_parser
self.ast = ast
assert isinstance( decl_factory, decl_factory_t )
self.__decl_factory = decl_factory
... |
dgary50/eovsa | cal_calendar.py | Python | gpl-2.0 | 1,777 | 0.010129 | def find_calibrations(year, month):
import calendar
from util import Time
import cal_header as ch
import stateframe
hc = calendar.HTMLCalendar(calendar.SUNDAY)
html_table = hc.formatmonth(year, month)
lines = html_table.split('\n')
lines[2] = lines[ | 2].replace('th class','th width="100" class')
c = calendar.TextCalendar(calendar.SUNDAY)
for i in c.itermonthdays(year,month):
if i != 0:
t = Time(str(year)+'-'+str(month)+'-'+str(i)+' 20:00')
cals = []
for caltype in [8,9,10]:
xml, buf = ch.rea... | append(0)
else:
tout = Time(stateframe.extract(buf,xml['Timestamp']),format='lv')
if (t - tout).value < 1./3:
cals.append(1)
else:
cals.append(0)
for k,line in enumerate(lines[3... |
akretion/l10n-brazil | l10n_br_stock_account/models/stock_rule.py | Python | agpl-3.0 | 2,373 | 0.000422 | # Copyright (C) 2020 Magno Costa - Akretion
# Copyright (C) 2016 Renato Lima - Akretion
# Copyright (C) 2016 Luis Felipe Miléo - KMEE
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import _, api, fields, models
class StockRule(models.Model):
_inherit = 'stock.rule'
@api.model
... | ='l10n_br_fiscal.operation',
string='Fiscal Operation',
domain=lambda self: self._fiscal_operation_domain(),
default=_default_fiscal_operation,
)
invoice_state = fields.Selection(
selection=[
('2binvoiced', _('To Be Invoiced')),
| ('none', _('Not Applicable'))],
string='Invoice Status',
default='none',
copy=False,
help="Invoiced: an invoice already exists\n"
"To Be Invoiced: need to be invoiced\n"
"Not Applicable: no invoice to create",
)
def _get_stock_move_values(self, pro... |
lgarren/spack | var/spack/repos/builtin/packages/fixesproto/package.py | Python | lgpl-2.1 | 1,847 | 0.001083 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Fixesproto(AutotoolsPackage):
"""X Fixe... | to many areas of the protocol to resolve
issues raised by application interaction with core protocol mechanisms
that cannot be adequately worked around on the client side of the wire."""
homepage = "http://cgit.freedesktop.org/xorg/proto/fixesproto"
url = "https://www.x.org/archive/individual/pro... |
woodshop/chainer | tests/functions_tests/test_vae.py | Python | mit | 3,930 | 0 | import unittest
import numpy
import chainer
from chainer import cuda
from chainer.functions import vae
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
if cuda.available:
cuda.init()
class TestGaussianKLDivergence(unittest.Te... | o_gpu(self.mean),
cuda.to_gpu(self.ln_var))
class TestBernoulliNLL(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (3 | ,)).astype(numpy.float32)
self.y = numpy.random.uniform(-1, 1, (3,)).astype(numpy.float32)
# Refer to Appendix C.1 in the original paper
# Auto-Encoding Variational Bayes (http://arxiv.org/abs/1312.6114)
p = 1 / (1 + numpy.exp(-self.y))
self.expect = - (numpy.sum(self.x * numpy.... |
mistercrunch/airflow | tests/conftest.py | Python | apache-2.0 | 28,521 | 0.002314 | # 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... | metavar="BACKEND",
help="only run tests matching the backend: [sqlite,postgres,mysql].",
)
group.addoption(
"--system",
action="append",
metavar="SYSTEMS",
help="only run tests matching the system speci | fied [google.cloud, google.marketing_platform]",
)
group.addoption(
"--include-long-running",
action="store_true",
help="Includes long running tests (marked with long_running marker). They are skipped by default.",
)
group.addoption(
"--include-quarantined",
actio... |
naritta/numpy | numpy/lib/tests/test_format.py | Python | bsd-3-clause | 32,619 | 0.005242 | from __future__ import division, absolute_import, print_function
r''' Test the .npy file format.
Set up:
>>> import sys
>>> from io import BytesIO
>>> from numpy.lib import format
>>>
>>> scalars = [
... np.uint8,
... np.int8,
... np.uint16,
... np.int16,
... ... | cr': '<u4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<u4', 'fortran_ | order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<u4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>u4... |
cdellin/prpy | src/prpy/tsr/tsr.py | Python | bsd-3-clause | 8,656 | 0 | # Copyright (c) 2013, Carnegie Mellon University
# 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 condi... | : self.T0_w.tolist(),
'Tw_e': self.Tw_e.tolist(),
'Bw': self.Bw.tolist(),
'manipi | ndex': int(self.manipindex),
'bodyandlink': str(self.bodyandlink),
}
@staticmethod
def from_dict(x):
""" Construct a TSR from a python dict. """
return TSR(
T0_w=numpy.array(x['T0_w']),
Tw_e=numpy.array(x['Tw_e']),
Bw=numpy.array(x['Bw']),... |
newera912/WeatherTransportationProject | data/trafficData/I90_TravelTime/readData.py | Python | gpl-2.0 | 2,329 | 0.028338 | import os
import csv
import sys
import numpy as np
print sys.maxsize
csv.field_size_limit(922337203)
dataFile=open('TMCsCenterLatLon.txt','r')
edgeFile=open("edgeList.txt","w")
tmcID={}
for i,line in enumerate(dataFile.readlines()):
line=line.strip().split()
tmcID[line[0]]=i
print tmcID
edgeList=[]
for i in... | f+=1
data[i][j]=data[i][f]
elif data[i][j]==0:
f=j-1
while(data[i][f]==0):
if f-1==-288:
break
f-=1
data[i][j]=data[i][f]
... | else:
a=0
count+=1
output.write(str(data[i][j])+" ")
output.write("\n")
if count!=288:
print count
#print d[0]
#print len(tmcList),("".join(list(tmcList)))
|
uwcirg/true_nth_usa_portal | portal/models/locale.py | Python | bsd-3-clause | 817 | 0 | from ..sy | stem_uri import IETF_LANGUAGE_TAG
from .coding import Coding
from .lazy import lazyprop
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for att... | prop
def AmericanEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Au... |
betaY/crawler | you-get-master/src/you_get/extractors/le.py | Python | mit | 5,748 | 0.014266 | #!/usr/bin/env python
__all__ = ['letv_download', 'letvcloud_download', 'letvcloud_download_by_vu']
import json
import random
import xml.etree.ElementTree as ET
import base64, hashlib, urllib, time, re
from ..common import *
#@DEPRECATED
def get_timestamp():
tn = random.random()
url = 'http://api.letv.com/t... | merge=merge)
def letvcloud_download(url, output_dir='.', merge=True, info_only=False):
qs = parse.urlparse(url).query
vu = match1(qs, r'vu=([\w]+)')
uu = match1(qs, r'uu=([\w]+)')
title = "LETV-%s" % vu
letvcloud_download_by_vu(vu, uu, title=title, output_dir=output_dir, merge=merge, info_only=inf... | wnload(url, output_dir=output_dir, merge=merge, info_only=info_only)
else:
html = get_content(url)
vid = match1(url, r'http://www.letv.com/ptv/vplay/(\d+).html') or \
match1(url, r'http://www.le.com/ptv/vplay/(\d+).html') or \
match1(html, r'vid="(\d+)"')
title = matc... |
surhudm/scipy | scipy/special/tests/test_cdflib.py | Python | bsd-3-clause | 11,339 | 0.001146 | """
Test cdflib functions versus mpmath, if available.
The following functions still need tests:
- ncfdtr
- ncfdtri
- ncfdtridfn
- ncfdtridfd
- ncfdtrinc
- nbdtrik
- nbdtrin
- nrdtrimn
- nrdtrisd
- pdtrik
- nctdtr
- nctdtrit
- nctdtridf
- nctdtrinc
"""
from __future__ import division, print_function, absolute_import... | t_atol = None
def idmap(self, *args):
if self.spfunc_first:
res = self.spfunc(*args)
if np.isnan(res):
return np.nan
args = list(args)
args[self.index] = res
with mpmath.workdps(self.dps):
res = self.mpfunc(*tuple(a... | pfunc(*args)
res = mpf2float(res.real)
args = list(args)
args[self.index] = res
res = self.spfunc(*tuple(args))
return res
def get_param_filter(self):
if self.endpt_rtol is None and self.endpt_atol is None:
return None
... |
terkkila/cgml | cgml/layers/convolution_layer.py | Python | apache-2.0 | 2,699 | 0.027418 |
import theano
from theano.tensor.signal.downsample import max_pool_2d
from .base import _dropout_from_layer_input
from .base import _make_images_from_vectors
from .base import _make_convolution_filters
from .base import _make_shared
class ConvolutionLayer(object):
def __init__(self,
rng = None,... | ilter_width = 0,
subsample = None,
ma | xpool = None,
name = 'unnamed'):
self.name = name
self.dropout = dropout
if input.ndim == 2:
input = _make_images_from_vectors(input,size=(n_in[1],n_in[2]))
# If dropout is positive, apply it to the input
if dropout > 0:
self.... |
cxchope/YashiLogin | tests/test_login.py | Python | mit | 712 | 0.010204 | # -*- coding:utf-8 -*-
import test_core
import demjson
import datetime
test_core.title("登录测试")
f = open("testconfig.json", 'r')
lines = f.read()
f.close()
jsonfiledata = demjson.decode(lines)
if jsonfiledata["url"] == "":
test_core.terr("错误: 'testconfig.json' 配置不完全。")
exit()
uurl = jsonfiledata["url"]+"nyalogin... | :"testmail@uuu.moe",
| 'password':"testpassword",
'ua':"test"
}
dataarr = test_core.postarray(uurl,udataarr,True)
jsonfiledata["update"] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
jsonfiledata["token"] = dataarr["token"]
lines = demjson.encode(jsonfiledata)
f = open("testconfig.json", 'w')
f.write(lines)
f.close() |
longyangking/Husky | Husky/GA/Selection.py | Python | lgpl-2.1 | 2,845 | 0.009139 | # Author: Yang Long <longyang_123@yeah.net>
#
# License: LGPL-2.1
import numpy as np
# Selection function will select parents for next generation based on fitness data
def Tournament(fitness,nParents,args):
'''
Choose best individual based on the Tournament (Default)
'''
tournamentsize = 3
if 'to... | pick = np.random.random()
for j in range(popsize):
if pick <= intervals(i):
selected[i] = j
value[i] = 0
intervals = np.cumsum(value)
| if intervals[-1] != 0:
intervals = intervals/intervals[-1]
break
return selected
def Roulette(fitness,nParents,args):
'''
Select parents by simulating a Roulette Wheel
'''
selected = np.zeros(nParents,dtype=int)
popsize = np.size(fitness)
wh... |
meganlkm/dopy | dopy/exceptions.py | Python | mit | 77 | 0.012987 | #!/u | sr/bin/env python
#coding: utf-8
class DoError(RuntimeError):
pas | s
|
mbuesch/moistcontrol | host/pymoistcontrol/commwidgets.py | Python | gpl-2.0 | 2,555 | 0.020352 | #
# Moisture control - Serial communication widgets
#
# Copyright (c) 2013 Michael Buesch <m@bues.ch>
#
# 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 ... | , Boston, MA 02110-1301 USA.
#
from pymoistcontrol.util import *
import os
class SerialOpenDialog(QDialog):
"""Serial | port connection dialog."""
def __init__(self, parent):
"""Class constructor."""
QDialog.__init__(self, parent)
self.setLayout(QGridLayout(self))
self.setWindowTitle("Select serial port")
self.portCombo = QComboBox(self)
if os.name.lower() == "posix":
# Unix operating system
# Add all serial devi... |
avilaton/sqlalchemy-continuum | sqlalchemy_continuum/transaction.py | Python | bsd-3-clause | 5,496 | 0.000182 | from datetime import datetime
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import six
import sqlalchemy as sa
from sqlalchemy.ext.compiler import compiles
from .dialects.postgresql import (
CreateTemporaryTransactionTableSQL,
InsertTemporaryTransacti... | if isinstance(user_cls, six.string_types):
try:
user_cls = registry[user_cls]
except KeyError:
raise ImproperlyConfigured(
'Could not build relationship between Transaction'
... | 'registry. Either configure VersioningManager to '
'use different user class or disable this '
'relationship ' % (user_cls, user_cls)
)
user_id = sa.Column(
sa.inspect(user_cls).pr... |
SSG-DRD-IOT/commercial-iot-security-system | opencv/tutorials/gui/video/faceDetectionRecording/webcam_writes_buff.py | Python | mit | 1,764 | 0.00737 | import cv2
import sys
def genBuffMask(bufferFrames):
'create bitwise mask for buffer length'
buffMask = 1
for i in range(0, BUFF_LEN-1):
buffMask = (buffMask)<<1 | buffMask
return buffMask
BUFF_LEN = 20 # 30 seems to be optimal number of frames for buffer
buffMask = genBuffMask(BUFF_LEN)
pri... | ff == 0)):
break
# Display the resulting frame
cv2.imshow('Vid | eo', frame)
# cv2.imshow('Video', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
out.release()
cap.release()
cv2.destroyAllWindows()
|
tomviner/pytest | src/_pytest/pastebin.py | Python | mit | 3,386 | 0 | """ submit failure or test session information to a pastebin service. """
import tempfile
import pytest
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting")
group._addoption(
"--pastebin",
metavar="mode",
action="store",
dest="pastebin",
default=... | tebinfile.close()
del config._pastebinfile
# undo our patching in the terminal reporter
tr = config.pluginmanager.getplugin("terminalreporter")
del tr._tw.__dict__["write"]
# write summary
tr.write_sep("=", "Sending information to Paste Service")
pastebinu | rl = create_new_paste(sessionlog)
tr.write_line("pastebin session-log: %s\n" % pastebinurl)
def create_new_paste(contents):
"""
Creates a new paste using bpaste.net service.
:contents: paste contents as utf-8 encoded bytes
:returns: url to the pasted contents
"""
import re
from ur... |
mcdermott-scholars/mcdermott | mccalendar/views.py | Python | mit | 4,577 | 0.015949 | import datetime
import time
import calendar
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from rolepermissi... | = McEvent.objects.filter(
start_date__lte=datetime.date(year, month, day),
end_date__gte=datetime.date(year, month, day))
if day == cur | _day and year == cur_year and month == cur_month:
current = True
lst[week].append((day, events, current))
if len(lst[week]) == 7:
lst.append([])
week += 1
context = {
'year': year,
'month': month,
'day': day,
'month_name': month_names[month-1],
'month_days': lst,
}
... |
jasonacox/SentryPi | sentrypi-cpu.py | Python | mit | 941 | 0.001063 | #!/usr/bin/python
#
# Temp Probe - CPU Status - JSON Output
#
# Jason A. Cox, @jasonacox
# https://github.com/jasonacox/SentryPI
import os
import glob
import time
import datetime
def cpu_temp():
result = 0
mypath = "/sys/class/thermal/thermal_zone0/temp"
with open(mypath, 'r') as mytmpfile:
f... | ine
return float(int(result) / 1000.0)
def gpu_temp():
res = os.popen('/opt/vc/bin/vcgencmd measure_temp').readline()
return res.replace("temp=", "")
def main():
# Main program block
now = datetime.datetime.utcnow()
iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")
ftemp = cpu_temp()
cp... | ad = os.getloadavg()[1] # 5 min load avg
print("{ \"datetime\": \"%s\", \"temperature\": %f, \"cpuload\": %f }" %
(iso_time, ftemp, cpuload))
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
|
pcmoritz/ray-1 | release/horovod_tests/workloads/horovod_test.py | Python | apache-2.0 | 4,752 | 0 | import torch
import torch.nn as nn
import os
import numpy as np
import torchvision
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import ray
from ray import tune
from ray.tune.schedulers import create_scheduler
from ray.tune.integration.horovod import (DistributedTrainableCreator,... | == 1999: # print every 2000 mini-batches
print("[%d, %5d] loss: %.3f" % (epoch + 1, i + 1,
running_ | loss / epoch_steps))
with distributed_checkpoint_dir(step=epoch) as checkpoint_dir:
print("this checkpoint dir: ", checkpoint_dir)
path = os.path.join(checkpoint_dir, "checkpoint")
torch.save((net.state_dict(), optimizer.state_dict(), epoch), path)
if __name__ == "__main__... |
Saevon/Recipes | oneshots/screenshot.py | Python | mit | 1,143 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Converts A bunch of mac Screenshots to 24hour format
def to_24(string):
hour, minute, trail = string.split('.')
sec, period = trail.s | plit(' ')
hour = int(hour)
minute = int(minute)
sec = int(sec)
is_pm = period.lower | () == "pm"
if hour == 12:
if not is_pm:
hour += 12
elif is_pm:
hour += 12
return "%s.%s.%s" % (
str(hour).zfill(2),
str(minute).zfill(2),
str(sec).zfill(2),
)
if __name__ == '__main__':
from folder_list import FolderList
root = FolderList(... |
explora26/zephyr | scripts/west_commands/runners/jlink.py | Python | apache-2.0 | 5,887 | 0.000849 | # Copyright (c) 2017 Linaro Limited.
#
# SPDX-License-Identifier: Apache-2.0
'''Runner for debugging with J-Link.'''
import os
import tempfile
import sys
from west import log
from runners.core import ZephyrBinaryRunner, RunnerCaps, \
BuildConfiguration
DEFAULT_JLINK_EXE = 'JLink.exe' if sys.platform == 'win32' ... | [s | elf.elf_name] +
['-ex', 'target remote :{}'.format(self.gdb_port)])
if command == 'debug':
client_cmd += ['-ex', 'monitor halt',
'-ex', 'monitor reset',
'-ex', 'load']
self.print_gdbserver_mes... |
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_chart_axis23.py | Python | bsd-2-clause | 1,661 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [46332160, 47470848]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3... | 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=... |
rupran/librarytrader | scripts/most_calls.py | Python | gpl-3.0 | 1,613 | 0.00186 | #!/usr/bin/env python3
import collections
import os
import sys
from librarytrader.librarystore import LibraryStore
s = LibraryStore()
s.load(sys.argv[1])
n = 20
if len(sys.argv) > 2:
n = int(sys.argv[2])
outgoing_calls = set()
incoming_calls = collections.defaultdict(int)
for l in s.get_library_objects():
... | for source, targets in l.local_calls.items():
for target in targets:
key = '{}:LOCAL_{}'.format(l.fullname, l.local_functions[target][0])
incoming_calls[key] += 1
out_sorted = sorted(outgoing_calls, key=lambda x: x[1])
print('Top {} outgoing calls'.format(n))
for tp in out_sorted[-n... | ])
for tp in in_sorted[-n:]:
print(tp[0], tp[1])
|
notriddle/pulldown-cmark | tools/mk_entities.py | Python | mit | 3,188 | 0.002196 | # Copyright 2015 Google Inc. All rights reserved.
#
# 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, modify, merge, publish, distribute, sublicense, and/or sell
# 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 KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT... |
ncbray/pystream | sandbox/sese/bracket.py | Python | apache-2.0 | 2,128 | 0.029135 | # Copyright 2011 Nicholas Bray
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use t | his file except in compliance with the License.
# You may obtain a copy of the L | icense at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language ... |
wysiwyng/sr14 | mai_sr14/robot.py | Python | gpl-3.0 | 10,128 | 0.012441 | # Copyright (C) 2105 wysiwyng
#
# 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 d... | ouvers.driveToWPAT(2, 1)
manouvers.driveToSlotAT(2, 1)
time.sleep(0.5)
d("driving t | o slot")
#manouvers.driveToSlotMk3(1)
l.releaseToken()
l.tokenHeightAsync()
def runSafe():
token = tokens.pop(0)
d("popping first slot out of se list {0}".format(token))
d("calling runPrepare({0})".format(token))
direction_ = manouvers.begin(token) #muss currentzone setzen; fahrt token aus ... |
amasiero/approach_control | approach_control_navigation/nodes/get_locals.py | Python | gpl-2.0 | 1,989 | 0.024635 | #!/usr/bin/env python
import rospy
import actionlib
from actionlib_msgs.msg import *
from geometry_msgs.msg import PoseStampted
import yaml
import os
impo | rt os.path
class GetLocals:
def __init__(self):
rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback)
print('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n')
def goal_callback(self, data):
self.fname = os.path.expanduser('~') + '/catkin_ws/src/a... | nfig/locals.yaml'
stream = open(self.fname, 'r')
self.data = yaml.load(stream)
self.keys = self.data.keys()
local = raw_input('Please, write the location for this point (if doesnt exist it will be create): \n options: ' + str(self.keys))
if [x for x in self.keys if x == local]:
self.data[local] = [[data.p... |
jiadaizhao/LeetCode | 0401-0500/0434-Number of Segments in a String/0434-Number of Segments in a String.py | Python | mit | 94 | 0 | class Solution:
def | countSegments(self, s: 'str') -> 'int':
return len | (s.split())
|
o-d-i-n/HelloWorld | api/serializers.py | Python | mit | 778 | 0.03856 | from .models import Project,Member,Contact,Technology,Contributor
from rest_framework import serializers
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = ('name', 'link')
class MemberSeri | alizer(serializers.ModelSerializer):
contacts = ContactSerializer(many=True)
class Meta:
model = Member
fields = ('name', 'post', 'img', 'contacts')
class ContributorSerializer(serializers.ModelSerializer):
class Meta:
model=Contributor
fields = ('name','github')
class ProjectSerializer... | del = Project
fields = ('slug','name','type','desc','icon','technologies','long_desc','contributors','meta') |
ttu/cubesensors-iot-azure | src/python_checker/checker.py | Python | apache-2.0 | 1,550 | 0.015484 | # Azure will execute first file.
# sys.path.append is required by Azure Web Jobs. It requires that all packages are provided to it in zip file.
# env\Lib\site-packages is virtual env path in Windows
import sys
sys.path.append("env\Lib\site-packages")
import logging
import logging.config
from datetime import datetime
... |
# Stop charging when nearing 100
if cable == 1 and battery > 96:
logger.debug("Request unplug %s (%s : %s)" % (sensor_id, battery, cable))
IFTTT.sendEvent | (config.ifttt_api_key, sensor_id + config.ifttt_event_off) |
ifduyue/sentry | tests/sentry/models/test_organization.py | Python | bsd-3-clause | 16,452 | 0.001702 | from __future__ import absolute_import
import copy
import mock
from sentry.models import (
ApiKey, AuditLogEntry, AuditLogEntryEvent, Commit, File, OrganizationMember,
OrganizationMemberTeam, OrganizationOption, Project, Release, ReleaseCommit,
ReleaseEnvironment, ReleaseFile, Team, TotpInterface, User,
)... | rganization_id == to_org.id
assert ReleaseEnvironment.objects.get(
id=from_release_environment.id
).release_id == to_release.id
def test_get_default_owner(self):
user = self.create_user('foo@example.com')
org = self.create_organization(owner=user)
assert org.get_... | 2fa = True
assert org.flag_has_changed('early_adopter')
assert org.flag_has_changed('allow_joinleave') is False
assert org.flag_has_changed('require_2fa') is True
def test_has_changed(self):
org = self.create_organization()
org.name = 'Bizzy'
assert org.has_changed(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.