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 |
|---|---|---|---|---|---|---|---|---|
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/psrc/opus_package_info.py | Python | gpl-2.0 | 292 | 0.006849 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from | opus_core.opus_package import OpusPackage
| class package(OpusPackage):
name = 'psrc'
required_opus_packages = ["opus_core", "opus_emme2", "urbansim"]
|
zhenzhai/edx-platform | common/lib/sandbox-packages/hint/hint_class/Week3/Prob2_Part1.py | Python | agpl-3.0 | 1,401 | 0.013562 | # Make sure you name your file with className.py
from hint.hint_class_helper | s.find_matches import find_matches
class Prob2_Part1:
"""
Author: Shen Ting Ang
Date: 10/11/2016
"" | "
def check_attempt(self, params):
self.attempt = params['attempt'] #student's attempt
self.answer = params['answer'] #solution
self.att_tree = params['att_tree'] #attempt tree
self.ans_tree = params['ans_tree'] #solution tree
matches = find_matches(params)
matching_n... |
spencerlyon2/distcan | distcan/scipy_wrap.py | Python | mit | 10,929 | 0 | """
Common distributions with standard parameterizations in Python
@author : Spencer Lyon <spencer.lyon@stern.nyu.edu>
@date : 2014-12-31 15:59:31
"""
from math import sqrt
import numpy as np
__all__ = ["CanDistFromScipy"]
pdf_docstr = r"""
Evaluate the probability density function, which is defined as
.. math::
... | ogcdf_docstr = r"""
Evaluate the log of the cdf, where the cdf is defined as
.. math::
{cdf_tex}
Parameters
----------
x : {arg1_type}
The point(s) at which to evaluate the log of the cdf
Returns
-------
out : {ret1_type}
The log of cdf of the distr | ibution evaluated at x
Notes
-----
For applicable distributions, equivalent to calling `p__dist_name(x,
*args, lower.tail=1, log.p=1)` from R
"""
rvs_docstr = r"""
Draw random samples from the distribution
Parameters
----------
size : tuple
A tuple specifying the dimensions of an array to be filled with
ran... |
ronen25/nautilus-copypath | nautilus-copypath.py | Python | gpl-3.0 | 2,595 | 0.004624 | #----------------------------------------------------------------------------------------
# nautilus-copypath - Quickly copy file paths to the clipboard from Nautilus.
# Copyright (C) Ronen Lapushner 2017-2018.
# Distributed under the GPL-v3+ license. See LICENSE for more information
#----------------------------------... | pathstr = '\n'.join(paths)
elif len(files) == 1:
pathstr = paths[0]
# Set clipboard text
if pathstr is not None:
self.clipboard.set_text(pathstr, -1)
def __copy_dir_path(self, menu, path):
if path is not None:
pathstr = | self.__sanitize_path(path.get_location().get_path())
self.clipboard.set_text(pathstr, -1)
def get_file_items(self, window, files):
# If there are many items to copy, change the label
# to reflect that.
if len(files) > 1:
item_label = 'Copy Paths'
else:
... |
karllessard/tensorflow | tensorflow/lite/testing/op_tests/greater.py | Python | apache-2.0 | 2,735 | 0.001828 | # Copyright 2019 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... | input_dtype"],
name="input2",
shape=parameters["input_shape_pair"][1])
out = tf.greater(input_value1, input_value2)
return [input_value1, input_value2], [out]
def build_inputs(parameters, sess, inputs, | outputs):
input_value1 = create_tensor_data(parameters["input_dtype"],
parameters["input_shape_pair"][0])
input_value2 = create_tensor_data(parameters["input_dtype"],
parameters["input_shape_pair"][1])
return [input_value1, input_v... |
Hearen/OnceServer | pool_management/bn-xend-core/util/path.py | Python | mit | 330 | 0.036364 | SBINDIR="/usr/sbin"
BINDIR="/usr/bin"
LIBEXEC="/usr/lib/xen/bin"
LIBDIR="/usr/lib64"
SHAREDIR="/usr/share"
PRIVA | TE_BINDIR="/usr/lib64/xen/bin"
XENFI | RMWAREDIR="/usr/lib/xen/boot"
XEN_CONFIG_DIR="/etc/xen"
XEN_SCRIPT_DIR="/etc/xen/scripts"
XEN_LOCK_DIR="/var/lock"
XEN_RUN_DIR="/var/run/xen"
XEN_PAGING_DIR="/var/lib/xen/xenpaging"
|
lehmannro/translate | storage/csvl10n.py | Python | gpl-2.0 | 7,279 | 0.001786 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2006 Zuza Software Foundation
#
# This | file is part of translate.
#
# translate 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.
#
# translate is distributed in the hope tha... | 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 translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
... |
ESOedX/edx-platform | openedx/core/djangoapps/credit/api/provider.py | Python | agpl-3.0 | 16,234 | 0.002649 | """
API for initiating and tracking requests for credit from a provider.
"""
from __future__ import absolute_import
import datetime
import logging
import uuid
import pytz
import six
from django.db import transaction
from edx_proctoring.api import get_last_exam_completion_date
from openedx.core.djangoapps.credit.exc... | <ul>
<li>Sample instruction abc</li>
<li>Sample instruction xyz</li>
</ul>",
},
...
]
"""
return CreditProvider.get_credit_providers(providers_list=providers_list)
def get_credit_provider_info(request, provider_id): ... | Retrieve the 'CreditProvider' model data against provided
credit provider.
Args:
provider_id (str): The identifier for the credit provider
Returns: 'CreditProvider' data dictionary
Example Usage:
>>> get_credit_provider_info("hogwarts")
{
"provider_id": "hogwarts"... |
frastlin/PyAudioGame | pyaudiogame/accessible_output2/outputs/say.py | Python | mit | 535 | 0.050467 | import os
from .base import Output
class AppleSay(Output):
"""Speech output supporting the Apple Say subsystem."""
name = 'Apple Say'
def __init__(self, voice = 'Alex', rate = '300'):
self.voice = voice
self.rate = rate
super(AppleSay, self).__init__()
def is_active(sel | f):
return not os.system('which say')
def | speak(self, text, interrupt = 0):
if interrupt:
self.silence()
os.system('say -v %s -r %s "%s" &' % (self.voice, self.rate, text))
def silence(self):
os.system('killall say')
output_class = AppleSay |
samrushing/cys2n | cys2n/__init__.py | Python | bsd-2-clause | 2,452 | 0.01509 | # -*- Mode: Python -*-
import socket
import unittest
__version__ = '0.1.1'
from .cys2n import *
protocol_version_map = {
'SSLv2' : 20,
'SSLv3' : 30,
'TLS10' : 31,
'TLS11' : 32,
'TLS12' : 33,
}
class PROTOCOL:
reverse_map = {}
for name, val in protocol_version_map.items():
setattr (PROT... | onn = Connection (MODE.SERVER)
conn.set_config (self.cfg)
conn.set_fd (sock.fileno())
# XXX verify
new = self.__class__ (self.cfg, sock, conn)
return new, addr
# XXX client mode as yet untested.
def connect (self, addr):
self.sock.connect (addr)
self.conn... | onnection (MODE.CLIENT)
self.conn.set_config (self.cfg)
self.conn.set_fd (self.fd)
def _check_negotiated (self):
if not self.negotiated:
self.negotiate()
def negotiate (self):
if not self.negotiated:
self.conn.negotiate()
self.negotiated = Tr... |
thunderoy/dgplug_training | assignments/assign4.py | Python | mit | 121 | 0.008264 | #!/usr/bin/env python3
import pwd
for p in pwd.getp | wall() | :
if p.pw_shell.endswith('/bin/bash'):
print(p[0])
|
girvan/pili | test/base_real.py | Python | lgpl-3.0 | 501 | 0.003992 | print " Content-Type: text/html; charset=utf-8"
print ""
print """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://yui.yahooapis.com/combo?3.3.0/build/yui/yui-min.js&3.3.0/build/loader/loader-min.js"></script>
</head>
| <body class="yui3-skin-sam yui-skin-sam">
<h1>Test pili.lite in real case</h1>
<div id="testLogger"></div>
<script t | ype='text/javascript'>
%s
</script>
</body>
</html>
""" % open("base_real.js").read()
|
mumuwoyou/vnpy-master | sonnet/python/modules/spatial_transformer.py | Python | mit | 23,304 | 0.006222 | # Copyright 2017 The Sonnet 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 l... | ace generates a reference grid
of feature points at construction time, and warps it via a parametric
transformation model, specified at run time by an input parameter Tensor.
Grid w | arpers must then implement a `create_features` function used to generate
the reference grid to be warped in the forward pass (according to a determined
warping model).
"""
def __init__(self, source_shape, output_shape, num_coeff, name, **kwargs):
"""Constructs a GridWarper module and initializes the source... |
qvazzler/Flexget | flexget/plugins/operate/rerun.py | Python | mit | 643 | 0 | from __future__ import unicode_literals, division, absolute_ | import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('rerun')
class MaxReRuns(object):
"""Force a task to rerun for debugging purposes."""
schema = {'type': ['boolean', 'intege | r']}
def on_task_start(self, task, config):
task.max_reruns = int(config)
def on_task_input(self, task, config):
task.rerun()
@event('plugin.register')
def register_plugin():
plugin.register(MaxReRuns, 'rerun', api_ver=2, debug=True)
|
kianmeng/codekata | rosalind/001_dna_counting_nucleotides/counting_nucleotides.py | Python | gpl-3.0 | 1,370 | 0.00073 | # -*- coding: utf-8 -*-
# author : kian-meng, ang
#
# input : a dna string at most 100 nt (NucleoTides)
# output : 20 12 17 21
#
# $ python counting_nucleotides.py
# input : a dna string at most 100 nt (NucleoTides)
# output : 20 12 17 21
f = open("rosalind_dna.txt", "r")
dna_string = f.read()
# method 1: using co... | tides = ''.join(sorted(set(dna_string.strip())))
for char in nucleotides:
print dna_string.count(char),
print ""
# method 4: using collections
# @see http://codereview.stackexchange.com/a/27784
# @see https://docs.python.org/2/library/collections.html#counter-objects
# @see http://stackoverflow.com/a/17930886
from... | ))
for _, count in nucleotides_count:
print count,
print ""
# method 5: using collections but different approach
counter = Counter()
for char in ''.join(dna_string.strip()):
counter[char] += 1
for _, count in sorted(counter.items()):
print count,
|
icloudrnd/automation_tools | openstack_dashboard/dashboards/tasks/history/panel.py | Python | apache-2.0 | 243 | 0.004115 | from django.utils.translation import ugettext_lazy as _
import horizon
fro | m openstack_dashboard.dashboards.tasks import dashboard
class History(horizon.Panel):
name = _("History")
slug = "history"
dashboard.Tasks.register( | History)
|
gregoriorobles/drPencilcode | app/migrations/0010_file_time.py | Python | agpl-3.0 | 417 | 0 | # -*- coding: utf-8 -*-
from __future__ impor | t unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0009_file_method'),
]
operations = [
migrations.AddField(
model_name='file',
name=' | time',
field=models.TextField(default=0),
preserve_default=False,
),
]
|
Toshakins/wagtail | wagtail/contrib/wagtailroutablepage/models.py | Python | bsd-3-clause | 3,477 | 0.000575 | from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from django.core.urlresolvers import RegexURLResolver
from django.http import Http404
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.url_routing import RouteResult
_creation_counter = 0
def route(pattern... | utes'):
view_func._routablepage_routes = []
# Add new route to view
view_func._routablepage_routes.append((
url(pattern, view_func, name=(name or view_func.__name__)),
_creation_counter,
))
return view_func
return decorator |
class RoutablePageMixin(object):
"""
This class can be mixed in to a Page model, allowing extra routes to be
added to it.
"""
@classmethod
def get_subpage_urls(cls):
routes = []
for attr in dir(cls):
val = getattr(cls, attr, None)
if hasattr(val, '_rout... |
EdDev/vdsm | lib/vdsm/virt/metadata.py | Python | gpl-2.0 | 17,301 | 0 | #
# Copyright 2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... | ace
self._namespace_uri = namespace_uri
self._prefix = None
if namespace is not None: |
ET.register_namespace(namespace, namespace_uri)
self._prefix = '{%s}' % self._namespace_uri
def load(self, elem):
"""
Load the content of the given metadata element `elem`
into a python object, trying to recover the correct types.
To recover the types, this ... |
felipenaselva/repo.felipe | plugin.video.salts/scrapers/xmovies8v2_scraper.py | Python | gpl-2.0 | 7,473 | 0.007895 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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.
T... | om:\s*'([^']+)", html)
if match:
show_id, ep_id, link_id, from_id = match.groups()
data = {'id': show_id, 'episode_id': ep_id, 'link_id': link_id, 'from': from_id}
headers = {'Referer': page_url, 'Accept-Formating': 'application/json, text/javascript', 'Server': 'cloudflare-n... | ttp_get(url, data=data, headers=headers, cache_limit=1)
return html
def _get_episode_url(self, season_url, video):
season_url = urlparse.urljoin(self.base_url, season_url)
html = self._http_get(season_url, cache_limit=.5)
html = self.__get_players(html, season_url)
episo... |
cfelton/myhdl | example/manual/GrayInc.py | Python | lgpl-2.1 | 1,048 | 0.016221 | import myhdl
from myhdl import *
from bin2gray2 import bin2gray
from inc import Inc
def GrayInc(graycnt, enable, clock, reset, width):
bincnt = Signal(modbv(0)[width:])
inc_1 = Inc(bincnt, enable, clock, reset)
bin2gray_1 = bin2gray(B=bincnt, G=graycnt, width=width)
return inc_1, bin2gr... | 1
def main():
width = 8
graycnt = Signal(modbv(0)[width:])
enable = Signal(bool())
clock = Signal(bool())
reset = ResetSignal(0, active=0, async=True)
toVerilog(GrayIncReg, graycnt, enable, clock, | reset, width)
toVHDL(GrayIncReg, graycnt, enable, clock, reset, width)
if __name__ == '__main__':
main()
|
ixc/glamkit-eventtools | eventtools/utils/diff.py | Python | bsd-3-clause | 2,524 | 0.004754 | # -*- coding: utf-8 -*-
# pinched from django-moderation.
# modified to include rather than exclude, fields
import re
import difflib
def get_changes_between_models(model1, model2, include=[]):
from django.db.models import fields
changes = {}
for field_name in include:
field = type(model1)._meta.ge... | urns a human-readable HTML diff."""
a, b = html_to_list(a), html_to_list(b)
diff = get_diff(a, b)
return u"".join(diff)
def html_to_list(html):
pattern = re.compile(r'&.*?;|(?:<[^<]*?>)|'\
'(?:\w[\w-]*[ ]*)|(?:<[^<]*?>)|'\
'(?:\s*[,\.\?]*)', re.UNICO... | diff(instance1, instance2, include=[]):
from django.db.models import fields
changes = get_changes_between_models(instance1, instance2, include)
fields_diff = []
for field_name in include:
field = type(instance1)._meta.get_field(field_name)
field_changes = changes.get(field.ver... |
Adai0808/SummyChou | BlogforSummyChou/manage.py | Python | gpl-2.0 | 259 | 0.003861 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BlogforSummyChou.s | etting | s")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
ecotg/Flash-Card-App | app/views.py | Python | mit | 1,100 | 0.048182 | # views are handlers that respond to requests from web browsers or other clients
# Each view function maps to one or more request URLs
from flask import render_template, flash, redirect
from app import app
from .forms import Deck
#./run.py
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = Deck()
i... | form.validate_on_submit():
return redirect('/index')
return render_template('submit.html',
title='Create Card',
form=form)
@app.route('/')
@app.route('/index')
def index():
# This is displayed on client's web browser
user = {'nickname': 'Enrique Iglesias'} #fake user
decks = | [
{
'title': 'GRE Words',
'cards': [
{
'word': 'combust',
'definition': 'to catch on fire'
},
{
'word': 'phaze',
'definition': 'to be affected'
}
]
},
{
'title': 'Food words',
'cards': [
{
'word': 'amuse bouche',
'definition': 'little serving'
},
{
'word': ... |
rht/zulip | zerver/lib/dev_ldap_directory.py | Python | apache-2.0 | 3,149 | 0.00127 | import glob
import logging
import os
from typing import Any, Dict, List, Optional
from django.conf import settings
from zerver.lib.storage import static_path
# See https://jackstromberg.com/2013/01/useraccountcontrol-attributeflag-values/
# for docs on what these values mean.
LDAP_USER_ACCOUNT_CONTROL_NORMAL = "512"... | }
if mode == "a":
ldap_dir["uid=" + email + ",ou=users,dc=zulip,dc=com"] = dict(
uid=[email],
thumbnailPhoto=[profile_images[i % len(profile_images)]],
userAccountControl=[LDAP_USER_ACCOUNT_CONTROL_NORMAL],
**common_data,
... | =users,dc=zulip,dc=com"] = dict(
uid=[email_username],
jpegPhoto=[profile_images[i % len(profile_images)]],
**common_data,
)
elif mode == "c":
ldap_dir["uid=" + email_username + ",ou=users,dc=zulip,dc=com"] = dict(
uid=[emai... |
ixc/django-fluent-contents | makemessages.py | Python | apache-2.0 | 634 | 0.012618 | #!/usr/bin/env python
import os
import django
fro | m os import path
from django.conf import settings
from django.core.management import call_command
def main():
if not settings.configured:
module_root = path.dirname(path.realpath(__file__))
settings.configure(
DEBUG = False,
INSTALLED_APPS = (
'fluent_conten... | makemessages', locale=('en', 'nl'), verbosity=1)
if __name__ == '__main__':
main()
|
pashango2/sphinx-explorer | sphinx_explorer/property_widget/property_model.py | Python | mit | 24,672 | 0.000851 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
from .value_types import find_value_type, TypeBase
from six import string_types
import re
from qtpy.QtCore import *
from qtpy.QtGui import *
from qtpy.QtWidgets import *
from .default_value_d... | s, **kwargs):
value_item = QStandardItem()
left_item = self.create_category(*args, **kwargs)
parent_item.appendRow([left_item, value_item])
return left_item
def add_property(self, parent_item, key, value=None, default=None, params=None, label_name=None):
parent_item = parent... | default if default is not None else params.get("default")
label_name = label_name or params.get("label") or key
# value type
value_type = params.get("value_type")
if isinstance(value_type, string_types):
value_type = find_value_type(value_type, params)
value_item = ... |
tobi2006/nomosdb | main/tests/test_views.py | Python | gpl-3.0 | 145,259 | 0.000296 | from django.test import TestCase, RequestFactory
from main.models import *
from main.views import *
from bs4 import BeautifulSoup
from .base import *
import datetime
from feedback.models import IndividualFeedback
class StatusCheckTest(TestCase):
"""Testing the decorator test functions"""
def test_user_teache... | performance1.assessment_results.add(assessment_result_1)
link1 = (
'<a href="/export_feedback/' +
mod | ule1.code +
'/' +
str(module1.year) +
'/' +
assessment1.slug +
'/' +
student.student_id +
'/'
)
link1_1 = link1 + 'first/'
link1_2 = link1 + 'resit/'
assessment_result_2 = AssessmentResult.objects.create(... |
kernevil/samba | wintest/test-s3.py | Python | gpl-3.0 | 10,296 | 0.003011 | #!/usr/bin/env python3
'''automated testing of Samba3 against windows'''
import wintest
def set_libpath(t):
t.putenv("LD_LIBRARY_PATH", "${PREFIX}/lib")
def set_krb5_conf(t):
t.run_cmd("mkdir -p ${PREFIX}/etc")
t.write_file("${PREFIX}/etc/krb5.conf",
'''[libdefaults]
dns_lookup_realm... | l = ${DEBUGLEVEL}
realm = ${WIN_REALM}
workgroup = ${WIN_DOMAIN}
security = ADS
bind interfaces only = yes
interfaces = ${INTERFACE}
winbind separator = /
idmap uid = 1000000-2000000
idmap gid = 1000000-2000000
winbind enum users | = yes
winbind enum groups = yes
max protocol = SMB2
map hidden = no
map system = no
ea support = yes
panic action = xterm -e gdb --pid %d
''')
def join_as_member(t, vm):
'''join a windows domain as a member server'''
t.setwinvars(vm)
t.info("Joining ${WI... |
nedaszilinskas/Odoo-CMS-Variant-Pictures | website_sale_variant_pictures/__openerp__.py | Python | mit | 783 | 0 | # -*- coding: utf-8 -*-
# © 20 | 15 Nedas Žilinskas <nedas.zilinskas@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Variant Pictures",
"category": "Website",
"summary": | "Shows picture of the product variant instead of plain color",
"version": "8.0.1.0",
"description": """
Variant Pictures
======================================
Shows picture of the product variant instead of plain color
""",
"author": "Nedas Žilinskas <nedas.zilinskas@gmail.com>",
"website": "h... |
kevinkahn/softconsole | hubs/ha/domains/__oldthermostat.py | Python | apache-2.0 | 3,386 | 0.025399 | from hubs.ha import haremote as ha
from hubs.ha.hasshub import HAnode, RegisterDomain
from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested
from utils import timers
import functools
# noinspection PyTypeChecker
class Thermostat( | HAnode): # deprecated version
def __init__( | self, HAitem, d):
super(Thermostat, self).__init__(HAitem, **d)
self.Hub.RegisterEntity('climate', self.entity_id, self)
self.timerseq = 0
# noinspection PyBroadException
try:
self.temperature = self.attributes['temperature']
self.curtemp = self.attributes['current_temperature']
self.target_low = sel... |
mpuig/faker | faker/providers/company.py | Python | isc | 624 | 0 | # -*- coding: utf-8 -*-
from baseprovider import BaseProvider
from utils import clean
class Company(BaseProvider):
"""Basic definition of a Company"""
def __init__(self, locales):
super(Company, self).__init__(locales)
def new(self):
self.name = self.parse('company.name')
self.su... | fetch('company.suffix')
self.website = "http://www.%s.%s" % (
clean(self.name),
self.fetch('internet.domain_suffix')
)
def __str__(self):
r | eturn "%s %s\n%s" % (
self.name,
self.suffix,
self.website)
|
races1986/SafeLanguage | CEM/tests/test_textlib.py | Python | epl-1.0 | 4,110 | 0.004623 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Unit tests for pywikibot/textlib.py"""
__version__ = '$Id: cadd8620e9dba64e3c2f3082e6f03f4551fd7641 $'
import unittest
from tests.test_pywiki import PyWikiTestCase
import wikipedia as pywikibot
import pywikibot.textlib as textlib
import catlib
class PyWikiTextLibTestCa... | e)
self.assertNotEqual(text, new_text)
def test_replaceLanguageLinks(self):
# This case demonstrates that eol isnt stripped
self.assertFailedRoundtripInterwiki(self.result1)
self.assertRoundtripInterwiki(self.result1 + self.end_of_line, 2)
def test_replaceLanguageLinks1(self):... | esult1
self.assertFailedRoundtripInterwiki(self.iwresult1)
self.assertRoundtripInterwiki(result, 2)
def test_categoryFormat_raw(self):
self.assertEqual(self.catresult1,
textlib.categoryFormat(['[[Category:Cat1]]',
'[[... |
JoostHuizinga/ea-plotting-scripts | configure_plots.py | Python | mit | 25,413 | 0.002873 | import os
import numpy as np
from typing import List, Dict, Union, Optional
import subprocess as sp
import matplotlib
import matplotlib.transforms
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import matplotlib.transforms as tf
import matplotlib.cm as cm
from matplotlib.axes import Axes
from matplotl... | up for the different plots
(both the main plot and the small bar at the bottom).
"""
init_params()
if plot_ids is None:
plot_ids = [0]
plot_configs = []
for plot_id in plot_ids:
plot_configs.append(setup_figure(plot_id, gridspec))
# We assume that the first entry in the... | n" plot,
# so we initialize it with the parameters we read from the global options.
init_subplot(plot_configs[-1], 0, gridspec[0])
# axis = [init_subplot(plot_id, grid_spec[0]) for i, plot_id in enumerate(plot_ids)]
return plot_configs
class ParseColumns:
def __init__(self, columns: List[i... |
joshua-cogliati-inl/raven | tests/framework/unit_tests/utils/testTreeStructure.py | Python | apache-2.0 | 8,503 | 0.029401 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | ent value name ==:',a==b,False)
checkSame('Inequivalent value name !=:',a!=b,True)
## test equivalent, only tags
a = TS.HierarchicalNode('rightTag')
b = TS.HierarchicalNode('rightTag')
checkSame('Equivalency only tag ==:',a==b,True)
checkSame('Equivalency only tag !=:',a!=b,False)
## test equivalent, | only values
a = TS.HierarchicalNode('rightTag',valuesIn={'attrib1':1,'attrib2':'2'})
b = TS.HierarchicalNode('rightTag',valuesIn={'attrib1':1,'attrib2':'2'})
checkSame('Equivalency only values ==:',a==b,True)
checkSame('Equivalency only values !=:',a!=b,False)
## test equivalent, only text
a = TS.HierarchicalNode('ri... |
Panos512/invenio | modules/webjournal/lib/widgets/bfe_webjournal_widget_latestPhoto.py | Python | gpl-2.0 | 4,058 | 0.005914 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## Licens... | invenio.config import CFG_CERN_SITE, CFG_SITE_URL, CFG_SITE_RECORD
def format_element(bfo, collections, max_photos="3", separator="<br/>"):
"""
Display the latest pictures from the given collection(s)
@param | collections: comma-separated list of collection form which photos have to be fetched
@param max_photos: maximum number of photos to display
@param separator: separator between photos
"""
try:
int_max_photos = int(max_photos)
except:
int_max_photos = 0
try:
collections_li... |
KorolevskyMax/TestFrameworkTemplate | pages/base_page.py | Python | mit | 1,954 | 0.002559 | from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from webium import BasePage as WebiumBasePage, Find
class BasePage(WebiumBasePage):
url_path = None
a... | _displayed() == True else 'logged out'
except NoSuchElementException:
return 'logged out'
def wait_for_loading(self, seconds=180):
wait = WebDriverWait(self._driver, seconds)
wait.until | (lambda x: self._driver.execute_script('return jQuery.active == 0') is True)
def replace_bad_elements(self, css_locator):
self._driver.execute_script("$('{}').remove()".format(css_locator))
def is_loader_displayed(self, *args):
return self._driver.find_element_by_xpath(self.loader_xpath).is_di... |
arpruss/plucker | parser/python/InvokePluckerBuildFromJava.py | Python | gpl-2.0 | 1,742 | 0.004592 | #
# This file is only used in the Java (Jython) version
# It serves as an entry point.
#
import sys
import PyPlucker.Spider
from java.lang import Runtime
from java.util import Hashtable
import org.plkr.distiller.API
class InvokePluckerBuildFromJava (org.plkr.distiller.API.Invocation):
def __init__(s... | c InvokePluckerBuildFromJava()"
pass
def create_dict_from_hashtable (self, ht):
dict = {}
e = ht.keys()
while e.hasMoreElements():
key = e.nextElement()
| value = ht.get(key)
dict[str(key)] = str(value)
return dict
def invoke(self, args, os, inputstring, config, callback):
"@sig public int invoke(java.lang.String[] args, java.io.OutputStream os, java.lang.String inputString, java.util.Hashtable config, org.plkr.distiller.API.C... |
nevermoreluo/privateoverseas | overseas/migrations/0014_auto_20160918_0010.py | Python | gpl-3.0 | 1,111 | 0.0027 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-17 16:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('overseas', '0013_auto_20160914_1706'),
]
operations ... | rField(
model_name='networkidentifiers',
name='service',
field= | models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='overseas.Service'),
),
migrations.AddField(
model_name='networkidentifiers',
name='cdn',
field=models.ManyToManyField(blank=True, null=True, to='overseas.CDN'),
),
]
|
thalesians/tsa | src/main/python/thalesians/tsa/simulation.py | Python | apache-2.0 | 4,012 | 0.008724 | import datetime as dt
import numpy as np
import pandas as pd
import thalesians.tsa.checks as checks
import thalesians.tsa.numpyutils as npu
import thalesians.tsa.processes as proc
import thalesians.tsa.randomness as rnd
def xtimes(start, stop=None, step=None):
checks.check_not_none(start)
i... | ates if variates is not None else rnd.multivariate_normals(ndim=process.noise_dim)
self._time = None
self._time_unit = time_unit
| self.__flatten = flatten
def __next__(self):
if self._time is None:
self._time = next(self.__times)
else:
newtime = next(self.__times)
time_delta = newtime - self._time
if isinstance(time_delta, dt.timedelta):
time_del... |
ChrisCuts/fnode | src/ezClasses/ezClasses.py | Python | gpl-2.0 | 755 | 0.025166 | # -*- coding: utf-8 -*-
'''
Created on 05.09.2015
@author: derChris
'''
class ezDict(dict):
def __missing__(self, key):
self.update({key: ezDict()})
return self[key]
def reduce(self):
items = | list(self.items())
for key, value in items:
if isinstance(value, ezDict):
value.reduce()
if not value:
self.pop(key)
return self
if __name__ == '__main__':
x = | ezDict()
x['heinz']['klaus'] = 'wolfgang'
x['heinz']['juergen'] = 'stefan'
x['stefanie']['ursula'] = {}
print(x)
print(x.reduce()) |
ryanvade/nanpy | setup.py | Python | mit | 1,020 | 0.017647 | #!/usr/bin/env python
from setuptools import setup, find_packages
classifiers = [
# Get more strings from
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
"License :: OSI Approved :: MIT License",
" | Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python" | ,
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
]
setup(name="nanpy",
versio... |
tcheneau/linux-zigbee | test-serial/test_recv.py | Python | gpl-2.0 | 2,105 | 0.023278 | #!/usr/bin/env python
# Linux IEEE 802.15.4 userspace tools
#
# Copyright (C) 2008, 2009 Siemens AG
#
# Written-by: Dmitry Eremin-Solenikov
# Written-by: Sergey Lapin
#
# 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... | ck())
except KeyboardInterrupt:
cn.close()
sys.exit(2)
for i in range(1, 12):
print 'Result of set_channel ' + hex(cn.set_channel(i))
time.sleep(1)
m = 0
res = 5
while res != 0 or m > 60:
res = cn.set_state(RX_MODE)
print "Got res %d" %(res)
m = m + 1
time.sleep(1)
if res == 5 or res == 8:
print "... | (cn.close())
sys.exit(2)
#state = 0
#try:
# f.write(cmd_open)
#except IOError:
# print "Error on write"
# sys.exit(2)
#
#resp = get_response(f)
#print "got response %d" % (resp);
#sys.exit(2)
#
#try:
# state = 0
# while 1:
# if state == 0:
# f.write(cmd_open)
# state = 1
# val = f.read(1)
#except KeyboardInterru... |
soerendip42/rdkit | Contrib/mmpa/search_mmp_db.py | Python | bsd-3-clause | 16,511 | 0.012234 | # Copyright (c) 2013, GlaxoSmithKline Research & Development Ltd.
# 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
# ... | GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTE | RRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Created by Jameed Hussain, July 2013
from __future__ import print_f... |
buddly27/champollion | source/champollion/parser/helper.py | Python | apache-2.0 | 5,395 | 0.001297 | # :coding: utf | -8
import re
#: Regular Expression pattern for single line comments
_ONE_LINE_COMMENT_PATTERN = re.compile(r"(\n|^| )//.*?\n")
#: Regular Expression pattern for multi-line comments
_MULTI_LINES_COMMENT_PATTERN = re.compile(r"/\*.*?\*/", re.DOTALL)
#: Regular Expression pattern for nested element symbols
_NESTED_EL... | ent, filter_multiline_comment=True, keep_content_size=False
):
"""Return *content* without the comments.
If *filter_multiline_comment* is set to False, only the one line comment
will be filtered out.
If *keep_content_size* is set to True, the size of the content is preserved.
.. note::
T... |
Hybrid-Cloud/cinder | cinder/tests/unit/volume/drivers/test_quobyte.py | Python | apache-2.0 | 38,830 | 0.000052 | # Copyright (c) 2014 Quobyte Inc.
# Copyright (c) 2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses... | lume.drivers.quobyte.QuobyteDriver'
'.read_proc_mount') as mock_open, \
mock.patch('cinder.volume.drivers.quobyte.LOG') as mock_LOG:
# Content of /proc/mount (empty).
mock_open.return_value = six.StringIO()
mock_execute.side_effect = [None, ... | cutionError(
stderr='is busy or already mounted')]
self._driver._mount_quobyte(self.TEST_QUOBYTE_VOLUME,
self.TEST_MNT_POINT,
ensure=True)
mkdir_call = mock.call('mkdir', '-p', self.TEST_MNT_POINT)
... |
lgmerek/ScalaProjectGeneratorFacade | scalaProjectGeneratorFacade.py | Python | mit | 6,824 | 0.002638 | import sublime
import sublime_plugin
import re
import subprocess
from array import *
from .giterCommandThread import CommandThread
from .commandBuilders import buildCommand
from .jsonDecoderBuilder import JsonDecoderBuilder
from .sbtBuildFileEditor import SbtBuildFileEditor
from .logger import LoggerFacade
from .utils ... | =0, dir=1):
def animate(i, dir):
before = i % 8
after = | (7) - before
if not after:
dir = -1
if not before:
dir = 1
i += 1
self.view.set_status(
key, message + ' [%s=%s]' % (' ' * before, ' ' * after))
return (i, dir)
a = animate(i, dir)
sublime.set_ti... |
astrorigin/pyswisseph | tests/test_swe_lun_eclipse.py | Python | gpl-2.0 | 2,097 | 0.005246 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import swisseph as swe
import unittest
class TestSweLunEclipse(unittest.TestCase):
@classmethod
def setUpClass(cls):
swe.set_ephe_path()
def test_01(self):
jd = 2454466.5
flags = swe.FLG_SWIEPH
geopos = (12.1, 49.0, 330)
... | t1 = (1.1061093373639495, 2.145134309769692, 0.0, 0.0,
73.8203145568749, 26.299290272560974, 26.330700027276947,
0.3801625589840114, 1.1061093373639495, 133.0, 26.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
| for i in range(20):
self.assertAlmostEqual(attr[i], t1[i])
if __name__ == '__main__':
unittest.main()
# vi: sw=4 ts=4 et
|
sander76/home-assistant | tests/components/mqtt/test_common.py | Python | apache-2.0 | 41,174 | 0.00085 | """Common test objects."""
import copy
from datetime import datetime
import json
from unittest.mock import ANY, patch
from homeassistant.components import mqtt
from homeassistant.components.mqtt import debug_info
from homeassistant.components.mqtt.const import MQTT_DISCONNECTED
from homeassistant.components.mqtt.mixin... | LE
mqtt_mock.connected = False
async_dispatcher_send(hass, MQTT_DISCONNECTED)
await hass.async_block_till_done()
state = hass.states.get(f"{domain}.test")
assert state.state == STATE_UNAVAILABLE
async def help_test_availability_without_topic(hass, mqtt_mock, domain, config):
"""Te | st availability without defined availability topic."""
assert "availability_topic" not in config[domain]
assert await async_setup_component(hass, domain, config)
await hass.async_block_till_done()
state = hass.states.get(f"{domain}.test")
assert state.state != STATE_UNAVAILABLE
async def help_tes... |
wangtuanjie/airflow | airflow/executors/sequential_executor.py | Python | apache-2.0 | 1,230 | 0 | from builtins import str
import logging
import subprocess
from airflow.executors.base_executor import BaseExecutor
from airflow.utils import State
class SequentialExecutor(BaseExecutor):
"""
This executor will only run one task instance at a time, can be used
for debugging. It is also the only executor t... | f).__init__()
self.commands_to_run = []
def execute_async(self, key, command, queue=None):
self.commands_to_run.append((key, command,))
def sync(self):
for key, command in self.comma | nds_to_run:
logging.info("command" + str(command))
try:
sp = subprocess.Popen(command, shell=True)
sp.wait()
except Exception as e:
self.change_state(key, State.FAILED)
raise e
self.change_state(key, State.SU... |
seanli9jan/tensorflow | tensorflow/contrib/rnn/python/ops/lstm_ops.py | Python | apache-2.0 | 25,114 | 0.005017 | # Copyright 2016 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... | ole=use_peephole,
name=name)
# pylint: enable=protected-access
def _block_lstm(seq_len_max,
x,
w,
b,
cs_prev=None,
h_prev=None,
wci=None,
wcf=None,
wco=None,
forget_b... | use_peephole=None,
name=None):
r"""TODO(williamchan): add doc.
Args:
seq_len_max: A `Tensor` of type `int64`.
x: A list of at least 1 `Tensor` objects of the same type.
w: A `Tensor`. Must have the same type as `x`.
b: A `Tensor`. Must have the same type as `x`.
cs... |
nandub/yammer | lib/TicketExceptionHandler.py | Python | gpl-2.0 | 9,659 | 0.013562 | # Copyright 2002, 2004 John T. Reese.
# email: jtr at ofb.net
#
# This file is part of Yammer.
#
# Yammer 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... | t WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI | TNESS 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 Yammer; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from WebKit.ExceptionHandle... |
ntt-sic/taskflow | taskflow/flow.py | Python | apache-2.0 | 2,637 | 0 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | a flow is just a 'structuring' concept this is typically a behavior that
should not be worried about (as it is not visible to the user), but it is
worth mentioning here.
Flows are expected to provide the following methods/properties:
- add
- __len__
- requires
- provides
"""
def _... | (human readable)"""
return self._name
@abc.abstractmethod
def __len__(self):
"""Returns how many items are in this flow."""
def __str__(self):
lines = ["%s: %s" % (reflection.get_class_name(self), self.name)]
lines.append("%s" % (len(self)))
return "; ".join(lines)... |
tommai78101/IRCBot | UserInput.py | Python | mit | 2,759 | 0.029358 | import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8")
class UserInput(threading.Thread):
isRunning = Fals | e
parent = None
def __init__(self, bot):
super().__init__()
self.parent = bot
self.setDaemon(True)
self.isRunning = False
self.start()
def createMessage(self, message):
temp = ""
for i in range(len(message)):
if (i != len(message) - 1):
temp | += message[i] + " "
else:
temp += message[i]
return temp
def run(self):
self.isRunning = True
while (self.isRunning):
try:
message = input()
message = message.split(" ")
if (message[0] != ""):
if (message[0] == "/r" or message[0] == "/reload"):
self.parent.reloadAll()
elif... |
jawilson/home-assistant | homeassistant/helpers/selector.py | Python | apache-2.0 | 5,138 | 0.000779 | """Selectors for Home Assistant."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any, cast
import voluptuous as vol
from homeassistant.const import CONF_MODE, CONF_UNIT_OF_MEASUREMENT
from homeassistant.util import decorator
SELECTORS = decorator.Registry()
def valida... | of a time value."""
CONFIG_SCHEMA = vol.Schema({})
@SELECTORS.register("target")
class TargetSelector(Selector):
"""Selector of a target value (area ID, device ID, entity ID etc).
Value should follow cv.ENTITY_SERVICE_FIELDS format.
"""
CONFIG_SCHEMA = vol.Schema(
{
vol.Opti... | vol.Optional("device_class"): str,
vol.Optional("integration"): str,
}
),
vol.Optional("device"): vol.Schema(
{
vol.Optional("integration"): str,
vol.Optional("manufacturer"): str,
... |
MSA-Argentina/relojito_project | relojito/app/tasks.py | Python | mit | 6,517 | 0.001536 | # -*- coding: utf-8 -*-
from datetime import date, timedelta
from subprocess import check_output
from celery import task
from django.template.loader import render_to_string
from django.db.models import Sum
from django.conf import settings
from django.contrib.auth.models import User
from django.core.mail import send_ma... | total_hours = tx['total_hours__sum']
subject = _(u"Feliz año nuevo de parte de Relojito")
body = _(u"""Hola %(username)s, Relojito te cuenta que hasta ahora completaste %(total_tareas)s tareas,
para un total de %(total_proyectos)s proyectos. En total, cargaste %(total_horas)s ho... | 'username': user.first_name,
'total_proyectos': len(projects),
'total_horas': total_hours
... |
thijsdezoete/BrBaFinals | poolgame/poolgame/urls.py | Python | gpl-2.0 | 816 | 0.003676 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'brbappl.views.index', name='index'),
url(r'^done$', 'brbappl.views.done', name='done'),
url(r... | ', 'brbappl.views.participate', name='participate'),
url(r'^admin', include(admin.site.urls)),
url(r'^(?P<contestant>\w+)$', 'brbappl.views.questionnaire', name='questions'),
# url(r'^poolgame/', include('poolgame.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# ur... | ls)),
)
|
pyta-uoft/pyta | examples/ending_locations/del_name.py | Python | gpl-3.0 | 6 | 0 | del | x
| |
jeremiedecock/snippets | python/pyqt/pyqt5/widget_QTableView_edit_print_signal_when_data_changed.py | Python | mit | 2,784 | 0.002514 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView
class MyData:
def __init__(self):
self._num_rows = 3
self._nu... | data = MyData()
table_view = QTableView()
my_model = MyModel(data)
my_model.dataChanged.connect(changedCallback)
my_model.rowsInserted.connect(changedCallback)
my_model.rowsRemoved.connect(changedCallback)
t | able_view.setModel(my_model)
table_view.show()
# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
exit_code = app.exec_()
# The sys.exit() method ensur... |
ayepezv/GAD_ERP | openerp/report/render/rml2pdf/utils.py | Python | gpl-3.0 | 6,163 | 0.008924 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import copy
import locale
import logging
import re
import reportlab
import openerp.tools as tools
from openerp.tools.safe_eval import safe_eval
from openerp.tools.misc import ustr
_logger = logging.getLogger(__name__)... | _logger.info('rml_except: "%s"', n.get('rml_except',''), exc_info=True)
continue
if n.get('rml_tag'):
try:
(tag,attr) = safe_eval(n.get('rml_tag'),{}, self.localcontext)
| n2 = copy.deepcopy(n)
n2.tag = tag
n2.attrib.update(attr)
yield n2
except GeneratorExit:
yield n
except Exception, e:
_logger.info(... |
shwetams/arm-samples-py | arm_basic_samples/arm_settings/migrations/0002_authsettings_user_id.py | Python | mit | 600 | 0.001667 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende | ncy(settings.AUTH_USER_MODEL),
('arm_settings', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='authsettings',
| name='user_id',
field=models.ForeignKey(related_name='user_id', default=1, to=settings.AUTH_USER_MODEL, unique=True),
preserve_default=False,
),
]
|
daaugusto/ppi | script/domination-many.py | Python | gpl-3.0 | 2,043 | 0.026921 | #!/usr/bin/env python
import sys
import argparse
def | less(a, b):
return a < b
def greater(a, b):
return a > | b
better = less
def dominated(x, y):
if len(x) != len(y):
print "Error: size mismatch!"
return None
dominated = False
for i,j in zip(x,y):
if better(i, j):
return False
if better(j, i):
dominated = True
return dominated
def dominates(x, y):
return dominated(y... |
chrisantonellis/pymongo_basemodel | test/test_model.py | Python | mit | 49,483 | 0.000364 |
import sys; sys.path.append("../") # noqa
import unittest
import copy
import pymongo
import datetime
import bson
from baemo.connection import Connections
from baemo.delimited import DelimitedDict
from baemo.references import References
from baemo.projection import Projection
from baemo.entity import Entity
from ba... | e,
"find_projection": {
"k1": 0
}
})
original = TestModel()
original.attributes({"k1 | ": "v", "k2": "v", "k3": "v"})
original_id = original.save().attributes[TestModel.id_attribute]
m = TestModel()
m.target({original.id_attribute: original_id})
m.find(projection={"k3": 0}, default=True)
self.assertEqual(m.attributes.get(), {
original.id_attribute: ori... |
eunchong/build | scripts/master/master_config.py | Python | bsd-3-clause | 7,620 | 0.005906 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import uuid
from buildbot.changes.filter import ChangeFilter
from buildbot.scheduler import Dependent
from buildbot.scheduler import Nightly
from buildb... | 'hour': hour}
def Periodic(self, name, periodicBuildTimer):
"""Helper method for the Periodic scheduler."""
if name in | self._schedulers:
raise ValueError('Scheduler %s already exists' % name)
self._schedulers[name] = {'type': 'Periodic',
'builders': [],
'periodicBuildTimer': periodicBuildTimer}
def Dependent(self, name, parent):
if name in self._schedulers:
... |
Jonekee/chromium.src | tools/telemetry/telemetry/core/command_line.py | Python | bsd-3-clause | 3,100 | 0.010645 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import optparse
from telemetry.core import camel_case
class ArgumentHandlerMixIn(object):
"""A structured way to handle command-line arg... |
class OptparseCommand(Command):
usage = | ''
@classmethod
def CreateParser(cls):
return optparse.OptionParser('%%prog %s %s' % (cls.Name(), cls.usage),
description=cls.Description())
def Run(self, args):
raise NotImplementedError()
@classmethod
def main(cls, args=None):
"""Main method to run this comman... |
rsk-mind/rsk-mind-framework | tests/dataset/test_dataset_pandas.py | Python | mit | 2,486 | 0.000402 | import os
from nose.tools import assert_equals, assert_items_equal
from rsk_mind.dataset import PandasDataset
from rsk_mind.transformer import *
import pandas as pd
class CustomTransformer(Transformer):
class Feats():
a1 = Feat()
a2 = Feat()
f1 = CompositeFeat(['a1', 'a2'])
def ge... | 4', 'target']
_rows = [[-0.0, 'fa', -0.0, 0.0, 0, 0, 1], [-1.0, 'fa', -1.0, 2.0, 0, 1, 0], [-1.0, 'fa', -0.0, 1.0, 0, 1, 0]]
_dataset.applyTransformations()
assert_equals(_dataset.transformed_header, _header)
assert_items_equal(_dataset.transformed_rows, _rows)
assert_equals(_... | est_applyTransformations_Without_Transformer(self):
_dataset = PandasDataset(self.reader)
_expected_header = ['a1', 'a2', 'a3', 'a4', 'target']
_expected_rows = [[0, 0, 0, 0, 1], [1, 1, 0, 1, 0], [1, 0, 0, 1, 0]]
_dataset.applyTransformations()
assert_equals(_dataset.transform... |
foxdog-studios/pyddp | tests/messages/client/test_method_message_parser.py | Python | apache-2.0 | 1,258 | 0.000795 | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | _ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from ddp.messages.client import MethodMessage
from ddp.messages.client import MethodMessageParser
class MethodMessageParserTestCase(unittest.TestCase):
def setUp(self):
self.parser = MethodMess... | params = [True, 1.0]
message = self.parser.parse({'msg': 'method', 'id': id,
'method': method, 'params': params})
self.assertEqual(message, MethodMessage(id, method, params))
|
GPflow/GPflow | gpflow/models/vgp.py | Python | apache-2.0 | 14,665 | 0.002524 | # Copyright 2016-2020 The GPflow Contributors. 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 appli... | putation. This is useful for avoiding extraneous
computations when you only want to call the posterior's
`fused_predict_f` method.
"""
X_data, _Y_data = self.data
return posteriors.VGPPosterior(
self.kernel,
| X_data,
self.q_mu,
self.q_sqrt,
mean_function=self.mean_function,
precompute_cache=precompute_cache,
)
def predict_f(
self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False
) -> MeanAndVariance:
"""
For backwa... |
bveina/TempSensorNode | main.py | Python | mit | 26 | 0 | from brv1 import *
main() | ||
chembl/the-S3-amongos | the-S3-amongos.py | Python | apache-2.0 | 21,343 | 0.014431 | #!/usr/bin/env python
# Copyright 2015 The ChEMBL group.
# Author: Nathan Dedman <ndedman@ebi.ac.uk>
# 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/LICE... |
self.finish('<?xml version="1.0" encoding="UTF-8"?>' +
''.join(parts))
def _render_parts(self, value, parts=[]):
if isinstance(value, (unicode, bytes)):
parts.append(escape.xhtml_escape(value))
elif isinstance(value, int) or isinstance(value, lo... | f isinstance(value, dict):
for name, subvalue in value.iteritems():
if not isinstance(subvalue, list):
subvalue = [subvalue]
for subsubvalue in subvalue:
parts.append('<' + escape.utf8(name) + '>')
self._render_parts... |
tomvansteijn/openradar | openradar/periods.py | Python | gpl-3.0 | 1,780 | 0 | # -*- coding: utf-8 -*-
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst.
"""
Period looper for atomic scripts.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import datetime
import math
import re
from r... | now = self.start
while | now <= self.stop:
yield now
now += self.step
def __repr__(self):
return '{} - {}'.format(self.start, self.stop)
|
mikalstill/nova | nova/tests/unit/objects/test_instance_action.py | Python | apache-2.0 | 16,824 | 0.000178 | # Copyright 2013 IBM Corp.
#
# 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... | 'start_time': self.context.timestamp,
'updated_at': self.context.timestamp,
}
expected_packed_action_finish = {
'request_id': self.context.request_id,
'instance_uuid': uuids.instance,
'finish_time': NOW,
'updated_at': NOW,
}
... | self.context, uuids.instance, 'fake-action')
action.finish()
mock_start.assert_called_once_with(self.context,
expected_packed_action_start)
mock_finish.assert_called_once_with(self.context,
expected_packed_acti... |
jpablobr/emacs.d | vendor/misc/emacs-skype/build/Skype4Py/Skype4Py/api/posix_x11.py | Python | gpl-3.0 | 17,077 | 0.001581 | """
Low level *Skype for Linux* interface implemented using *XWindows messaging*.
Uses direct *Xlib* calls through *ctypes* module.
This module handles the options that you can pass to `Skype.__init__`
for Linux machines when the transport is set to *X11*.
No further options are currently supported.
Warning PyGTK fr... | of your script, before
PyGTK is even imported.
.. python::
from Skype4Py.api.posix_x11 import threads_init
threads_init()
This function enables multithreading support in Xlib and GDK. If not done
here, this is enabled for Xlib library when the `Skype` object is instantiated.
If your script imports the PyGTK ... |
by calling the ``threads_init`` function.
"""
__docformat__ = 'restructuredtext en'
import sys
import threading
import os
from ctypes import *
from ctypes.util import find_library
import time
import logging
from Skype4Py.api import Command, SkypeAPIBase, \
timeout2float, finalize_opts
from... |
Molecular-Image-Recognition/Molecular-Image-Recognition | code/rmgpy/data/kinetics/common.py | Python | mit | 16,818 | 0.003687 | #!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
#
# RMG - Reaction Mechanism Generator
#
# Copyright (c) 2002-2017 Prof. William H. Green (whgreen@mit.edu),
# Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu)
#
# ... | {0}\n'.format(lines[0]))
for line in lines[1:-1]:
f.write(' {0}\n'.format(line))
f.write(' ),\n'.format(lines[0]))
if entry.referenceType != "":
f.write(' referenceType = "{0}",\n'.format(entry.referenceType))
if entry.rank is not None:
f.write(' ran... | write(entry.shortDesc.encode('utf-8'))
except:
f.write(entry.shortDesc.strip().encode('ascii', 'ignore')+ "\n")
f.write('""",\n')
if entry.longDesc.strip() !='':
f.write(' longDesc = \n')
f.write('u"""\n')
try:
f.write(entry.longDesc.strip().en... |
exercism/python | exercises/practice/clock/.meta/example.py | Python | mit | 752 | 0 | class Cloc | k:
"""Clock that displays 24 hour clock that rollsover properly"""
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
self.cleanup()
def __repr__(self):
return f'Clock({self | .hour}, {self.minute})'
def __str__(self):
return '{:02d}:{:02d}'.format(self.hour, self.minute)
def __eq__(self, other):
return repr(self) == repr(other)
def __add__(self, minutes):
self.minute += minutes
return self.cleanup()
def __sub__(self, minutes):
self... |
collingreen/startuppong | techpong/apps/techpong/migrations/0005_auto__del_field_company_image_url__add_field_company_banner_url__add_f.py | Python | mit | 8,058 | 0.007446 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Company.image_url'
db.delete_column(u'techpong_company', 'image_url')
# Adding fi... | e'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'rating': ('django.db.models.fields.FloatField', [], {'default': '0.0'})
},
u'techpong.round': {
'Meta': {'object_name': 'Round'},
u'id': ( | 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'match': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['techpong.Match']"}),
'player1_score': ('django.db.models.fields.IntegerField', [], {}),
'player2_score': ('django.db.models.fields.IntegerField... |
vileopratama/vitech | src/addons/hw_posbox_homepage/__openerp__.py | Python | mit | 714 | 0.002801 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'PosBox Homepage',
'version': '1.0',
'category': 'Point of Sale',
'sequence': 6,
| 'website': 'https://www.odoo.com/page/point-of-sale',
'summary': 'A homepage for the PosBox',
'description': """
PosBox Homepage
===============
This module overrides openerp web interface to display a simple
Homepage that explains what's the posbox and show the status,
and where to find documentation.
If yo... |
}
|
JCBarahona/edX | lms/djangoapps/lti_provider/models.py | Python | agpl-3.0 | 5,760 | 0.00191 | """
Database models for the LTI provider feature.
This app uses migrations. 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 lti_provider --auto "descr... | o find a record with a matching consumer_key.
This can be the case if the LtiConsumer record was created as the result
of an LTI launch with no instance_guid.
If the instance_guid is now present, the LtiConsumer model will be
supplemented with the instance_guid, to more concretely ident... | mers provide an instance_guid, so
the fallback mechanism of matching by consumer key should be rarely
required.
"""
consumer = None
if instance_guid:
try:
consumer = LtiConsumer.objects.get(instance_guid=instance_guid)
except LtiConsumer.Do... |
googleapis/python-game-servers | google/cloud/gaming_v1/types/common.py | Python | apache-2.0 | 13,962 | 0.001361 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | rce path for
the target of the operation.
verb (str):
Output only. Name of the verb executed by the
operation.
status_message (str):
Output only. Human-readable status of the
operation, if any.
requested_cancellation (bool):
... | led have [Operation.error][] value
with a [google.rpc.Status.code][google.rpc.Status.code] of
1, corresponding to ``Code.CANCELLED``.
api_version (str):
Output only. API version used to start the
operation.
unreachable (Sequence[str]):
Output o... |
jvahala/brew-thing | app/views.py | Python | apache-2.0 | 274 | 0 | from flask import render_template
fr | om app import app
@app.route('/')
@app.route('/mainpage')
def slp | age():
return render_template('mainpage.html')
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
|
dekomote/mezzanine-modeltranslation-backport | mezzanine/core/admin.py | Python | bsd-2-clause | 10,434 | 0.000479 | from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.db.models import AutoField
from django.forms import ValidationError, ModelForm
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.transl... | _all_editable = settings.OWNABLE_MODELS_ALL_EDITABLE
models_all_editable = [m.lower() for m in models_all_editable]
qs = super(OwnableAdmin, self).queryset(request)
if request.user.is_superuser or model_name in models_all_editable:
return qs
return qs.filter(user__id=request.... | database. Redirect all views to the change view when the
instance exists, and to the add view when it doesn't.
"""
def handle_save(self, request, response):
"""
Handles redirect back to the dashboard when save is clicked
(eg not save and continue editing), by checking for a redirec... |
xingjian-f/Leetcode-solution | 80. Remove Duplicates from Sorted Array II.py | Python | mit | 605 | 0.07438 | class Solution(object):
def removeDuplicates(self, nums):
| """
:type num | s: List[int]
:rtype: int
"""
length = len(nums)-1
if length<=0:
return 0
pos = 1
cnt = 1
last = nums[0]
while length > 0:
if nums[pos] == last:
if cnt >= 2:
del nums[pos]
else:
pos += 1
... |
bionikspoon/Codewars-Challenges | python/5kyu/palindrome_chain_length/solution.py | Python | mit | 612 | 0.001634 | from main import *
def palindrome_chain_length(n):
count = 0
while True:
reversed_n = reverse_order(n)
if is_palin | drome(n, reversed_n):
return count
n += reversed_n
count += 1
def reverse_order(n):
return int("".join([i for i in list(str(n)[::-1])]))
def is_palindrome(n, reversed_n):
return True if n == reversed_n else False
test.assert_equals(reverse_order(87), 78)
test.assert_equals(is_p... | rome_chain_length(87), 4) |
freak97/binutils | gdb/testsuite/gdb.python/py-finish-breakpoint2.py | Python | gpl-2.0 | 1,221 | 0.006552 | # Copyright (C) 2011-2016 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis | hed by
# the Free Software Foun | dation; 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 PARTICULAR PURPOSE. See the
# GNU General Public License for more det... |
seymour1/label-virusshare | test/test_hashes.py | Python | bsd-3-clause | 1,444 | 0.004848 | import json
import argparse
import logging
import glob
# Logging Information
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s: %(message)s')
fh = logging.FileHandler('test_hashes.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter) |
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
parser = argparse.ArgumentParser()
parser.add_argument("hash_num", | help="file that we want to verify")
args = parser.parse_args()
hashes = set()
hash_num = args.hash_num
logger.info("Verifying consistency for VirusShare_00" + str(hash_num).zfill(3))
logger.debug("Generating hashes from ../hashes/VirusShare_00" + str(hash_num).zfill(3) + ".md5")
with open(("../hashes/VirusShare_00" ... |
dscho/hg | mercurial/streamclone.py | Python | gpl-2.0 | 13,689 | 0.001315 | # streamclone.py - producing and consuming streaming repository data
#
# Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import struct
... | , None
# Streaming clone only works on empty repositories.
if len(repo):
return False, None
# Streaming clone only works if all data is being requested.
if pullop.heads:
return False, None
streamrequested = pullop.streamclonerequested
# If we don't have a preference, let the ... | eamrequested is None:
# The server can advertise whether to prefer streaming clone.
streamrequested = remote.capable('stream-preferred')
if not streamrequested:
return False, None
# In order for stream clone to work, the client has to support all the
# requirements advertised by th... |
googleads/google-ads-python | google/ads/googleads/v9/services/types/keyword_plan_campaign_service.py | Python | apache-2.0 | 6,083 | 0.000493 | # -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | age):
r"""A single operation (create, update, remove) on a Keyword Plan
campaign.
This message has `oneof`_ fields (mutually exclusive fields).
For each oneof, at most | one member field can be set at the same time.
Setting any member of the oneof automatically clears all other
members.
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
... |
henrysher/imagefactory | imagefactory-plugins/EC2Cloud/EC2Cloud.py | Python | apache-2.0 | 70,484 | 0.006626 | #
# Copyright 2011 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | n import ApplicationConfiguration
from imgfac.ImageFactoryException import ImageFactoryException
from imgfac.ReservationManager import ReservationManager
from boto.s3.connection import S3Connection
from boto.s3.connection import Location
from boto.exception import *
from boto.ec2.blockdevicemapping import EBSBlockDevic... | , BlockDeviceMapping
from imgfac.CloudDelegate import CloudDelegate
# Boto is very verbose - shut it up
logging.getLogger('boto').setLevel(logging.INFO)
def subprocess_check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
pr... |
jlcarmic/producthunt_simulator | venv/lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py | Python | mit | 19,348 | 0.001551 | """
Pure SciPy implementation of Locally Optimal Block Preconditioned Conjugate
Gradient Method (LOBPCG), see
http://www-math.cudenver.edu/~aknyazev/software/BLOPEX/
License: BSD
Authors: Robert Cimrman, Andrew Knyazev
Examples in tests directory contributed by Nils Wagner.
"""
from __future__ import division, prin... | `` to make this better.
2. How well conditioned the problem is. This can be changed by using proper
preconditioning. For example, a | rod vibration test problem (under tests
directory) is ill-conditioned for large ``n``, so convergence will be
|
stvstnfrd/edx-platform | openedx/features/calendar_sync/tests/test_views.py | Python | agpl-3.0 | 2,051 | 0.002438 | """
Tests for Calendar Sync views.
"""
import ddt
from django.test import TestCase
from django.urls import reverse
from openedx.features.calendar_sync.api import SUBSCRIBE, UNSUBSCRIBE
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import Course... | '{}'}}".format(UNSUBSCRIBE)}, 302, ''],
# 422 on unknown toggle_data
[{'tool_data': "{{'toggle_data': '{}'}}".format('gibberish')}, 422,
'Toggle data was not provided or had unknown value.'],
# 422 on no toggle_data
[{'tool_data': "{{'random_data': '{}'}}".format('gibberish'... | gibberish')}, 422, 'Tool data was not provided.'],
)
@ddt.unpack
def test_course_dates_fragment(self, data, expected_status_code, contained_text):
response = self.client.post(self.calendar_sync_url, data)
assert response.status_code == expected_status_code
assert contained_text in st... |
mapr-demos/wifi-sensor-demo | python/mpu6050/all_constants.py | Python | apache-2.0 | 15,010 | 0.022252 | # constants extracted from
# https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050.h
MPU6050_ADDRESS_AD0_LOW = 0x68
MPU6050_ADDRESS_AD0_HIGH = 0x69
MPU6050_DEFAULT_ADDRESS = MPU6050_ADDRESS_AD0_LOW
MPU6050_RA_XG_OFFS_TC = 0x00
MPU6050_RA_YG_O... | = 0x16
MPU6050_RA_ZG_OFFS_USRH = 0x17
MPU6050_RA_ZG_OFFS_USRL = 0x18
MPU6050_RA_SMPLRT_DIV = 0x19
MPU6050_RA_CONFIG = 0x1A
MPU6050_RA_GYRO_CONFIG = 0x1B
MPU6050_RA_ACCEL_CONFIG = 0x1C
MPU6050_RA_FF_THR ... | MPU6050_RA_FF_DUR = 0x1E
MPU6050_RA_MOT_THR = 0x1F
MPU6050_RA_MOT_DUR = 0x20
MPU6050_RA_ZRMOT_THR = 0x21
MPU6050_RA_ZRMOT_DUR = 0x22
MPU6050_RA_FIFO_EN = 0x23
MPU6050_RA_I2C_MST_CTRL = 0x24
MPU60... |
drpaneas/linuxed.gr | lib/python2.7/site-packages/dateutil/rrule.py | Python | mit | 47,634 | 0.000084 | # -*- coding: utf-8 -*-
"""
The rrule module offers a small, complete, and very fast, implementation of
the recurrence rules documented in the
`iCalendar RFC <http://www.ietf.org/rfc/rfc2445.txt>`_,
including support for caching of results.
"""
import itertools
import datetime
import calendar
import sys
from six impor... | lse
self._len = None
def __iter__(self):
if self._cache_complete:
return iter(self | ._cache)
elif self._cache is None:
return self._iter()
else:
return self._iter_cached()
def _iter_cached(self):
i = 0
gen = self._cache_gen
cache = self._cache
acquire = self._cache_lock.acquire
release = self._cache_lock.release
... |
baverman/cakeplant | cakeplant/bank/model.py | Python | mit | 573 | 0.012216 | import calendar
db = [None]
def get_month_transaction_day | s(acc, year, month):
monthdays = calendar.monthrange(year, month)
result = db[0].view('bank/transaction_days', startkey=[acc._id, year, month, 1],
endkey=[acc._id, year, month, monthdays], group=True, group_level=4).all()
return [r['key'][-1] for r in result]
def get_what_choice():
result = db... | ['key'] for r in result] |
Lucky0604/algorithms | sort/bubble-sort.py | Python | mit | 1,125 | 0.002361 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
冒泡排序(bubble sort):每个回合都从第一个元素开始和它后面的元素比较,
如果比它后面的元素更大的话就交换,一直重复,直到这个元素到了它能到达的位置。
每次遍历都将剩下的元素中最大的那个放到了序列的“最后”(除去了前面已经排好的那些元素)。
注意检测是否已经完成了排序,如果已完成就可以退出了。时间复杂度O(n2)
'''
def short_bubble_sort(a_list):
excha | nge = True
pass_num = len(a_list) - 1
while pass_num > 0 and exchange:
exchange = False
for i in range(pass_num):
if a_list[i] > a_list[i + 1]:
exchange = True
# temp = a_list[i]
# a_list[i] = a_list[i + 1]
# a_list[i + ... | if __name__ == '__main__':
a_list = [20, 40, 50, 22, 100, 90]
short_bubble_sort(a_list)
print(a_list) # [20, 22, 40, 50, 90, 100]
|
taosheng/jarvis | socialBrainTest/python/brain.py | Python | apache-2.0 | 1,645 | 0.015309 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import requests
class Brain():
def think(self, userSession):
pass
class WikiBrain(Brain):
maxN = ''
maxX = ''
wikiAPI = u'https://zh.wikipedia.org/w/api.php?uselang=zh_tw&action=query&prop=extracts&format=xml&exintro=&titles='
... | pass
return result
def findWiki(self, word):
# print(word)
r = requests.get( self.wikiAPI+word.word )
# print(r.encoding)
#print(dir(r))
return self.getExtract(r.text)
def | getExtract(self, wikiApiRes):
if wikiApiRes.count('<extract')==0 :
return ""
result = wikiApiRes.split('<extract')[1].split('</extract>')[0]
result = result.replace('xml:space="preserve">','')
result = result.replace('<','')
result = result.replace('p>','')
... |
uwosh/uwosh.filariasis | uwosh/filariasis/skins/uwosh.filariasis/indexByBMalayi.py | Python | gpl-2.0 | 393 | 0.007634 | if hasattr(context, 'portal_type') a | nd context.portal_type == 'FormSaveData2ContentEntry':
index = None
if context.getValue('brugia-malayi') != 'None' or ('B. malayi' | in context.getValue('a-aegypti-infected-with-filariae')):
if context.getValue('brugia-malayi') == '':
index = None
else:
index = 'BM'
return index
else:
return None
|
yehnan/project_euler_python | p019.py | Python | mit | 1,291 | 0.015492 |
# Problem 19: Counting Sundays
# https://projecteuler.net/problem=19
def is_leapyear(year):
if year%4 == 0 and year%100 != 0 or year%400 == 0:
return 1
else:
return 0
month = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31]
def days_of_month(m, y):
... | te_to_days(date):
dy, mn, yr = date
days = dy
for y in range(1900, yr):
days += days_of_year(y)
for m in range(1, mn):
days += days_of_month(m, yr)
return days
def is_sunday(days):
return days % 7 == 0
def cs():
count = 0
for y in range(1901, 2000+1):
... | 2+1):
days = date_to_days((1, m, y))
if is_sunday(days):
count += 1
return count
#
def test():
return 'No test'
def main():
return cs()
if __name__ == '__main__':
import sys
if len(sys.argv) >= 2 and sys.argv[1] == 'test':
pr... |
tastyproject/tasty | tasty/tests/functional/protocols/mul/garbled_server_server_client/protocol_setup_server.py | Python | gpl-3.0 | 756 | 0.005291 | from tasty.types import conversions
from tasty.types import *
from tasty.types.driver impo | rt TestDriver
__params__ = {'la': 32, 'lb': 32, 'da': 10}
driver = TestDriver()
def protocol(client, server, params):
server.ga = Garbled(val=Unsigned(bitlen=764, dim=[1], signed=False, passive=True, empty=True), signed=False, bitlen=764, dim=[1])
server.gb = Garbled(val=Unsigned(bitlen=764, dim=[1], signed=Fa... | arbled_Garbled_send(server.gb, client.gb, 764, [1], False)
client.gc = client.ga * client.gb
client.c = Unsigned(val=client.gc, passive=True, signed=False, bitlen=1528, dim=[1])
|
daspecster/google-cloud-python | speech/google/cloud/speech/client.py | Python | apache-2.0 | 4,677 | 0 | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance | with the License.
# You | may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable 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 ... |
oconnor663/peru | tests/test_cache.py | Python | mit | 18,779 | 0 | import asyncio
import os
import time
import peru.cache
from shared import assert_contents, create_dir, make_synchronous, PeruTest
class CacheTest(PeruTest):
@make_synchronous
def setUp(self):
self.cache = yield from peru.cache.Cache(create_dir())
self.content = {
'a': 'foo',
... | chronous
def test_merge_trees(self):
merged_tree = yield from self.cache.merge_trees(
self.content_tree, self.content_tree, 'subdir')
expected_content = dict(self.content)
for path, content in self.content.items():
expected_content[os.path.join('subdir', path)] = cont... | ises(peru.cache.MergeConflictError):
# subdir/ is already populated, so this merge should throw.
yield from self.cache.merge_trees(
merged_tree, self.content_tree, 'subdir')
@make_synchronous
def test_merge_with_deep_prefix(self):
'''This test was inspired by a b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.