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 |
|---|---|---|---|---|---|---|---|---|
amrdraz/brython | www/tests/test_dict.py | Python | bsd-3-clause | 593 | 0.06914 | d = {1:'Z','y':88}
assert d.__class__ == dict
assert isinstance(d,dict)
assert str(d)=="{1: 'Z', 'y': 88}"
x = dict([['a',1],['r',2],['bg',3],['Z',4]])
y = dict(zip(['a','r','Z','bg'],[1,2,4,3]))
z = {'bg':3,' | Z':4,'a':1,'r':2}
assert x==y
assert x==z
assert y==z
assert x['a']==1
assert x.get('a')==1
assert x.get('uiop',99)==99
y = x.copy()
assert x==y
y.clear()
assert len(y)==0
assert len(x)==4
# subclass
class foo(dict):
def show(self):
return 'show'
x = foo({1:2})
assert x.show() == 'show'
assert str(x)=="... | ("passed all tests..")
|
jkonecny12/anaconda | pyanaconda/payload/rpmostreepayload.py | Python | gpl-2.0 | 2,202 | 0.000454 | # ostreepayload.py
# Deploy OSTree trees to target
#
# Copyright (C) 2012,2014,2021 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later versi... | _from_opts(self, opts):
"""Add the flatpak source if available."""
flatpak_source = create_source(SOURCE_TYPE_FLATPAK)
if not flatpak_source.IsAvailable():
log.debug("The flatpak source is not available.")
return
sources = self.proxy.Sources
sources.appe... | ject_path(flatpak_source))
self.proxy.SetSources(sources)
@property
def type(self):
"""The DBus type of the payload."""
return PAYLOAD_TYPE_RPM_OSTREE
@property
def default_source_type(self):
"""The DBus type of the default source."""
return SOURCE_TYPE_RPM_OSTR... |
dhalbert/Adafruit_CircuitPython_HID | adafruit_hid/__init__.py | Python | mit | 1,062 | 0.000942 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_hid`
====================================================
This driver sim | ulates USB HID devices.
* Author(s): Scott Shawcroft, Dan Halbert
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
# imports
__version__ = "0.0.0-auto.0"
__repo__ = "https://g... | om/adafruit/Adafruit_CircuitPython_HID.git"
def find_device(devices, *, usage_page, usage):
"""Search through the provided list of devices to find the one with the matching usage_page and
usage."""
if hasattr(devices, "send_report"):
devices = [devices]
for device in devices:
if (
... |
ericleepa/watcherforreddit | redditpoller/migrations/0021_auto_20170312_2106.py | Python | mit | 708 | 0 | # -*- codin | g: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-13 01:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('redditpoller', '0020_auto_20170311_1503'),
]
operations = [
... | ),
migrations.AddField(
model_name='watchedsubreddit',
name='watch_interval',
field=models.IntegerField(blank=True, null=True),
),
]
|
leapcode/soledad | src/leap/soledad/client/http_target/__init__.py | Python | gpl-3.0 | 3,365 | 0 | # -*- coding: utf-8 -*-
# __init__.py
# Copyright (C) 2015 LEAP
#
# 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.
#
# Th... |
#
# You should have received a copy of | the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
A U1DB backend for encrypting data before sending to server and decrypting
after receiving.
"""
import os
from twisted.web.client import Agent
from twisted.internet import reactor
from leap.common.http import... |
lakshmi-kannan/st2 | st2actions/st2actions/scheduler.py | Python | apache-2.0 | 4,884 | 0.003686 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | get_driver(policy_db.ref,
policy_db.policy_type,
**policy_db.parameters)
try:
LOG.debug('Applyin | g pre_run policy "%s" (%s) for liveaction %s' %
(policy_db.ref, policy_db.policy_type, str(liveaction_db.id)))
liveaction_db = driver.apply_before(liveaction_db)
except:
LOG.exception('An exception occurred while applying policy "%s".', policy_db.ref... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractDhragonisslytherinWordpressCom.py | Python | bsd-3-clause | 576 | 0.032986 |
def extractDhragonisslytherinWordpressCom(item):
'''
Parser for 'dhragonisslytherin.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'trans... | buildReleaseMessageWithType(item, name, vol, chp, fra | g=frag, postfix=postfix, tl_type=tl_type)
return False
|
paour/weblate | weblate/trans/management/commands/commit_pending.py | Python | gpl-3.0 | 1,898 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | from datetime import timedelta
from optparse import make_option
class Command(WeblateLangCommand):
help = 'commits pending changes older than given age'
option_list = WeblateLangCommand.option_list + (
make_option(
'--age',
action='store',
type='int',
de... | s (default is 24 hours)'
),
)
def handle(self, *args, **options):
age = timezone.now() - timedelta(hours=options['age'])
for translation in self.get_translations(*args, **options):
if not translation.git_needs_commit():
continue
last_change = t... |
nidhididi/CloudBot | plugins/factoids.py | Python | gpl-3.0 | 5,516 | 0.004351 | import string
import asyncio
import re
from sqlalchemy import Table, Column, String
import requests
from cloudbot import hook
from cloudbot.util import botvars, colors, web
re_lineends = re.compile(r'[\r\n]*')
FACTOID_CHAR = "?" # TODO: config
table = Table(
"mem",
botvars.metadata,
Column("word", St... | ck=nick))
yield from async(db.commit)
yield from load_cache(async, db)
@asyncio.coroutine
def del_factoid(async, db, word):
"""
:type db: sqlalchemy.orm.Session
:type word: str
"""
yield from async(db.execute, table.delete().where(table.c.word == word))
yield from async(db.commit)
... | <word> [+]<data> - remembers <data> with <word> - add + to <data> to append"""
try:
word, data = text.split(None, 1)
except ValueError:
return remember.__doc__
old_data = factoid_cache.get(word)
if data.startswith('+') and old_data:
# remove + symbol
new_data = data[1:... |
Dzess/ALFIRT | alfirt.opencv/src/samples/find_obj.py | Python | mit | 3,725 | 0.012617 | import numpy as np
import cv2
#from common import anorm
from functools import partial
help_message = '''SURF image match
USAGE: findobj.py [ <image1> <image2> ]
'''
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
flann_params = dict(algorithm = FLANN_INDEX_KDTREE,
trees = 4)
def anorm2... | 0)
surf = cv2.SURF(400)
kp1, desc1 = surf.detect(img1, None, False)
kp2, desc2 = surf.detect(img2, None, False)
desc1.shape = (-1, surf.descriptorSize())
desc2.shape = (-1, surf.descriptorSize())
print 'img1 - %d features, img2 - %d features' % (len(kp1), len(kp2))
def match_and_draw(matc... | matched_p1 = np.array([kp1[i].pt for i, j in m])
matched_p2 = np.array([kp2[j].pt for i, j in m])
H, status = cv2.findHomography(matched_p1, matched_p2, cv2.RANSAC, 5.0)
print '%d / %d inliers/matched' % (np.sum(status), len(status))
vis = draw_match(img1, img2, matched_p1, matche... |
MiroK/dolfin | test/unit/python/function/test_function.py | Python | gpl-3.0 | 13,347 | 0.00517 | #!/usr/bin/env py.test
"""Unit tests for the Function class"""
# Copyright (C) 2011-2014 Garth N. Wells
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, eith... | .gnu.org/licenses/>.
import pytest
from dolfin import *
import ufl
from dolfin_utils.test import *
@fixture
def mesh():
return UnitCubeMesh(8, 8, 8)
@fixture
def R(mesh):
return FunctionSpace(mesh, 'R', 0)
@fixture
def V(mesh):
return FunctionSpace(mesh, 'CG', 1)
@fixture
def W(mesh):
return Vecto... | e(mesh, 'CG', 1)
def test_name_argument(W):
u = Function(W)
v = Function(W, name="v")
g = Function(v, name="g")
assert u.name() == "f_%d" % u.count()
assert v.name() == "v"
assert str(v) == "v"
assert g.name() == "g"
def test_in_function_space(W):
u = Function(W)
v = Function(W)
... |
mysql/mysql-utilities | mysql-test/t/import_errors.py | Python | gpl-2.0 | 15,732 | 0 | #
# Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in th... | "TAB", "GRID", "VERTICAL")
test_num = 1
for frmt in _FORMATS:
comment = ("Test Case {0} : Testing import with "
"{1} format and NAMES display").format(test_num, frmt)
# We test DEFINITIONS and DATA only in other tests
self.run_import_test(1, fro... | ay=NAMES")
self.drop_db(self.server2, "util_test")
test_num += 1
export_cmd = ("mysqldbexport.py {0} util_test --export=BOTH "
"--format=SQL --skip-gtid > "
"{1}").format(from_conn, self.export_import_file)
# First run the export to ... |
Oslandia/vizitown_plugin | twisted/lore/texi.py | Python | gpl-2.0 | 3,134 | 0.002553 | # -*- test-case-name: twisted.lore.test.test_texi -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from cStringIO import StringIO
import os, re
from twisted.web import domhelpers
import latex, tree
spaceRe = re.compile('\s+')
def texiEscape(text):
return spaceRe.sub(text, ' ')
entiti... | te, entities=entities)
| self.writer(tree._removeLeadingTrailingBlankLines(buf.getvalue()))
self.writer('@end verbatim\n')
def visitNode_code(self, node):
fout = StringIO()
latex.getLatexText(node, fout.write, texiEscape, entities)
self.writer('@code{'+fout.getvalue()+'}')
def visitNodeHeader(self,... |
nortikin/sverchok | nodes/curve/length_parameter.py | Python | gpl-3.0 | 5,754 | 0.01512 | import numpy as np
import bpy
from bpy.props import FloatProperty, EnumProperty, IntProperty, BoolProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level
from sverchok.utils.curve import SvCurveLengthSolver, SvCurve
from sverch... | e the curve at evenly spaced points", 0),
('MANUAL', "Manual", "Evaluate the curve at specified points", 1)
]
eval_mode : EnumProperty(
name = "Mode",
it | ems = eval_modes,
default = 'AUTO',
update = update_sockets)
sample_size : IntProperty(
name = "Samples",
default = 50,
min = 4,
update = updateNode)
specify_accuracy : BoolProperty(
name = "Specify accuracy",
default = False,
... |
olgabot/prettyplotlib | prettyplotlib/_pcolormesh.py | Python | mit | 4,451 | 0.000225 | __author__ = 'olga'
import numpy as np
from prettyplotlib.colors import blue_red, blues_r, reds
from prettyplotlib.utils import remove_chartjunk, maybe_get_fig_ax
def pcolormesh(*args, **kwargs):
"""
Use for large datasets
Non-traditional `pcolormesh` kwargs are:
- xticklabels, which will put x tic... | wargs)
# ax.set_ylim(0, x.shape[0])
# ax.set_xlim(0, x.shape[1])
# Get rid of ALL axes
remove_chartjunk(ax, ['top', 'right', 'left', 'bottom'])
if xticklabels is not None and any(xticklabels):
if len(args) == 1:
xticks = np.arange(0.5, data.shape[1] + 0.5)
else | :
xticks = []
for i in np.arange(len(x) - 1):
half = float(x[i + 1] - x[i]) / 2. + x[i]
xticks.append(half)
xticks = np.array(xticks)
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels, rotation=xticklabels_rotation)
if yticklabels i... |
mrozekma/Sprint | Log.py | Python | mit | 1,492 | 0.036863 | from __future__ import division
import traceback
import datetime
from math import ceil
from User import User
from utils import *
from stasis.Singleton import get as db
from stasis.ActiveRecord import ActiveR | ecord, link
class LogEntry(ActiveRecord):
user = link(User, 'userid')
def __init__(self, type, text, userid = None, ip = None, timestamp = None, location = 0, id = None):
ActiveRecord.__init__(self)
self.id = id
self.userid = userid
self.ip = ip
self.type = type
self.text = text
if timestamp:
self... | ow = datetime.now() # Use real time, not mocked time through getNow()
self.timestamp = dateToTs(now) + now.microsecond / 1000000
if isinstance(location, int):
filename, line, fn, code = traceback.extract_stack()[-2-location]
if filename.startswith(basePath()):
filename = filename[len(basePath())+1:]
... |
felipetomm/POX-Django | pox/openflow/topology.py | Python | apache-2.0 | 15,340 | 0.013233 | # Copyright 2011 James McCauley
#
# 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 writi... | "Switch %s connected, but... it's already connected!" %
(dpidToStr(event.dpid),))
sw._setConnection(event.connection, event.ofp)
log.info("Switch " + dpidToStr(event.dpid) + " connected")
if add:
self.topology.addEntity(sw)
sw.raiseEvent(SwitchJoin, sw)
def _handle_openflow_C... | dpidToStr(event.dpid),))
else:
if sw._connection is None:
log.warn("Switch %s disconnected, but... it's wasn't connected!" %
(dpidToStr(event.dpid),))
sw._connection = None
log.info("Switch " + str(event.dpid) + " disconnected")
class OpenFlowPort (Port):
"""
A subcl... |
ovnicraft/odoo_addons | smile_attachment/models/models.py | Python | agpl-3.0 | 3,948 | 0.002533 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under th... | e.fromstring(res['arch'])
element = etree.Element('field', name=name)
arch_etree.insert(-1, element)
res['arch'], res['fields'] = View.postprocess_and_fields(self._name, arch_etree, view_id)
return res
Model._get_attachments_field_name = _get_attachments_field_name
Model._setup_fields = _se... | tachments = _get_attachments
Model._search_attachments = _search_attachments
Model.fields_view_get = fields_view_get
|
JeffHoogland/python-elm-extensions | test_tabbedbox.py | Python | bsd-3-clause | 1,214 | 0.01318 | import efl.elementary as elm
elm.init()
from efl.elementary.window import StandardWindow
from efl.elementary.label import Label
from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL
from elmextensions import TabbedBox
EXPAND_BOTH = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND
FILL_BOTH = EVAS_HINT_FILL, EVAS_HINT_FILL
class M... | elf ):
win = StandardWindow("Testing", "Elementary Tabbed Widget")
win.callback_delete_request_add(lambda o: elm.exit())
tabbs = TabbedBox(win, size_hint_weight= | EXPAND_BOTH, size_hint_align=FILL_BOTH)
tabbs.closeCallback = self.closeChecks
for i in range(10):
lbl = Label(win)
lbl.text = "Tab %s"%i
lbl.show()
tabbs.addTab(lbl, "Tab %s"%i)
tabbs.disableTab(0)
tabbs.disableTab(3)
... |
liosha2007/temporary-groupdocs-python3-sdk | groupdocs/models/StorageInfoResponse.py | Python | apache-2.0 | 1,149 | 0.007833 | #!/usr/bin/env python
"""
Copyright 2012 GroupDocs.
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 Lic | ense at
http://www.apache.org/licenses/LICENSE-2.0
Unless required b | y 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 governing permissions and
limitations under the License.
"""
class Stora... |
vasiliykochergin/euca2ools | euca2ools/commands/iam/deactivatemfadevice.py | Python | bsd-2-clause | 1,876 | 0 | # Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions ... | he above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation | and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SH... |
nixhope/UdacityX | main.py | Python | mit | 2,047 | 0.010259 | import re
import logging
from google.appengine.ext import db
from google.appengine.api import users, memcache
from handler import Handler, SlashRedirect
from webapp2_extras.routes import RedirectRoute, PathPrefixRoute
import webapp2
fro | m webapp2_extras.routes import RedirectRoute, PathPrefixRoute
import articles
import api
from contents import panels
class Main(Handler):
def get(self):
logging.debug('%s'%self.request)
if 'main' in self.request.url:
| self.redirect('/')
self.render('base.html')
def handle_404(request, response, exception):
Handler(request, response).throw_error(404)
def handle_500(request, response, exception):
Handler(request, response).throw_error(500)
# Define which urls to handle and how
PAGE_RE = r'((?:[a-zA... |
googleapis/python-compute | google/cloud/compute_v1/services/forwarding_rules/transports/__init__.py | Python | apache-2.0 | 1,111 | 0.0009 | # -*- 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.a | pache.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 governing permissions and
# li... | from .base import ForwardingRulesTransport
from .rest import ForwardingRulesRestTransport
from .rest import ForwardingRulesRestInterceptor
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[ForwardingRulesTransport]]
_transport_registry["rest"] = ForwardingRulesRestTranspo... |
saadatqadri/airflow | airflow/operators/hive_stats_operator.py | Python | apache-2.0 | 6,082 | 0 | from builtins import str
from builtins import zip
from collections import OrderedDict
import json
import logging
from airflow.utils import AirflowException
from airflow.hooks import PrestoHook, HiveMetastoreHook, MySqlHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class HiveSta... | return {k: v.format(col=co | l) for k, v in d.items()}
def execute(self, context=None):
metastore = HiveMetastoreHook(metastore_conn_id=self.metastore_conn_id)
table = metastore.get_table(table_name=self.table)
field_types = {col.name: col.type for col in table.sd.cols}
exprs = {
('', 'count'): 'CO... |
mvidalgarcia/indico | indico/core/plugins/alembic/env.py | Python | mit | 3,235 | 0.001855 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indic | o is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import logging.config
from alembic import context
from flask import cur | rent_app
from flask_pluginengine import current_plugin
from sqlalchemy import engine_from_config, pool
from indico.core.db.sqlalchemy.util.models import import_all_models
if not current_plugin:
raise Exception('Cannot run plugin db migration outside plugin context')
# Ensure all our models are imported - XXX i... |
jordanemedlock/psychtruths | temboo/core/Library/Amazon/S3/GetService.py | Python | apache-2.0 | 3,503 | 0.004568 | # -*- coding: utf-8 -*-
###############################################################################
#
# GetService
# Retrieves a list of buckets owned by the authenticated user.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# y... | eo. ((optional, string) The format that the response should be in. Valid values are "xml" (the default) and "json".)
"""
super(GetServiceInputSet, self)._set_input('ResponseFormat', value)
class GetServiceResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the ... | , str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Amazon.)
"""
return self._output.get('Response', None)
class GetServiceChoreographyExecution(ChoreographyExecution):
d... |
wasade/qiime | scripts/convert_unifrac_sample_mapping_to_otu_table.py | Python | gpl-2.0 | 457 | 0 | #! /usr/bin/env python
__author__ = "Cathy Lozupone"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["Catherine Lozupone", "Greg Caporaso",
"Jose Antonio Navas | Molina"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__m | aintainer__ = "Cathy Lozupone"
__email__ = "lozupone@colorado.edu"
print """\nThis script has been moved to the FastUnifrac repository. \
For more information, see http://github.com/qiime/FastUnifrac"""
|
l5h5t7/ZeroNet | plugins/disabled-UiPassword/UiPasswordPlugin.py | Python | gpl-2.0 | 5,239 | 0.003818 | import string
import random
import time
import json
import re
from Config import config
from Plugin import PluginManager
if "sessions" not in locals().keys(): # To keep sessions between module reloads
sessions = {}
def showPasswordAdvice(password):
error_msgs = []
if not password or not isinstance(pass... | password):
return | password == config.ui_password
def randomString(self, nchars):
return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(nchars))
@classmethod
def cleanup(cls):
cls.last_cleanup = time.time()
for session_id, session in cls.sessions... |
bsmedberg/socorro | socorro/lib/threaded_task_manager.py | Python | mpl-2.0 | 16,098 | 0.001864 | """This module defines classes that implements a threaded
producer/consumer system. A single iterator thread pushes jobs into an
internal queue while a flock of consumer/worker threads do the jobs. A job
consists of a function and the data applied to the function."""
import time
import threading
import Queue
from c... | e been translated to) and will order the threads to die."""
try:
self.start()
self.wait_for_completion(waiting_func)
# it only ends if someone hits ^C or sends SIGHUP or SIGTERM -
# any of which will get translated into a KeyboardInterrupt
except Keyboar | dInterrupt:
while True:
try:
self.stop()
break
except KeyboardInterrupt:
self.logger.warning('We heard you the first time. There '
'is no need for further keyboard or signal '
... |
MungoRae/home-assistant | homeassistant/components/zeroconf.py | Python | apache-2.0 | 1,636 | 0 | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util
from homeassistant.const import (EVENT_HOMEASSISTANT... | = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.reg | ister_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
|
asedunov/intellij-community | python/helpers/python-skeletons/django/forms/formsets.py | Python | apache-2.0 | 583 | 0.001715 | # TODO: Commit to | separate repositoruy
from django.forms import BaseForm
class BaseFormSet(object):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, form_kwargs=None):
"""
... | :rtype: collections.Iterator[T]
"""
pass
def __getitem__(self, index):
"""
:rtype: T
"""
pass
|
DT42/BerryNet | berrynet/engine/tensorflow_engine.py | Python | gpl-3.0 | 3,670 | 0.000272 | # Copyright 2017 DT42
#
# This file is part of BerryNet.
#
# BerryNet 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.
#
# BerryNet is d... | = round(float(predictions[node_id]), decimal_digits)
anno = {
'type': 'classification',
'label': human_string,
'confidence': score
}
processed_output['annotations'].append(an | no)
logger.debug('%s (score = %.5f)' % (human_string, score))
return processed_output
def save_cache(self):
pass
# NOTE: Copied from trainer.component
def read_tensor_from_nparray(self, input_height=192, input_width=192,
input_mean=0, input_std=... |
pronobis/rocs | src/data/python/rocs/data/conceptual.py | Python | bsd-2-clause | 2,891 | 0.011073 | # -*- coding: utf-8 -*-
# ==================================================================
# ROCS - Toolkit for Robots Comprehending Space
# Copyright (C) 2011 André Susano Pinto
#
# This file is part of ROCS.
#
# ROCS is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Gen... | tual map.
#
# ConceptualMaps can be created from dumps of the conceptual modules or from
# other database sequences.
#
class Graph:
def __init__(self):
self.node = {}
self.edge = {}
def AddNode( | self, name, type):
assert name not in self.node
node = ConceptualNode(name, type)
self.node[name] = node
return node
def AddEdge(self, name, type, nodes):
assert name not in self.edge
for node in nodes: assert node in self.node
edge = ConceptualEdge(name, type, nodes)
self.edge... |
kaback/ham2mon | apps/receiver.py | Python | gpl-3.0 | 25,151 | 0.000676 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 3 13:38:36 2015
@author: madengr
"""
from gnuradio import gr
import osmosdr
from gnuradio import filter as grfilter # Don't redefine Python's filter()
from gnuradio import blocks
from gnuradio import fft
from gnuradio.fft import window
from gnuradi... | # If we never wrote any data to the wavfile sink, delete
# the (empty) wavfile
if os.stat(self.file_name).st_size in (44, 0): # ugly hack
os.unlink(self.file_nam | e) # delete the file
def set_squelch(self, squelch_db):
"""Sets the threshold for both squelches
Args:
squelch_db (float): Squelch in dB
"""
self.analog_pwr_squelch_cc.set_threshold(squelch_db)
def __del__(self):
"""Called when the object is destroyed."""
... |
IvIePhisto/Ancestration | tests/family_b.py | Python | mit | 231 | 0.004329 | from ancestration import family
super_family = family.tests.famil | y_a()
ClassA = family_class('ClassA', (object,), {
'a': lambda self: 'family_b: A',
'd': lambda self: 'family_b: A',
})
adopt(m | odule='tests.adopt_into_b') |
MelomanCool/telegram-audiomemes | custom_filters.py | Python | mit | 653 | 0 | from telegram.ext import BaseFilter
from pathlib import Path
import model
class IsInDatabase(BaseFilter):
def __init__(self, storage):
self.storage = storage
def filter(self, message) | :
return (message.voice is not None
and self.storage.has_meme_with_file_id(message.voice.file_id))
class IsAudioDocument(BaseFi | lter):
EXTENSIONS = ('.mp3', '.ogg')
def filter(self, message):
return (message.document is not None
and Path(message.document.file_name).suffix in self.EXTENSIONS)
is_audio_document = IsAudioDocument()
is_in_database = IsInDatabase(storage=model.get_storage())
|
larsks/cloud-init | cloudinit/sources/DataSourceGCE.py | Python | gpl-3.0 | 11,049 | 0 | # Author: Vaidas Jablonskis <jablonskis@gmail.com>
#
# This file is part of cloud-init. See LICENSE file for license information.
import datetime
import json
from base64 import b64decode
from cloudinit.distros import ug_util
from cloudinit import log as logging
from cloudinit import sources
from cloudinit import url... | _parse_public_keys(public_keys_data, default_user=None):
# Parse the SSH key data for the default user account. Public keys in | put is
# a list containing SSH public keys in the GCE specific key format
# documented here:
# https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#sshkeyformat
public_keys = []
if not public_keys_data:
return public_keys
for public_key in public_keys_data:
if... |
OCA/multi-company | account_invoice_consolidated/tests/__init__.py | Python | agpl-3.0 | 151 | 0 | # Copyright (C) 2020 Open Source Integrators
# Lic | ense AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import test_ | consolidated_invoices
|
ibuildthecloud/volmgr | tests/integration/test_main.py | Python | apache-2.0 | 12,292 | 0.008054 | #!/usr/bin/python
import subprocess
import os
import json
import pytest
from volmgr import VolumeManager
TEST_ROOT = "/tmp/volmgr_test/"
CFG_ROOT = os.path.join(TEST_ROOT, "volmgr")
BLOCKSTORE_ROOT = os.path.join(TEST_ROOT, "rancher-blockstore")
BLOCKSTORE_CFG = os.path.join(BLOCKSTORE_ROOT, "blockstore.cfg")
BLOCK... | mes"][volume2_uuid]["Snapshots"][snap2_vol2_uuid]
assert volumes["Volumes"][volume2_uuid]["Snapshots"][snap3_vol2_uuid]
volumes = v.list_volumes()
assert volumes["Volumes"][volume1_uuid]["Snapshots"][snap1_vol1_uuid]
assert volumes["Volumes"][volume1_uuid]["Snapshots"][snap2_vol1_uuid]
assert volum... | Volumes"][volume2_uuid]["Snapshots"][snap2_vol2_uuid]
assert volumes["Volumes"][volume2_uuid]["Snapshots"][snap3_vol2_uuid]
v.delete_snapshot(snap1_vol1_uuid, volume1_uuid)
v.delete_snapshot(snap2_vol1_uuid, volume1_uuid)
v.delete_snapshot(snap1_vol2_uuid, volume2_uuid)
v.delete_snapshot(snap2_vol2... |
openfisca/openfisca-survey-manager | openfisca_survey_manager/tests/test_marginal_tax_rate.py | Python | agpl-3.0 | 989 | 0.019211 |
import logging
from openfisca_core.tools import assert_near
from openfisca_country_template import CountryTaxBenefitSystem
from openfisca_survey_manager.tests.test_scenario import (
create_randomly_initialized_survey_scenario
)
log = logging.getLogger(__name__)
tax_benefit_system = CountryTaxBenefitSyste... | scenario = create_randomly_initialized_survey_scenario(use_marginal_tax_rate = True)
assert survey_scenario._modified_simulation is not None
assert_near(
survey_scenario.compute_marginal_tax_rate(target_variable = 'income_tax', period = 2017),
(1 - .15),
relative_error_margin = 1e-6,
| )
survey_scenario.compute_marginal_tax_rate(target_variable = 'disposable_income', period = 2017)
if __name__ == "__main__":
import sys
log = logging.getLogger(__name__)
logging.basicConfig(level = logging.DEBUG, stream = sys.stdout)
test_compute_marginal_tax_rate()
|
MostlyOpen/odoo_api | myo_person.py | Python | agpl-3.0 | 17,530 | 0.000627 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pub... | d:
user_id = person_reg.user_id.id
birthday = None
if person_reg.birthday:
birthday = person_reg.birthday
| estimated_age = None
if person_reg.estimated_age:
estimated_age = person_reg.estimated_age
date_reference = None
if person_reg.date_reference:
date_reference = person_reg.date_reference
marital = None
if person_reg.marital:
mari... |
ballouche/navitia | source/jormungandr/jormungandr/scenarios/destineo.py | Python | agpl-3.0 | 17,467 | 0.003779 | # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | if j1.departure_date_time != j2.departure_date_time:
return -1 if j1.departure_date_time < j2.departure_date_time else 1
return self.sort_by_duration_and_transfert(j1, j2)
def __call__(self, j1, j2):
j1_dt = datetime.utcfromtimestamp(j1.departure_date_time)
j2_dt = datetime.ut... | ytz.utc.localize(j1_dt).astimezone(pytz.timezone(self.timezone)).date()
j2_date = pytz.utc.localize(j2_dt).astimezone(pytz.timezone(self.timezone)).date()
#we first sort by date, we want the journey of the first day in first even if it's a non_pt
if j1_date != j2_date:
if j1_date < ... |
takeyourmeds/takeyourmeds-web | takeyourmeds/reminders/migrations/0003_reminder_slug.py | Python | mit | 580 | 0.001724 | # -*- coding: utf-8 -*-
# Generated by Django 1.9c1 on 2015-11-17 18:21
from __future__ import un | icode_literals
from django.db import migrations, models
import django.utils.crypto
import functools
class Migration(migrations.Migration):
dependencies = [
('reminders', '0002_reminder_type'),
]
operations = [
migrations.AddField(
model_name='reminder',
name='slu... | **{}), max_length=12, null=True),
),
]
|
sinomiko/project | python_project/python/fun_for_t1.py | Python | bsd-3-clause | 110 | 0.027273 | a = ['Mary', ' | had', 'a', 'little', 'lamb']
for i in a:
print i
for i in range(len(a)):
print i,a[ | i]
|
yanheven/horizon | openstack_dashboard/dashboards/project/networks/ports/views.py | Python | apache-2.0 | 4,904 | 0 | # Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | )
return context
def get_tabs(self, request, *args, **kwargs):
port = self.get_data()
return self.tab_group_class(request, port=port, **kwargs)
@staticmethod
def get_redirect_url():
return | reverse('horizon:project:networks:index')
class UpdateView(forms.ModalFormView):
form_class = project_forms.UpdatePort
form_id = "update_port_form"
modal_header = _("Edit Port")
template_name = 'project/networks/ports/update.html'
context_object_name = 'port'
submit_label = _("Save Changes")
... |
haystack/eyebrowse-server | stats/views.py | Python | mit | 13,236 | 0.00068 | import json
from datetime import datetime
from datetime import timedelta
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Sum
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.template.load... | ')
def followers_data(request, username=None):
if request.user.username == username:
username = None
username, follows, profile_user, empty_search_msg, nav_bar = _profile_info(
request.user, username, followers=True)
# stats
tot_time, item_count = profile_stat_gen(profile_user)
f... | FavData.objects.get(user=profile_user)
num_history = EyeHistory.objects.filter(user=profile_user).count()
is_online = online_user(user=profile_user)
followers = UserProfile.objects.filter(follows=profile_user.profile)
following_count = profile_user.profile.follows.count()
follower_count = follow... |
bmya/server-tools | dbfilter_from_header/__manifest__.py | Python | agpl-3.0 | 618 | 0 | # © 2013 Therp BV
# © 2014 ACSONE SA/NV
# Copyright 2018 Quartile Limited
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "dbfilter_from_header",
"summary": "Filter databases with HTTP headers",
"version": "11.0.1.0.0",
"author": "Therp BV,Odoo Community Association (OC... | ity": "normal",
"category": "Tools",
"depends": [
'web',
],
"data": [
| ],
"js": [
],
"css": [
],
"auto_install": False,
'installable': True,
"external_dependencies": {
'python': [],
},
}
|
wikimedia/pywikibot-core | tests/date_tests.py | Python | mit | 5,263 | 0 | #!/usr/bin/python3
"""Tests for the date module."""
#
# (C) Pywikibot team, 2012-2022
#
# Distributed under the terms of the MIT license.
#
import unittest
from contextlib import suppress
from datetime import datetime
from pywikibot import date
from tests.aspects import MetaTestCaseClass, TestCase
class TestDateMeta... | formatname][code]
predicate, start, stop = date.formatLimits[formatname]
for value in range(start, stop):
with self.subT | est(code=code, month=value):
self.assertTrue(
predicate(value),
"date.formats['{}']['{}']:\ninvalid value {}"
.format(formatname, code, value))
new_value = convert(convert(value))
self.as... |
Smart-Torvy/torvy-home-assistant | homeassistant/components/climate/honeywell.py | Python | mit | 8,927 | 0 | """
Support for Honeywell Round Connected and Honeywell Evohome thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.honeywell/
"""
import logging
import socket
import voluptuous as vol
from homeassistant.components.climate import (Clima... | self._device = device
@property
def is_fan_on(self):
"""Return true if fan is on."""
return self._device.fan_running
@property
def name(self):
"""Return the name of the honeywell, if any."""
return self._device.name
@property
def temperature_unit(self):... | return (TEMP_CELSIUS if self._device.temperature_unit == 'C'
else TEMP_FAHRENHEIT)
@property
def current_temperature(self):
"""Return the current temperature."""
self._device.refresh()
return self._device.current_temperature
@property
def target_temperatu... |
intel-hpdd/intel-manager-for-lustre | chroma_core/models/network_interface.py | Python | mit | 1,046 | 0.001912 | # -*- coding: utf-8 -*-
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from django.db import models
from django.db.models import CASCADE
from chroma_core.models import Nid
class NetworkInterface(models.Model):
h... | st stick to lnet types!)
state_up = models.BooleanField(default=False)
def __str__(self):
return "%s-%s" % (self.host, self.name)
class Meta:
app_label = "chroma_core"
ordering = ["id"]
unique_together = ("host", "name")
@property
de | f lnd_types(self):
return Nid.lnd_types_for_network_type(self.type)
|
NTsystems/NoTes-API | notes/apps/account/migrations/0007_auto_20150427_1107.py | Python | mit | 422 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django | .db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0006_auto_20150422_1311'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='date_of_birth',
field=model | s.DateField(null=True, blank=True),
),
]
|
S03D4-164/thug | src/ThugAPI/IThugAPI.py | Python | gpl-2.0 | 10,957 | 0.000456 | #!/usr/bin/env python
#
# IThugAPI.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; ... | ents(events):
"""
set_events
Set the DOM events to emula | te
Note: the load and mousemove events are emulated by default and do not
need to be added through set_events
@param events: comma separated list of DOM events to emulate
@type events: C{str}
@return: None
"""
def get_delay():
"""
get_delay
... |
Lekanich/intellij-community | python/testData/refactoring/move/moveSymbolFromStatementList/before/src/a.py | Python | apache-2.0 | 127 | 0.007874 | if True:
de | f func():
pass
while True:
for _ in range(10):
# comment
clas | s C:
pass |
libracore/erpnext | erpnext/patches/v12_0/set_produced_qty_field_in_sales_order_for_work_order.py | Python | gpl-3.0 | 406 | 0.007389 | import frappe
from frappe.utils import flt
from erpnext.se | lling.doctype.sales_order.sales_order import update_produced_qty_in_so_item
def execute():
frappe.reload_doctype('Sales Order Item')
frappe.reload_doctype('Sales Order')
sales_order_items = frappe.db.get_all('Sales Order Item', ['name'])
for so_item in sales_order_items:
update_produced_qty_in_... | (so_item.get('name')) |
SEL-Columbia/commcare-hq | corehq/pillows/mappings/group_mapping.py | Python | bsd-3-clause | 1,716 | 0 | GROUP_INDEX = "hqgroups_htj2o87ep2rugag3k46hh2a67tn0r8d9"
GROUP_MAPPING = {
"date_formats": [
"yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ssZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyy... | "index": "analyzed",
"type": "string",
"analyzer": "sortable_exact"
},
"name": {
"index": | "analyzed",
"type": "string"
}
},
"type": "multi_field"
},
"reporting": {"type": "boolean"},
"path": {"type": "string"},
"case_sharing": {"type": "boolean"},
"users": {"type": "string"},
}
}
|
pwnbus/scoring_engine | tests/scoring_engine/checks/test_ftp.py | Python | mit | 474 | 0.00211 | from scor | ing_engine.engine.basic_check import CHECKS_BIN_PATH
from tests.scoring_engine.checks.check_test import CheckTest
class TestFTPCheck(CheckTest):
check_name = 'FTPCheck'
properties = {
'remotefilepath': '/adir/ | textfile.txt',
'filecontents': 'Sample contents'
}
accounts = {
'testuser': 'testpass'
}
cmd = CHECKS_BIN_PATH + "/ftp_check '127.0.0.1' 1234 'testuser' 'testpass' '/adir/textfile.txt' 'Sample contents'"
|
18F/django-rest-swagger | tests/auth_example/auth_example/wsgi.py | Python | bsd-2-clause | 1,437 | 0.000696 | """
WSGI config for auth_example project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | s own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "auth_example.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auth_example.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
#... | ware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
gengwg/leetcode | 024_swap_nodes_in_pairs.py | Python | apache-2.0 | 1,999 | 0.001501 | """
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space.
You may not modify the values in the list, only nodes itself can be changed.
author: https://git... | # store node2 in tmp
p.next.next = tmp.next # connect node1 to node3; this also disconnects node1 from node2
# p.next.next = p.next.next.next # delete node2
tmp.next = p.next # connect node2 to node1; now that node1 is already disconnected to node2
p.next = tmp # ... | p = p.next.next
return dummy.next
if __name__ == '__main__':
l = ListNode(1)
l.next = ListNode(2)
l.next.next = ListNode(3)
l.next.next.next = ListNode(4)
print l
print Solution().swapPairs(l)
|
androidarmv6/android_external_chromium_org | tools/telemetry/telemetry/page/actions/loop.py | Python | bsd-3-clause | 1,886 | 0.005832 | # Copyright 2013 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.
"""A Telemetry page_action that loops media playback.
Action attributes are:
- loop_count: The number of times to loop media.
- selector: If no selector is ... | LoopAction, self).WillRunAction(page, tab)
self.LoadJS(tab, 'loop.js')
def RunAction(self, page, tab, previous_action):
try:
assert hasattr(self, 'loop_count') and self.loop_count > 0
selector = self.selector if hasattr(self, 'selector') else ''
tab.ExecuteJavaScript('window.__loopMedia("%s... | nt)
# Check if there is no need to wait for all loops to end
if hasattr(self, 'wait_for_loop') and not self.wait_for_loop:
return
self.WaitForEvent(tab, selector, 'loop', timeout)
except exceptions.EvaluateException:
raise page_action.PageActionFailed('Cannot loop media element(s) wi... |
NeuroRoboticTech/AnimatLabPublicSource | Libraries/AnimatSimPy/Scripts/ErrorTesting.py | Python | bsd-3-clause | 1,130 | 0.023009 | import sys, traceback
def lumberjack():
bright_side_of_death()
def bright_side_of_death():
return tuple()[0]
def testCod | e() :
return tuple()[ | 0]
try:
testCode()
except IndexError:
#exc_type, exc_value, exc_traceback = sys.exc_info()
#print "*** print_tb:"
#traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
#print "*** print_exception:"
#traceback.print_exception(exc_type, exc_value, exc_traceback,
# ... |
square/pylink | pylink/jlock.py | Python | apache-2.0 | 4,881 | 0 | # Copyright 2017 Square, 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,... | that the lockfile exists, but the pid does not
# correspond to a valid process, rem | ove the file.
if not psutil.pid_exists(pid):
os.remove(self.path)
except ValueError as e:
# Pidfile is invalid, so just delete it.
os.remove(self.path)
except IOError as e:
# Something happened while trying to ... |
PW-Sat2/PWSat2OBC | integration_tests/experiment_type.py | Python | agpl-3.0 | 435 | 0 | from enum import unique, IntEnum
@unique
c | lass ExperimentType(IntEnum):
Detumbling = 1
EraseFlash = 2
SunS = 3
LEOP = 4
RadFET = 5
SADS = 6
Sail = 7
Fibo = 8
Payload = 9
Camera = 10
@unique
class StartResult(IntEnum):
Success = 0
Failure = 1
@unique
class IterationResult(IntEnum):
NoResult = 0
Finishe... | Failure = 4
|
zhaopu7/models | deep_speech_2/datasets/librispeech/librispeech.py | Python | apache-2.0 | 6,496 | 0.000154 | """Prepare Librispeech ASR datasets.
Download, unpack and create manifest files.
Manifest file is a json-format file with each line containing the
meta data (i.e. audio filepath, transcript and audio duration)
of each audio file in the data set.
"""
from __future__ import absolute_import
from __future__ import divisio... | -other.tar.gz"
URL_TRAIN_CLEAN_100 = URL_ROOT + "/train-clean-100.tar.gz"
URL_TRAIN_CLEAN_360 = URL_ROOT + "/train-clean-360.tar.gz"
URL_TRAIN_OTHER_500 = URL_ROOT + "/train-other-500.tar.gz"
MD5_TEST_CLEAN = "32fa31d27d2e1cad72775fee3f4849a9"
MD5_TEST_OTHER = "fb5a50374b501bb3bac4815ee91d3135"
MD5_DEV_CLEAN = "42e223... | _TRAIN_CLEAN_100 = "2a93770f6d5c6c964bc36631d331a522"
MD5_TRAIN_CLEAN_360 = "c0e676e450a7ff2f54aeade5171606fa"
MD5_TRAIN_OTHER_500 = "d1a0fd59409feb2c614ce4d30c387708"
parser = argparse.ArgumentParser(
description='Downloads and prepare LibriSpeech dataset.')
parser.add_argument(
"--target_dir",
default=DA... |
doirisks/dori | models/10.7326:0003-4819-148-2-200801150-00005/model_b.py | Python | gpl-3.0 | 1,569 | 0.021033 | """
model_b.py
by Ted Morin
contains a function to predict 2-year Incident Hypertension risks using Weibull beta coefficients from:
10.7326/0003-4819-148-2-200801150-00005
2008 A Risk Score for Predicting Near-Term Incidence of Hypertension
Framingham Heart Study
translated and adapted from from FHS online risk calc... | with Hypert. History"
years mm Hg mm Hg kg/m^2
bool int/float int/float int/float int/float bool int
"""
def model(ismale,age,sbp,dbp,bmi,smoker,parentalht):
# imports
import numpy as np
# betas and | Weibull scale factor
betas = np.array([
22.949536, #intercept
-0.202933, #female gender
-0.156412, #age
-0.033881, #bmi
-0.05933, #sbp
-0.128468, #dbp
-0.190731, #smoker
-0.166121, ... |
inclement/python-for-android | pythonforandroid/bootstraps/webview/__init__.py | Python | mit | 5,904 | 0.003726 | from pythonforandroid.toolchain import Bootstrap, shprint, current_directory, info, warning, ArchARM, info_main
from os.path import join, exists, curdir, abspath
from os import walk
import glob
import sh
class WebViewBootstrap(Bootstrap):
name = 'webview'
recipe_depends = ['genericndkbuild', ('python2', 'pyth... | info('priva | te/lib does not exist, making')
shprint(sh.cp, '-a', join('python-install', 'lib'), 'private')
shprint(sh.mkdir, '-p', join('private', 'include', 'python2.7'))
# AND: Copylibs stuff should go here
if exists(join('libs', arch.arch, 'libpymodules.so')):... |
jgmize/bedrock | bedrock/firefox/tests/test_base.py | Python | mpl-2.0 | 19,618 | 0.000561 | # -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
from django.core.cache import caches
from django.http import HttpResponse
from django.... | ('/en-US/firefox/whatsnew/')
self.view(req, version='35.0a2')
| template = render_mock.call_args[0][1]
eq_(template, ['firefox/dev-whatsnew.html'])
# begin 42.0 whatsnew tests
@override_settings(DEV=True)
def test_fx_42_0(self, render_mock):
"""Should use tracking protection whatsnew template for 42.0"""
req = self.rf.get('/en-US/firefox/wha... |
vanyh/handkeinzungen-app | vocabs/filters.py | Python | mit | 1,239 | 0.000807 | import django_filters
from dal import autocomplete
from .models import SkosConcept, SkosConceptScheme
django_filters.filters.LOOKUP_TYPES = [
('', '---------'),
('exact', 'Is equal to'),
('iexact', 'Is equal to (case insensitive)'),
| ('not_exact', 'Is not equal to'),
('lt', 'Lesser than/before'),
('gt', 'Greater than/after'),
('gte', 'Greater than or equal to'),
('lte', 'Lesser than or equal to'),
('startswith', 'Starts with'),
('endswith', 'Ends with'),
('contains', 'Contains'),
('icontains', 'Contains (case insensi... | o_filters.ModelMultipleChoiceFilter(
widget=autocomplete.Select2Multiple(url='vocabs-ac:skosconcept-autocomplete'),
queryset=SkosConcept.objects.all(),
lookup_expr='icontains',
label='PrefLabel',
help_text=False,
)
scheme = django_filters.ModelMultipleChoiceFilter(
... |
deepmind/acme | acme/jax/running_statistics.py | Python | apache-2.0 | 13,577 | 0.006629 | # Lint as: python3
# Copyright 2018 DeepMind Technologies Limited. 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
#
# ... | or
arrays and tuples) that uniquely identifies a subtree in the nested structure.
| See
https://tree.readthedocs.io/en/latest/api.html#tree.map_structure_with_path
for more details.
"""
def _is_prefix(a: Path, b: Path) -> bool:
"""Returns whether `a` is a prefix of `b`."""
return b[:len(a)] == a
@chex.dataclass(frozen=True)
class NestedMeanStd:
"""A container for running statistics (me... |
Friedbaumer/litecoin | test/functional/test_runner.py | Python | mit | 20,245 | 0.003014 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
f... | E_BITCOIND")
if config["environment"]["EXEEXT"] == ".exe" and not args.force:
# https://github.com/bitcoin/bitcoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
# https://github.com/bitcoin/bitcoin/pull/5677#issuecomment-136646964
print("Tests currently disabled on Windows by default. Use... | enable")
sys.exit(0)
if not (enable_wallet and enable_utils and enable_bitcoind):
print("No functional tests to run. Wallet, utils, and litecoind must all be enabled")
print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
sys.exit(0)
# Bui... |
sunze/py_flask | venv/lib/python3.4/site-packages/celery/tests/contrib/test_methods.py | Python | mit | 840 | 0 | from __future__ import absolute_import
from celery.contrib.methods import tas | k_method, task
from celery.tests.case import AppCase, patch
class test_task_method(AppCase):
def test_task_method(self):
class X(object):
def __init__(self):
self.st | ate = 0
@self.app.task(shared=False, filter=task_method)
def add(self, x):
self.state += x
x = X()
x.add(2)
self.assertEqual(x.state, 2)
x.add(4)
self.assertEqual(x.state, 6)
self.assertTrue(X.add)
self.assertIs(x.add.__s... |
mitliagkas/pyliakmon | main.py | Python | mit | 931 | 0.017186 | import numpy as np
from numpy import linalg as la
import time
import subprocess
from streaming import Oja
from streaming import BlockOrthogonal
import MovieLens
if __name__ == "__main__":
#oja=Oja(Ceta=1e-3,k=1,stream=MovieLens.UserStream())
boi1=BlockOrthogonal(k=1,stream=MovieLens.User... | datasets/ml-10M100K/ratingsTab21.dat'))
boi2=BlockOrthogonal(k=1,stream=MovieLens.UserStream(sparse=False, file='/var/datasets/ml-10M100K/ratingsTab22.dat'))
t0 = time.time()
oneDone=False
twoDone=False
while not (oneDone and twoDone):
try:
boi1.next()
except StopI... | e
try:
boi2.next()
except StopIteration:
twoDone=True
t1 = time.time()
total = t1-t0
print "Total time: ", total
print np.dot(boi1.getEstimate().T,boi2.getEstimate())
|
oe-alliance/e2openplugin-CrossEPG | src/enigma2/python/crossepg_main.py | Python | lgpl-2.1 | 2,743 | 0.024426 | from __future__ import print_function
from __future__ import absolute_import
from enigma import *
from Screens.MessageBox import MessageBox
from Screens.Standby import TryQuitMainloop
from . crossepglib import *
from . crossepg_downloader import CrossEPG_Downloader
from . crossepg_importer import CrossEPG_Importer
fr... | wnloader.\nWould You like to do it now ?"), type=MessageBox.TYPE_YESNO)
else:
self.config.deleteLog()
| self.session.openWithCallback(self.downloadCallback, CrossEPG_Downloader, self.config.providers)
def configureCallback(self, result):
if result is True:
self.session.open(CrossEPG_Setup)
def loaderAsPlugin(self, session):
self.session = session
CrossEPG_Auto.instance.lock = True
CrossEPG_Auto.instance.st... |
mganeva/mantid | scripts/test/SANS/gui_logic/settings_diagnostic_presenter_test.py | Python | gpl-3.0 | 3,279 | 0.00183 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | ll_count == 2)
def test_that_updates_rows_when_triggered(self):
parent_presenter = create_run_tab_present | er_mock()
view = create_mock_settings_diagnostic_tab()
presenter = SettingsDiagnosticPresenter(parent_presenter)
presenter.set_view(view)
self.assertTrue(view.update_rows.call_count == 1)
presenter.on_update_rows()
self.assertTrue(view.update_rows.call_count == 2)
de... |
mfherbst/spack | var/spack/repos/builtin/packages/libunwind/package.py | Python | lgpl-2.1 | 1,797 | 0.001113 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produce | d at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All r | ights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the... |
after1990s/little_utils | EveItem/main.py | Python | apache-2.0 | 6,571 | 0.005942 | # -*- coding: utf-8 -*-
import httplib
import json
import yaml
from mysql import *
from industry import industry_typeid
from materials import *
# def printGroups(resJson):
# items = resJson['items']
# for i in items:
# print "name: " + i['name'] + " url:" + i['href']
#
# def printCategory(resJson):
# ... | if len(GetMaterialsByTypeid(i)) > 1 else None for i in range(178, 42234)])
# for i in range(3446, 42234):
# if len(GetMaterialsByTypeid(i)) > 1:
# avail_typ | eid.append(i);
profit_list = [calc_profit_by_typeid(i) for i in industry_typeid]
profit_list = [z for z in profit_list if z is not None]
t2_profit_list = filter(lambda x: "II" in x['item_name'], profit_list)
t1_profit_list = filter(lambda x: "II" not in x['item_name'] and "I" in x['item_name'], profi... |
emd/mitpci | tests/pci_tests/signal_tests.py | Python | gpl-2.0 | 931 | 0 | from nose import tools
import numpy as np
import filters
from mitpci.pci.signal import Phase
def test_Phase__init__():
shot = 171110
channel = [8]
# Needs to receive `filt` that is `None` or `filters.fir.Kaiser`
tools.assert_raises(
ValueError,
Phase, *[shot, channel], **{'filt': {}})... | el retrievals and that the records are arranged
# as expected
tlim = [1, 2]
Ph7 = Phase(shot, 7, tlim=tlim)
Ph8 = Phase(shot, 8, tlim=tlim)
Ph = Phase(shot, [7, 8], tlim=tlim)
np.testing.assert_equal(P | h7.x, Ph.x[0, :])
np.testing.assert_equal(Ph8.x, Ph.x[1, :])
return
|
tosdr/tosback2 | code/get_history_from_git.py | Python | gpl-2.0 | 1,371 | 0.042305 | import sys
from git import *
if(len(sys.argv) != 4):
print "Usage: python get_history_from_git.py REPO_LOCATION REPO_PATH BRANCH"
sys.exit()
def printCommit(commitHash, commitDate, printed):
if not printed:
print "\t{"
else:
print ",\n\t{"
print '\t\tcommitHash: "' + commitHash + '",'
print "\t\tcommitDate:... | mit
currentCommit = currentCommit.parents[0]
else:
currentC | ommit = None
print "\n]"
except:
print "[ ]"
getHistoryFromGit(sys.argv[1], sys.argv[2], sys.argv[3]) |
scarescrow/LongPollChat | djangochat/wsgi.py | Python | mit | 398 | 0 | """
WSGI config for djangochat p | roject.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_applicati | on
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangochat.settings")
application = get_wsgi_application()
|
LCAS/teaching | cmp3103m-code-fragments/scripts/image_publisher.py | Python | mit | 532 | 0.00188 | #!/usr/bin/env python
import rospy
import cv2
from s | ensor_msgs.msg import Image
from cv_bridge import CvBridge
class image_publisher:
def __init__(self):
self.bridge = CvBridge()
self.image_pub = rospy.Publisher('/image', Image, latch=True)
def publish(self, filename):
cv_image = cv2.imread(filename)
self.image_pub.publish(se... | ('image_converter', anonymous=True)
ic.publish('../blofeld.jpg')
rospy.spin()
|
sajeeshcs/nested_quota_latest | nova/api/openstack/wsgi.py | Python | apache-2.0 | 44,219 | 0.000068 | # Copyright 2013 IBM Corp.
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LIC... | pi_version_request = api_version.APIVersionRequest(
hdr_string)
| # Check that the version requested is within the global
# minimum/maximum of supported API versions
if not self.api_version_request.matches(
api_version.min_api_version(),
api_version.max_api_version()):
ra... |
nyrocron/eve-wspace | evewspace/Alerts/method_registry.py | Python | apache-2.0 | 2,115 | 0.002837 | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# 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... | ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A registry module for registering alert methods.
"""
from django.db import models
from method_base import AlertMethodBase
class MethodRegistry(dict):
"""
Dict wi... | name):
method = self[name]
del self[name]
def register(self, name, module):
"""
Registers a method with its name and module.
"""
if not issubclass(module, AlertMethodBase):
raise AttributeError("Module given to MethodRegistry not valid")
if not n... |
rajul/tvb-framework | setup.py | Python | gpl-2.0 | 2,824 | 0.006728 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http:/... | OUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details. You should have received a copy of the | GNU General
# Public License along with this program; if not, you can download it here
# http://www.gnu.org/licenses/old-licenses/gpl-2.0
#
#
# CITATION:
# When using The Virtual Brain for scientific publications, please cite it as follows:
#
# Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide,
#... |
matheuscas/pyfuzzy_toolbox | pyfuzzy_toolbox/evaluation.py | Python | bsd-3-clause | 550 | 0.018182 | def precision(TP, FP):
return (TP / (TP + FP)) if (TP + FP) > 0 else 0
def recall(TP, FN):
return (TP / (TP + FN)) if (TP + FN) > 0 else 0
def f1(TP, FP, TN, FN):
return ((2 * (((TP / (TP + FP)) * (TP / (TP + FN))) / ((TP / (TP + FP)) + (TP / (TP + FN)))))) if (TP + | FP) > 0 and (TP + FN) > 0 else 0
def accuracy(TP, FP, TN, FN):
return ((TP + TN) / (TP + TN + FP + FN)) if (TP + TN + FP + FN) > 0 else 0
def tpr(TP, FN):
return (TP / (TP + FN)) if (TP + FN) > 0 else 0
def tnr(TN, FP):
return (TN / (TN + FP)) if (TN + FP) | > 0 else 0
|
matrix-org/synapse | synapse/rest/client/profile.py | Python | apache-2.0 | 5,704 | 0.001052 | # Copyright 2014-2016 OpenMarket Ltd
#
# 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 w... | ser, requester_user)
displayname = await self.profile_handler.get_displayname(user)
avatar_url = await self.profile_handler.get_avatar_url(user)
ret = {}
if displayname is not None:
ret["displayname"] = displayname
if avatar_url is not None:
| ret["avatar_url"] = avatar_url
return 200, ret
def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
ProfileDisplaynameRestServlet(hs).register(http_server)
ProfileAvatarURLRestServlet(hs).register(http_server)
ProfileRestServlet(hs).register(http_server)
|
eminorhan/inevitable-probability | nin_nhu/ninnhu_kalman_filtering_expt.py | Python | gpl-3.0 | 5,329 | 0.015575 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 28 16:52:18 2016 by emin
"""
import os
import sys
import theano
import theano.tensor as T
import numpy as np
from lasagne.layers import InputLayer, ReshapeLayer, DenseLayer
from generators import KalmanFilteringTaskFFWD
import lasagne.layers
import lasagne.nonlinearities
i... | training an old model, uncomment below
# npzfile_lout = | np.load('kf_lout_trained_model.npz')
# npzfile_lrec = np.load('kf_lrec_trained_model.npz')
# lasagne.layers.set_all_param_values(l_out,[npzfile_lout['arr_0'],npzfile_lout['arr_1'],npzfile_lout['arr_2'],npzfile_lout['arr_3'],npzfile_lout['arr_4'],npzfile_lout['arr_5']])
# lasagne.layers.set_all_param_v... |
pawel-wlk/ecommerce-site | mysite/shop/migrations/0003_auto_20170904_1553.py | Python | mit | 550 | 0 | # -*- coding: utf-8 -*-
# Generate | d by Django 1.11.4 on 2017-09-04 15:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_category'),
]
operations = [
migrations.RemoveField(
model_name='category',
... | grations.AddField(
model_name='item',
name='category',
field=models.ManyToManyField(to='shop.Category'),
),
]
|
lillian-gardenia-seabreeze/sappho | tests/test_layers.py | Python | mit | 2,612 | 0 | from __future__ import absolute_import
import pygame
import sappho.layers
from .common import compare_surfaces
class TestSurfaceLayers(object):
"""
Do not need to test create_surface_layers(), because
it's inherent to SurfaceLayers' initialization and
everything else tested.
"""
NUMBER_OF... | 0))
surface_layers[1].blit(rect1, rect1pos)
surface_layers[2].blit(rect2, rect2pos)
surface_layers[3].blit(rect3, rect3pos)
# Render to the target surface
su | rface_layers.render()
# Compare the two surfaces
assert compare_surfaces(self.target_surface, test_surface)
|
ssaini4/RoboticLamp | main/haarDetection.py | Python | bsd-2-clause | 6,327 | 0.0471 | # **********************************************
# * Robotic Lamp
# * 26 March 2017
# * Saksham Saini, James Jia and Dhruv Diddi
# **********************************************
import cv2
import sys
sys.path.append('/home/pi/Desktop/RoboticLamp/main/Adafruit_Python_PCA9685/Adafruit_PCA9685')
import numpy as np
import... | derp"
inputStr = "RM.noLock()\n"
led.send(inputStr)
gestureListCounter += 1
gestureListCounter %= 4
gestureCounter = np.zeros(10)
frameNumber = 0
detectedGesture = np.zeros(5)
cv2.imshow('img',gray)
k = cv2.waitKey(10)
if | k == 27:
break
|
vgrem/SharePointOnline-REST-Python-Client | office365/sharepoint/attachmentfile_collection.py | Python | mit | 1,876 | 0.002665 | from office365.runtime.client_object_collection import ClientObjectCollection
from office365.runtime.client_query import ServiceOperationQuery
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office365.sharepoint.attachmentfile import AttachmentFile
from office365.sharepoi... | tion
from office365.sharepoint.file import File
class AttachmentfileCollection(ClientObjectCollection):
"""Represents a collection of AttachmentFile resources."""
def __init__(self, context, resource_path=None):
super(AttachmentfileCollection, self).__init__(context, AttachmentFile, resource_path)
... | tachment_file_information, dict):
attachment_file_information = AttachmentfileCreationInformation(
attachment_file_information.get('filename'),
attachment_file_information.get('content')
)
target_file = File(self.context)
self.add_child(target_fil... |
google-research/language | language/labs/drkit/hotpotqa/preprocessing/convert_wikidata_to_mrqa.py | Python | apache-2.0 | 5,508 | 0.007625 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | _pattern % ii
out_file = FLAGS.out_pattern % ii
print("Input %s Output %s" % (in_file, out_file))
rel2items = collections.defaultdict(list)
with open(in_file) as f, gzip.open(out_file, "wt") as fo:
for line in tqdm(f):
item = json.loads(line.strip())
out = _convert_question(item)
... | = item["id"] + "_inv"
out_i = _convert_question(item, inverse=True)
fo.write(json.dumps(out_i) + "\n")
rel2items[out["qas"][0]["relation"]].append(out)
rel2items[out_i["qas"][0]["relation"]].append(out_i)
out_file = FLAGS.out_pattern % -1
print("Relation negatives output %s... |
laputian/dml | equation/nnfromscratch_eq_func.py | Python | mit | 5,297 | 0.011327 | import cPickle as pickle
import matplotlib.pyplot as plt
import numpy as np
nr_examples= 200
modelfilename = '../data/nnfromscratch_eq' + str(nr_examples) + '.pkl'
def activation(x):
return np.tanh(x) #1/ (1 + np.exp(-x)) -0.5 #np.tanh(x) # np.log(1 + np.exp(x))
def the_function(x):
return np.sin(2*x)
nn_... | er function to evaluate the tot | al loss on the dataset
def calculate_loss(model, X = inputs):
W1, b1, W2, b2 = model['W1'], model['b1'], model['W2'], model['b2']
# Forward propagation to calculate our predictions
z1 = X.dot(W1) + b1
a1 = activation(z1)
z2 = a1.dot(W2) + b2
#exp_scores = np.exp(z2)
#probs = exp_scores / np.... |
hthompson6/a10-neutron-lbaas | a10_neutron_lbaas/v2/wrapper_certmgr.py | Python | apache-2.0 | 2,706 | 0.003695 | # Copyright 2015, A10 Networks
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | e, private_key, inte | rmediates=None,
private_key_passphrase=None, expiration=None,
name='A10-LBaaS TLS Cert',
project_id=None, **kwargs):
try:
return self.certmgr.store_cert(certificate, private_key,
intermediates=interme... |
BrandonY/python-docs-samples | pubsub/cloud-client/subscriber.py | Python | apache-2.0 | 5,328 | 0 | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | )
subscription_path = subscriber | .subscription_path(
project, subscription_name)
def callback(message):
print('Received message: {}'.format(message))
message.ack()
# Limit the subscriber to only have ten outstanding messages at a time.
flow_control = pubsub_v1.types.FlowControl(max_messages=10)
subscriber.subs... |
mhbu50/erpnext | erpnext/patches/v12_0/update_item_tax_template_company.py | Python | gpl-3.0 | 419 | 0 | import frappe
def execute():
frappe.reload_doc('accounts', 'doctype', 'item_tax_template')
item_tax_tem | plate_list = frappe.get_list('Item Tax Template')
| for template in item_tax_template_list:
doc = frappe.get_doc('Item Tax Template', template.name)
for tax in doc.taxes:
doc.company = frappe.get_value('Account', tax.tax_type, 'company')
break
doc.save()
|
aredmond/djangular | code/app1/serializers.py | Python | mit | 738 | 0.001355 | from rest_framework import serializers
from django.contrib.auth.models import User
from app1.models import Tweet
class TweetSerializer(serializers.ModelSerializer):
user = serializers.Field(source='user')
class Meta:
model = Tweet
fields = ('text', 'user', 'timestamp')
def validate_text... | serializers.ModelSerializer):
tweets = TweetSerializer(many=True, source="tweet_set")
class Meta:
| model = User
fields = ('username', 'first_name', 'last_name', 'last_login', 'tweets')
|
project-asap/IReS-Platform | panic/panic-deployer/setup.py | Python | apache-2.0 | 260 | 0.003846 | from setuptools import setup, find_packages
setup(
name="panic-deployer",
versi | on="0.1",
packages=find_packages(),
requires= | ['kamaki',
'paramiko'],
author='Giannis Giannakopoulos',
author_email='ggian@cslab.ece.ntua.gr'
) |
electron/electron | script/verify-mksnapshot.py | Python | mit | 4,821 | 0.011408 | #!/usr/bin/env python
from __future__ import print_function
import argpar | se
import glob
import os
import platform
import shutil
import subprocess
import sys
from lib.util import get_electron_branding, rm_rf, scoped_cwd
PROJECT_NAME = get_electron_branding()['project_name']
PRODUCT_NAME = get_electron_branding()['product_name']
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(... | p.js')
def main():
args = parse_args()
source_root = os.path.abspath(args.source_root)
initial_app_path = os.path.join(source_root, args.build_dir)
app_path = create_app_copy(initial_app_path)
returncode = 0
try:
with scoped_cwd(app_path):
if args.snapshot_files_dir is None:
with open(o... |
xzturn/tensorflow | tensorflow/python/keras/engine/training_utils.py | Python | apache-2.0 | 81,689 | 0.006598 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | thon.keras import losses
from tensorflow.python.keras import metrics as metrics_module
from tensorflow.python.keras.utils import data_utils
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils import losses_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.op... | w.python.ops import math_ops
from tensorflow.python.ops.losses import util as tf_losses_utils
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import nest
from tensorflow.python.util import tf_inspect
from tensorflow.python.util.compat import collections_abc
@six.add_metaclass(... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractMajimeHomeBlog.py | Python | bsd-3-clause | 1,139 | 0.028144 | def extractMajimeHomeBlog(item):
'''
Parser for 'majime.home.blog'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loitero... | if item['tags'] == ['Uncategorized | ']:
chp_prefixes = [
('Chapter ', 'Strange Grief Wants to Retire ~The Weakest Hunter’s Hero Dream~', 'translated'),
('Manowa', 'Manowa Mamono Taosu Nouryoku Ubau Watashi Tsuyokunaru', 'translated'),
('Cat ', 'Me and My Beloved Cat (Girlfriend)', ... |
myarjunar/QGIS | python/plugins/processing/algs/qgis/RasterLayerStatistics.py | Python | gpl-2.0 | 4,669 | 0.000643 | # -*- coding: utf-8 -*-
"""
***************************************************************************
RasterLayerStatistics.py
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
****************... | objects.getObjectFromUri(uri)
values = raster.scanraster(layer, feedback)
n = 0
nodata = 0
mean = 0
M2 = 0
sum = 0
minvalue = None
maxvalue = None
for v in values | :
if v is not None:
sum += v
n = n + 1
delta = v - mean
mean = mean + delta / n
M2 = M2 + delta * (v - mean)
if minvalue is None:
minvalue = v
maxvalue = v
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.