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 |
|---|---|---|---|---|---|---|---|---|
sbg/sevenbridges-python | sevenbridges/models/compound/tasks/batch_group.py | Python | apache-2.0 | 454 | 0 | from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField, DictField
| class BatchGroup(Resource):
"""
Batch group for a batch task.
Represents the group that is assigned to the child task
from the batching criteria that was used when the task was started.
"""
value = StringField(read_only=True)
fields = DictField(read_only=True)
def __str__(self):
... | |
TheCoderNextdoor/DjangoSites | django_tut/website/music/views.py | Python | gpl-3.0 | 3,632 | 0.020099 | # from django.shortcuts import render, get_object_or_404
# from .models import Album, Song
# def index(request):
# all_albums = Album.objects.all()
# context = {
# 'all_albums':all_albums,
# }
# return render(request, 'music/index.html', context)
# def detail(request, album_id):
... | ||
StoDevX/cs251-toolkit | cs251tk/specs/load.py | Python | mit | 2,467 | 0.001621 | import sys
from logging import warning
from glob imp | ort iglob
import json
import os
import shutil
from ..common import chdir, run
from .cache import cache_specs
from .dirs import get_specs_dir
def load_all_specs(*, basedir=get_specs_dir(), skip_update_check=True):
os.makedirs(basedir, exist_ok=True)
if not skip_update_check:
with chdir(basedir):
... | uccess':
print("Error fetching specs", file=sys.stderr)
_, res, _ = run(['git', 'log', 'HEAD..origin/master'])
if res != '':
print("Spec updates found - Updating", file=sys.stderr)
with chdir(basedir):
run(['git', 'pull', 'origin', 'master'])... |
edisondotme/motoPi | main/apps.py | Python | mit | 80 | 0.0125 | from django.apps import AppConfig
|
class MainConfig(AppConfi | g):
name = 'main'
|
jk977/twitch-plays | bot/tests/commands.py | Python | gpl-3.0 | 1,035 | 0.002899 | import unittest
from chat.commands.commandlist import CommandList
from chat.command import Command
from tests.structs.dummychat import DummyChat
class TestCommands(unittest.TestCase):
| def setUp(self):
self.chat = DummyChat()
def test_get(self):
command = CommandList.get('help', self.chat, 'message')
self.assertTrue(command and isinstance(command, Command), 'Command get failed')
def test_validate(self):
fail_msg = 'Command validate failed'
self.a... | ommandList.validate('!help'), fail_msg)
self.assertTrue(CommandList.validate('song'), fail_msg)
self.assertTrue(CommandList.validate('!song'), fail_msg)
self.assertTrue(CommandList.validate('restart'), fail_msg)
self.assertTrue(CommandList.validate('!restart'), fail_msg)
self.ass... |
2gis/pytestrail | testrail/testcase.py | Python | mit | 474 | 0 | class TestRailTestCase:
def __init__(self, title, section, suite, steps):
self.title = title
self.secti | on_name = section
self.suite_name = suite
self.steps = steps
self.type_id = 1
self.priority_id = 4
def to_json_dict(self):
return {
't | itle': self.title,
'type_id': self.type_id,
'priority_id': self.priority_id,
'custom_steps_separated': self.steps
}
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/core/mail/__init__.py | Python | bsd-3-clause | 5,072 | 0.002957 | """
Tools for sending email.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
# Imported for backwards compatibility, and for the sake
# of a cleaner namespace. These symbols used to be in
# django/core/mail.py before the int... | SSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = connection or get_connection(username=auth_user,
password=auth_password,
... | for subject, message, sender, recipient in datatuple]
return connection.send_messages(messages)
def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Sends a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
... |
ruamel/ordereddict | test/unit/test_support.py | Python | mit | 17,653 | 0.003852 | """Supporting definitions for the Python regression tests."""
if __name__ != 'test_support':
raise ImportError, 'test_support must be imported from the test package'
import sys
class Error(Exception):
"""Base class for regression test exceptions."""
class TestFailed(Error):
"""Test failed."""
class Tes... | ng multiple
tests and we don't try multiple ports, the test can fails. This
makes the test more robust."""
import socket, errno
# some random ports that hopefully no one is listening on.
for port in [preferred_port, 9907, 10243, 32999]:
| try:
sock.bind((host, port))
return port
except socket.error, (err, msg):
if err != errno.EADDRINUSE:
raise
print >>sys.__stderr__, \
' WARNING: failed to listen on port %d, trying another' % port
raise TestFailed, 'unab... |
msabramo/pycobertura | tests/test_cobertura.py | Python | mit | 7,957 | 0.000754 | import mock
import lxml.etree as ET
from .utils import make_cobertura
def test_parse_path():
from pycobertura import Cobertura
xml_path = 'foo.xml'
with mock.patch('pycobertura.cobertura.os.path.exists', return_value=True):
with mock.patch('pycobertura.cobertura.ET.parse') as mock_parse:
... | issed_statements_by_class_name():
cobertura = make_cobertura()
expected_missed_statements = {
'Main': [],
'search.BinarySearch': [24],
'search.ISortedArraySearch': [],
'search.LinearSearch': [19, 24],
}
for class_name in cobertura.classes():
assert cobertura.miss... | \
expected_missed_statements[class_name]
def test_list_packages():
cobertura = make_cobertura()
packages = cobertura.packages()
assert packages == ['', 'search']
def test_list_classes():
cobertura = make_cobertura()
classes = cobertura.classes()
assert classes == [
'Mai... |
thelok/crits_scripts | crits/core/managament/commands/get_indicator_types.py | Python | mit | 4,701 | 0.005956 | from optparse import make_option
from django.core.management.base import BaseCommand
from crits.core.mongo_tools import mongo_connector
import pprint
class Command(BaseCommand):
"""
Gets a count of indicator types and object types in CRITs
"""
help = "Gets a count of indicator types and object type... | bjects.type"
}
}
},
"count": {"$sum": 1}
}
}
]
if sort_count is True:
pipe.append({"$sort": {"count": 1}})
else:
pipe.append({"$sort": {"_id": 1}})
... | ollection, pp):
results = {}
for collection in self.all_object_collections:
object_types = self.aggregate_object_for_collection(collection, sort_count)
results[collection] = object_types
if is_agg_per_collection:
for collection in self.all_object_collection... |
areitz/pants | src/python/pants/backend/jvm/tasks/scala_repl.py | Python | apache-2.0 | 2,743 | 0.008385 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generator | s, nested_scopes, print_function,
unicode_literals, with_statement) |
from pants.backend.jvm.tasks.jvm_task import JvmTask
from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin
from pants.base.target import Target
from pants.console.stty_utils import preserve_stty_settings
from pants.java.util import execute_java
class ScalaRepl(JvmToolTaskMixin, JvmTask):
@class... |
odahoda/noisicaa | noisicaa/builtin_nodes/control_track/track_ui.py | Python | gpl-2.0 | 15,641 | 0.000895 | #!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# 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 y... | self.track.highlightedPoint().point.value = new_value
evt.accept()
return
super().mouseReleaseEvent(evt)
def mouseDoubleClickEvent(self, evt: QtGui.QMouseEvent) -> None:
if evt.button() == Qt.LeftButton and evt.modifiers() == Qt.N | oModifier:
# If the first half of the double click initiated a move,
# cancel that move now.
if self.__moving_point is not None:
self.track.setPointPos(self.__moving_point, self.__moving_point_original_pos)
self.__moving_point = None
time ... |
Eficent/purchase-workflow | procurement_purchase_no_grouping/__manifest__.py | Python | agpl-3.0 | 662 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 AvanzOsc (http://www.avanzosc.es)
# Copyright 2015-2017 - Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "Procurement Purchase No Grouping",
"version": "10.0.1.0.0",
"author": "AvanzOSC,"
... | ativa,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/purchase-workflow",
"category": "Procurements",
"depends": [
'purchase',
'procurement',
],
"data": [
'views/product_category_view.xml',
],
'installable': True,
| 'license': 'AGPL-3',
}
|
GoogleCloudPlatform/tf-estimator-tutorials | 00_Miscellaneous/model_optimisation/optimize_graph_keras.py | Python | apache-2.0 | 7,518 | 0.009178 | # Copyright 2018 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 by applicable law or a... | c language governing permissions and
# limitations under the License.
""" Extract from notebook for Serving Optimization on Keras """
from __future__ import print_function
from datetime import datetime
import os
import sh
import sys
import tensorflow as tf
from tensorflow import data
from tensorflow.pyth | on.saved_model import tag_constants
from tensorflow.python.tools import freeze_graph
from tensorflow.python import ops
from tensorflow.tools.graph_transforms import TransformGraph
from inference_test import inference_test, load_mnist_keras
from optimize_graph import (run_experiment, get_graph_def_from_saved_model,
... |
saeki-masaki/cinder | cinder/volume/drivers/dell/dell_storagecenter_iscsi.py | Python | apache-2.0 | 7,182 | 0 | # Copyright 2015 Dell 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 agree... | ation.iscsi_port
# Three cases that should all be satisfied with the
| # same return of Target_Portal and Target_Portals.
# 1. Nova is calling us so we need to return the
# Target_Portal stuff. It should ignore the
# Target_Portals stuff.
# 2. OS brick is calling us i... |
attugit/cxxjson | test/conftest.py | Python | mit | 587 | 0.001704 | from pytest import fixture
from itertools import combinations
import msgpack as pymsgpack
values = [
42, 7, 3.14, 2.71, 'lorem', 'ipsum', True, False, None, b'lorem', b'ipsum', [], [
'lorem', 42, 3.14, True, None, ['ipsum']], dict(), {
' | lorem': 'ipsum', 'dolor': 42, 'sit': 3.14, 'amet': [
| True, None], 'consectetur':{
'adipisicing': 'elit'}}]
pairs = tuple(combinations(values, 2))
@fixture
def cxxjson():
from cxx import json
return json
@fixture
def cxxmsgpack():
from cxx import msgpack
return msgpack
|
pkill-nine/qutebrowser | tests/conftest.py | Python | gpl-3.0 | 6,876 | 0.000873 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free S... | ken with QtWebEngine on Windows"),
]
for searched_marker, condition, default_reason in markers:
marker = item.get_marker(search | ed_marker)
if not marker or not condition:
continue
if 'reason' in marker.kwargs:
reason = '{}: {}'.format(default_reason, marker.kwargs['reason'])
del marker.kwargs['reason']
else:
reason = default_reason + '.'
skipif_marker = pytest.mark... |
airbnb/airflow | tests/api_connexion/schemas/test_event_log_schema.py | Python | apache-2.0 | 4,612 | 0.000867 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | "event": "TEST_EVENT_2",
"dag_id": "TEST_DAG_ID",
"task_id": "TEST_TASK_ID",
"execution_date": self.default | _time,
"owner": 'airflow',
"when": self.default_time2,
"extra": None,
},
],
"total_entries": 2,
},
)
|
melviso/phycpp | beatle/activity/models/ui/dlg/cc/Member.py | Python | gpl-2.0 | 14,333 | 0.001535 | """Subclass of NewMember, which is generated by wxFormBuilder."""
import copy
import wx
from beatle import model
from beatle.lib import wxx
from beatle.activity.models.ui import ui as ui
# Implementing NewMember
class MemberDialog(ui.NewMember):
"""
This dialog allows to setup data member of class
or s... | m_textCtrl7.Show(True)
self.m_textCtrl7.Enable(True)
self.m_textCtrl7.SetValue(str(ti._array_size))
else:
self.m_textCtrl7.SetValue('0')
self.m_che | ckBox51.SetValue(member._bitField)
if ti._type_args is not None:
self.m_staticText67.Enable(True)
self.m_template_args.Enable(True)
self.m_staticText68.Enable(True)
self.m_template_args.SetValue(ti._type_args)
if member._bitField is True:
self... |
sxjscience/tvm | python/tvm/micro/session.py | Python | apache-2.0 | 4,567 | 0.002847 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ef __enter__(self):
"""Initialize this session and establish an RPC session with the on-device RPC server.
Returns
-------
Session :
Returns self.
"""
if self.flasher is not None:
self.transport_context_manager = self.flasher.flash(self.binary)
... | __()
self._rpc = RPCSession(
_rpc_connect(self.session_name, self.transport.write, self.transport.read)
)
self.context = self._rpc.cpu(0)
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
"""Tear down this session and associated RPC session reso... |
vmayoral/basic_reinforcement_learning | tutorial5/tests/theano_mnist_mlp.py | Python | gpl-3.0 | 14,310 | 0.001048 | """
This tutorial introduces the multilayer perceptron using Theano.
A multilayer perceptron is a logistic regressor where
instead of feeding the input to the logistic regression you insert a
intermediate layer, called the hidden layer, that has a nonlinear
activation function (usually tanh or sigmoid) . One can use ... | n=T.tanh
)
# The logistic regression layer gets as input the hidden units
# of the hidden lay | er
self.logRegressionLayer = LogisticRegression(
input=self.hiddenLayer.output,
n_in=n_hidden,
n_out=n_out
)
# end-snippet-2 start-snippet-3
# L1 norm ; one regularization option is to enforce L1 norm to
# be small
self.L1 = (
... |
cjh1/tomviz | acquisition/tests/conftest.py | Python | bsd-3-clause | 1,440 | 0 | import pytest
import requests
import time
from threading import Thread
from bottle import default_app, WSGIRefServer
from tomviz.acquisition import server
class Server(Thread):
def __init__(self, dev=False, port=9999):
super(Server, self).__init__()
self.host = 'localhost'
self.port = por... |
self.url = '%s/acquisition' % self.base_url
self.dev = dev
self._server = WSGIRefServer(host=self.host, port=self.port)
def run(self):
self | .setup()
self._server.run(app=default_app())
def start(self):
super(Server, self).start()
# Wait for bottle to start
while True:
try:
requests.get(self.base_url)
break
except requests.ConnectionError:
time.sleep... |
google-research/language | language/compgen/nqg/tasks/compare_predictions.py | Python | apache-2.0 | 1,653 | 0.008469 | # 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 ... | FINE_string("gold", "", "tsv file containing gold targets.")
flags.DEFINE_string("predictions", "", "txt file with predicted targets.")
def main(unused_argv):
gold_examples = tsv_utils.read_tsv(FLAGS.gold)
preds = []
with gfile.GFile(FLAGS.predictions, "r") as f:
for line in f:
preds.append(line.rst... |
if pred == gold_example[1]:
correct += 1
else:
incorrect += 1
print("Incorrect for example %s.\nTarget: %s\nPrediction: %s" %
(gold_example[0], gold_example[1], pred))
print("correct: %s" % correct)
print("incorrect: %s" % incorrect)
print("pct: %s" % str(float(correct) / f... |
noyeitan/cubes | cubes/common.py | Python | mit | 9,653 | 0.002695 | # -*- encoding: utf-8 -*-
"""Utility functions for computing combinations of dimensions and hierarchy
levels"""
from __future__ import absolute_import
import itertools
import sys
import re
import os.path
import decimal
import datetime
import json
from collections import OrderedDict
from .errors import *
from . imp... | `separator`, create sub-dictionaries as necessary"""
result = {}
for key, value in record.items():
current = result
path = key.split(separator)
for part in path[:-1]:
if part not in current:
current[part] = {}
current = current[part]
c... | scription"""
if "label" in trans:
obj.label = trans["label"]
if "description" in trans:
obj.description = trans["description"]
def localize_attributes(attribs, translations):
"""Localize list of attributes. `translations` should be a dictionary with
keys as attribute names, values are ... |
semkiv/heppy_fcc | particles/p4.py | Python | gpl-3.0 | 1,250 | 0.0152 | import math
class P4(object):
def p4(self):
'''4-momentum, px, py, pz, E'''
return self._tlv
def p3(self):
'''3-momentum px, py, pz'''
return self._tlv.Vect()
def e(self):
'''energy'''
return self._tlv.E()
def pt(self):
'''transverse momentum ... | a(self):
'''angle w/r to transverse plane'''
return math.pi/2 - self._tlv.Theta()
def eta(self):
'''pseudo-rapidity (-ln(tan self._tlv.Theta()/2)).
theta = 0 -> eta = +inf
theta = pi/2 -> 0
theta = pi -> eta = -inf
'''
return self._tlv.Eta()
def... | from x axis, in the transverse plane)'''
return self._tlv.Phi()
def m(self):
'''mass'''
return self._tlv.M()
def __str__(self):
return 'pt = {e:5.1f}, e = {e:5.1f}, eta = {eta:5.2f}, theta = {theta:5.2f}, phi = {phi:5.2f}, mass = {m:5.2f}'.format(
pt = self... |
hnakamur/django-bootstrap-table-example | project/apiv2/urls.py | Python | mit | 430 | 0.002326 | from django.conf. | urls import url
from .viewsets import BookmarkViewSet
bookmark_list = BookmarkViewSet.as_view({
'get': 'list',
'post': 'create'
})
bookmark_detail = BookmarkViewSet.as_view({
'get': 'retrieve',
'patch': 'update',
'delete': 'destroy'
})
urlpatterns = [
url(r'^bookmarks/$', bookmark_list, name... | , name='bookmark'),
]
|
dagwieers/ansible | lib/ansible/modules/remote_management/redfish/idrac_redfish_command.py | Python | gpl-3.0 | 5,884 | 0.00119 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Dell EMC Inc.
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
... | a)"
| '''
EXAMPLES = '''
- name: Create BIOS configuration job (schedule BIOS setting update)
idrac_redfish_command:
category: Systems
command: CreateBiosConfigJob
baseuri: "{{ baseuri }}"
username: "{{ username }}"
password: "{{ password }}"
'''
RETURN = '''
msg:
description: Messag... |
sysadminmatmoz/pmis | analytic_account_open/wizards/analytic_account_open.py | Python | agpl-3.0 | 1,741 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Eficent - Jordi Ballester Alomar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AnalyticAccountOpen(models.TransientModel):
_name = 'analytic.account.open'
_description = 'Open single analytic account'
... | result[curr_id] = True
# Now | add the children
self.env.cr.execute('''
WITH RECURSIVE children AS (
SELECT parent_id, id
FROM account_analytic_account
WHERE parent_id = %s
UNION ALL
SELECT a.parent_id, a.id
FROM account_analytic_account a
JOIN children b ON(a.parent_id = b.id)
... |
necolt/hudson-notifier | hudsonnotifier/AboutHudsonnotifierDialog.py | Python | gpl-3.0 | 2,628 | 0.012938 | # -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Philip Peitsch <philip.peitsch@gmail.com>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed ... | pass
def finish_initializing(self, builder):
"""finish_initalizing should be called after parsing the ui definition
and creating a AboutHudsonnotifierDialog object with it in order to finish
initializing the start of the new AboutHudsonnotifierDi | alog instance.
"""
#get a reference to the builder and set up the signals
self.builder = builder
self.builder.connect_signals(self)
#code for other initialization actions should be added here
def NewAboutHudsonnotifierDialog():
"""NewAboutHudsonnotifierDialog - returns... |
Khroki/MCEdit-Unified | pkgutil.py | Python | isc | 20,304 | 0.000788 | """Utilities to support packages."""
# NOTE: This module must remain compatible with Python 2.3, as it is shared
# by setuptools for distribution with Python 2.3 and up.
import os
import sys
import imp
import os.path
from types import ModuleType
__all__ = [
'get_importer', 'iter_importers', 'get_loader', 'find_l... | path=None, prefix=''):
"""Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
... | yielded = {}
for i in importers:
for name, ispkg in iter_importer_modules(i, prefix):
if name not in yielded:
yielded[name] = 1
yield i, name, ispkg
#@simplegeneric
def iter_importer_modules(importer, prefix=''):
if not hasattr(importer, 'iter_modules'):
... |
Huyuwei/tvm | nnvm/tests/python/frontend/darknet/test_forward.py | Python | apache-2.0 | 18,555 | 0.00388 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | pe=dtype)
for i in range(length):
data_np[i] = data[i]
return data_np.reshape(shape)
def _get_tvm_output(net, data, build_dtype='float32'):
'''Compute TVM output'''
dtype = 'float32'
sym, params = frontend.darknet.from_d | arknet(net, dtype)
target = 'llvm'
shape_dict = {'data': data.shape}
graph, library, params = nnvm.compiler.build(sym, target, shape_dict,
build_dtype, params=params)
# Execute on TVM
ctx = tvm.cpu(0)
m = graph_runtime.create(graph, library, ctx)... |
waneric/PyMapLib | src/gabbs/layers/Layer.py | Python | mit | 2,213 | 0.001808 | # -*- coding: utf-8 -*-
"""
Layer.py - base layer for gabbs maps
======================================================================
AUTHOR: Wei Wan, Purdue University
EMAIL: rcac-help@purdue.edu
Copyright (c) 2016 Purdue University
See the file "license.terms" for information on usage and
re... | = int(zoomlevel)
scale = (dpi * inchesPerMeter * maxScalePerPixel) / (math.pow(2, zoomlevel))
| scale = int(scale)
return scale
except TypeError:
raise
#pass
except Exception as e:
raise e |
JonSteinn/Kattis-Solutions | src/Slatkisi/Python 3/main.py | Python | gpl-3.0 | 71 | 0.014085 | cost, zeros = map(int, input().split())
print | (int(rou | nd(cost, -zeros))) |
VTabolin/networking-vsphere | networking_vsphere/common/vmware_conf.py | Python | apache-2.0 | 3,247 | 0.002772 | # Copyright 2015 Mirantis, 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 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
# ... | .agent.common import config
DEFAULT_BRIDGE_MAPPINGS = []
DEFAULT_UPLINK_MAPPINGS = []
DEFAULT_VLAN_RANGES = []
DEFAULT_TUNNEL_RANGES = []
DEFAULT_TUNNEL_TYPES = []
agent_opts = [
cfg.IntOpt('polling_interval', default=2,
help=_("The number of seconds the agent will wait between "
... |
doctormo/python-crontab | tests/test_usage.py | Python | lgpl-3.0 | 7,441 | 0.000672 | #!/usr/bin/env python
#
# Copyright (C) 2012 Jay Sigbrandt <jsigbrandt@slb.com>
# Martin Owens <doctormo@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; ei... | s = []
def test_01_empty(self):
"""Open system crontab"""
cron = crontab.CronTab()
self.assertEqual(cron.render(), "")
self.assertEqual(cron.__unicode__(), "")
self.assertEqual(repr(cron), "<Unattached CronTab>")
def test_02_user(self):
"""Open a user's crontab"... | b(user='basic')
self.assertEqual(cron.render(), BASIC)
self.assertEqual(repr(cron), "<User CronTab 'basic'>")
def test_03_usage(self):
"""Dont modify crontab"""
cron = crontab.CronTab(tab='')
sys.stdout = DummyStdout()
sys.stdout.flush = flush
try:
... |
friendly-of-python/flask-online-store | flask_online_store/forms/admin/category.py | Python | mit | 461 | 0 | from .. import BaseForm
from wtforms import StringField, | TextAreaField
from wtforms.validators import DataRequired
class CategoryForm(BaseForm):
name = StringField('name',
validators=[
DataRequired()
])
description = TextAreaField('description',
validators=[
... | red()
])
|
cvandeplas/plaso | plaso/parsers/plist.py | Python | apache-2.0 | 5,390 | 0.004824 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... | tested a bit more.
# TODO: Re-evaluate if we can delete this or still require it.
#if bpl.is_corrupt:
# logging.warning(
# u'[{0:s}] corruption detected in binary plist: {1:s}'.format(
| # self.NAME, file_name))
return top_level_object
def Parse(self, parser_context, file_entry):
"""Parse and extract values from a plist file.
Args:
parser_context: A parser context object (instance of ParserContext).
file_entry: A file entry object (instance of dfvfs.FileEntry).
... |
pyblub/pyload | pyload/utils/purge.py | Python | agpl-3.0 | 1,743 | 0 | # -*- coding: utf-8 -*-
# @author: vuolter
from __future__ import absolute_import, unicode_literals
import os
import re
import sys
from future import standard_library
standard_library.install_aliases()
def char(text, chars, repl=''):
return re.sub(r'[{0}]+'.format(chars), repl, text)
_UNIXBADCHARS = ('\0', ... | ern(text, rules):
for rule in rules:
try:
pattr, repl, flags = rule
except ValueError:
pattr, repl = rule
flags = 0
text = re.sub(pattr, repl, text, flags)
return text
def truncate(text, offset):
maxtrunc = len(text) // 2
if offset > maxtrunc... | uncate')
trunc = (len(text) - offset) // 3
return '{0}~{1}'.format(text[:trunc * 2], text[-trunc:])
def uniquify(seq):
"""Remove duplicates from list preserving order."""
seen = set()
seen_add = seen.add
return type(seq)(x for x in seq if x not in seen and not seen_add(x))
|
eukaryote/dotfiles | sublime3/.config/sublime-text-3/Packages/SublimeREPL/repls/killableprocess/__init__.py | Python | mit | 118 | 0.016949 | from .killabl | eprocess import Popen, mswindows
if mswindows:
from .winprocess import START | UPINFO, STARTF_USESHOWWINDOW |
arnomoonens/DeepRL | yarll/scripts/run_model.py | Python | mit | 2,858 | 0.004899 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import argparse
import tensorflow as tf
from gym import wrappers
from yarll.environment.registration import make
class ModelRunner(object):
"""
Run an already learned model.
Currently only supports one variation of an environment.
"""
def __i... | turn dictionary of results
"""
state = self.env.reset()
for _ in range(self.config["episode_max_length"]):
action = self.choose_action(state)
for _ in range(self.config["repeat_n_actions"]):
_, _, done, _ = self.env.step(action)
if done: #... | def run(self):
for _ in range(self.config["n_iter"]):
self.get_trajectory()
parser = argparse.ArgumentParser()
parser.add_argument("environment", metavar="env", type=str, help="Gym environment to execute the model on.")
parser.add_argument("model_directory", type=str, help="Directory from wher... |
google/jax | tests/linalg_test.py | Python | apache-2.0 | 64,375 | 0.007518 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
for dtype in float_types + complex_types))
def testSlogdet(self, shape, dtype):
rng = jtu.rand_default(self.rng())
| args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(np.linalg.slogdet, jnp.linalg.slogdet, args_maker,
tol=1e-3)
self._CompileAndCheck(jnp.linalg.slogdet, args_maker)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name":
"_shape={}".... |
repotvsupertuga/tvsupertuga.repository | script.module.resolveurl/lib/resolveurl/plugins/videozoo.py | Python | gpl-2.0 | 3,993 | 0.008264 | """
Kodi resolveurl plugin
Copyright (C) 2014 smokdpi
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.
... | = 'http://' + host + '/' + stream_url.replace('/gplus.php', 'gplus.php').replace('/picasa.php', 'picasa.php')
stream_url = self._redirect_test(stream_url)
if stream_url:
if 'google' in str | eam_url:
return HostedMediaFile(url=stream_url).resolve()
else:
return stream_url
else:
raise ResolverError('File not found')
def _redirect_test(self, url):
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', common.IOS... |
dgaston/ddb-ngsflow-scripts | workflow-vcfanno_somatic_amplicon.py | Python | mit | 2,541 | 0.002361 | #!/usr/bin/env python
# Standard packages
import os
import sys
import argparse
# Third-party packages
from toil.job import Job
# Package methods
from ddb import configuration
from ddb_ngsflow import gatk
from ddb_ngsflow import annotation
from ddb_ngsflow import pipeline
from ddb_ngsflow.align import bwa
from ddb_ng... | s
from ddb_ngsflow | .qc import qc
from ddb_ngsflow.coverage import sambamba
from ddb_ngsflow.variation import variation
from ddb_ngsflow.variation import freebayes
from ddb_ngsflow.variation import mutect
from ddb_ngsflow.variation import platypus
from ddb_ngsflow.variation import vardict
from ddb_ngsflow.variation import scalpel
from ddb... |
brianz/servant | servant/transport/local.py | Python | lgpl-3.0 | 2,255 | 0.002661 | import importlib
from .base import BaseTransport
from ..service import Service
class LocalTransport(BaseTransport):
def __init__(self):
super(LocalTransport, self).__init__()
self.__service = None
def __repr__(self):
return self.__class__.__name__
def configure(self, service_na... | 'must subclass servant.Service and define an action_map, '
'name and version.'
)
def _looks_like_service_class(self, obj, service_name, service_version):
return (
getattr(obj, 'name', '') == service_name and
getattr(obj, 'version', -1) ... | actions')
)
def is_connected(self):
return True
def send(self, request):
return self.__service.handle_request(request)
|
eek6/squeakspace | www/proxy/scripts/local/node_addr.py | Python | gpl-3.0 | 2,510 | 0.004382 | import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.proxy.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def post_handler(environ):
query = ht.parse_post_request(environ)
cookies = ht.parse_cookies(environ)
user_id = ht.get_re... | on, {
'POST' : post_handler,
'GET | ' : get_handler,
'DELETE' : delete_handler})
def application(environ, start_response):
return ht.respond_with_handler(environ, start_response, main_handler)
|
blitzrk/sublime_libsass | lib/deps.py | Python | mit | 1,567 | 0.003191 | from .pathutils import grep_r
from . import project
import os
import re
def is_partial(path):
'''Check if file is a Sass partial'''
return os.path.basename(path).startswith('_')
def partial_import_regex(partial):
'''Get name of Sass partial file as would be used for @import'''
def from_curdir(cwd)... | s']):
if f not in files and f not in partials:
files, partials = get_rec(f, start, files, partials)
return (files, partials)
def get(path):
'''Get files af | fected by change in contents of `path`'''
rel, root = project.splitpath(path)
deps, _ = get_rec(rel, root)
return (deps, root)
|
e-sensing/wtss.py | src/wtss/__init__.py | Python | lgpl-3.0 | 1,040 | 0.000962 | #
# Copyright (C) 2014 National Institute For Space Research (INPE) - Brazil.
#
# This file is part of Python Client API for Web Time Series Service.
#
# Web Time Series Service for Python is free software: you can
# redistribute it and/or modify it under the terms of the
# GNU Lesser General Public License as pu... | he Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Web Time Series Service for Python 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... | ng with Web Time Series Service for Python. See LICENSE. If not, write to
# e-sensing team at <esensing-team@dpi.inpe.br>.
#
"""Python Client API for Web Time Series Services (WTSS)."""
from .wtss import wtss
from .wtss import time_series
|
artminster/artminster | contrib/billing/migrations/0002_auto__add_field_subscription_frequency.py | Python | mit | 5,583 | 0.008239 | # -*- 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):
# Adding field 'Subscription.frequency'
db.add_column('billing_subscription', 'frequency',
... | oField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
| 'price': ('django.db.models.fields.DecimalField', [], {'max_digits': '10', 'decimal_places': '2'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'u... |
AlanJAS/iknowEditor | activity.py | Python | gpl-3.0 | 4,743 | 0.004217 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
import sys
import pygame
from gi.repository import Gtk
from sugar3.activity.activity import Activity
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.activity.widgets import ActivityToolbarButton
from sugar3.graphic... | self.box1.set_size_request(350, 350)
self.box1.show()
self.box2 = Gtk.HBox()
self.box2.set_size_request(50, 200)
self.box2.show()
self.table.attach(self.box1, 0, 1, 0, 1)
self.table.attach(self.box2, 1, 2, 0, 1)
self.labels_and_values = Data(self)
... | s_and_values)
self.set_canvas(self.table)
def run_canvas(self):
self.actividad.canvas = sugargame.canvas.PygameCanvas(self,
main=self.actividad.run,
modules=[pygame.display, pygame.font])
self.box1.add(self.actividad.c... |
FlintHill/SUAS-Competition | tests/unit_tests/test_suassystem_utils_data_functions.py | Python | mit | 1,006 | 0.001988 | import unittest
import os
from PIL import Image
from SUASSystem.utils import crop_target
class SUASSystemUtilsDataFunctionsTestCase(unittest.TestCase):
def test_crop_image(self):
"""
Test the crop image method.
"""
input_image_path = "tests/images/image2_test_image_bounder.jpg"
... | crop_image_path = "tests/images/test_crop.jpg"
top_left_coords = [250.0, 200.0]
bottom_right_coords = [350.0, 300.0]
crop_target(input_image_path, output_crop_image_path, top_left_coords, bottom_right_coords)
saved_crop = Image.open(output_crop_image_path).load()
input_image = ... | self.assertEqual(saved_crop[50, 50], input_image[300, 250])
self.assertEqual(saved_crop[99, 99], input_image[349, 299])
os.remove("tests/images/test_crop.jpg")
|
leohmoraes/weblate | weblate/trans/scripts.py | Python | gpl-3.0 | 2,637 | 0 |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 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, eith... | me)
def run_post_commit_script(component, filename):
"""
Post commit hook
"""
run_hook(component, component.post_commit_script, filename)
def run_hook(component, script, *args):
"""
Generic script hook executor.
"""
if script:
command = [script]
if args:
c... | ironment = get_clean_env()
if component.is_repo_link:
target = component.linked_subproject
else:
target = component
environment['WL_VCS'] = target.vcs
environment['WL_REPO'] = target.repo
environment['WL_PATH'] = target.get_path()
environment['WL_F... |
BizShuk/code_sandbox | python/raw_input_test.py | Python | mit | 120 | 0.016667 | import sys
|
#line = sys.stdin.read()
#print line
datas = []
for line in sys.stdin:
datas.append(line)
print datas
| |
pybursa/homeworks | a_lusher/hw3/Lusher_Alexander_home_work_3_.py | Python | gpl-2.0 | 2,380 | 0.059714 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
def add(x, y):
a=1
while a>0:
a = x & y
b = x ^ y
x = b
y = a << 1
return b
def vowel_count(word):
vowels_counter = 0
for letter in word:
if letter.isalpha():
if letter.upper() in 'AEIOUY':
vowels_co... | adipiscing elit. Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum congue leo eget malesuada. Cras ultricies ligula sed magna dic | tum porta."
list=text.split()
i=len(text)-1
mirrored_text=''
while i>=0:
mirrored_text=mirrored_text+(text[i])
i-=1
print mirrored_text
# Assignment N 4
import os
content=dir(os)
content_len=len(content)
for k in range(0,content_len-1):
s="os"+"."+content[k]+".__doc__"
print(eval(s))
... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/temporaryblobstorage/webservice.py | Python | agpl-3.0 | 959 | 0 | # Copyright 22011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""All the interfaces that are exposed through the webservice.
There is a declaration in ZCML somewhere that looks like:
<webservice:register module="lp.patchwebservice" />
wh... | [
'ITemporaryBlobStorage',
'ITemporaryStorageManager',
]
from lp.services.temporaryblobstorage.interfaces import (
ITemporaryBlobStorage,
ITemporaryStorageManager,
)
from lp.services.webservice.apihelpers import (
patch_operations_explicit_version,
)
# ITemporaryBlobStorage
patch_opera... | StorageManager, 'beta', "fetch")
|
simgunz/anki | qt/aqt/preferences.py | Python | agpl-3.0 | 10,181 | 0.000982 | # Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import anki.lang
import aqt
from aqt import AnkiQt
from aqt.profiles import RecordingDriver, VideoDriver
from aqt.qt import *
from aqt.utils import (
TR,
HelpPage,
disable_help_butt... | CLICK_THE_SYNC)
)
def onSyncDeauth(self) -> None:
if self.mw.media_syncer.is_syncing():
showWarning("Can't log out while sync in progress.")
return
self.prof["syncKey"] = None
self.mw.col.media.force_resync()
self._hideAuth()
def updateNetwork(se... | ) -> None:
self.prof["autoSync"] = self.form.syncOnProgramOpen.isChecked()
self.prof["syncMedia"] = self.form.syncMedia.isChecked()
self.mw.pm.set_auto_sync_media_minutes(
self.form.autoSyncMedia.isChecked() and 15 or 0
)
if self.form.fullSync.isChecked():
... |
bitmazk/django-registration-email | registration_email/backends/default/urls.py | Python | unlicense | 1,615 | 0 | """Custom urls.py for django-registration."""
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from registration.backends.default.views import (
ActivationView,
| RegistrationView,
)
from registration_email.forms import EmailRegistrationForm
ur | lpatterns = [
# django-registration views
url(r'^activate/complete/$',
TemplateView.as_view(
template_name='registration/activation_complete.html'),
name='registration_activation_complete'),
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(
t... |
gtrdp/twitter-clustering | crawling/crawl.py | Python | mit | 1,795 | 0.007242 | #!/usr/bin/env python
import json
DEBUG = False
import sys
import tweepy
import time
#consumer_key = 'HcMP89vDDumRhHeQBYbE3Asnp'
#consumer_secret = 'kcXfsNyBl7tan1u2DgV7E10MpsVxhbwTjmbjp3YL9XfDdMJiYt'
#access_key = '67882386-IXbLKaQEtTbZF9yotuLTjgitqjwBkouIstmlW4ecG'
#access_secret = 'SyVrXlIDkidYr3JlNiTQ8tjZ973gIKy... | = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, data_dir):
# query_fname = format_filename(query)
time_now = time.strftime("%Y-%m-%d_%H.%M.%S")
self.outfile = "%s/stream_%s.json" % (data_dir, time_now)
| def on_data(self, data):
try:
with open(self.outfile, 'a') as f:
f.write(data)
print(data)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
time.sleep(5)
return True
def on_error(s... |
wmarshall484/streamsx.topology | com.ibm.streamsx.topology/opt/python/packages/streamsx/topology/mqtt.py | Python | apache-2.0 | 7,558 | 0.003705 | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016
"""
Publish and subscribe to MQTT messages.
Additional information at http://mqtt.org and
http://ibmstreams.github.io/streamsx.messaging
"""
from future.builtins import *
from streamsx.topology.topology import *
from streamsx.topology ... | stream to the topic "python.topic1"
topic = "python.topic1"
src = topo.source(test_functions.mqtt_publish)
mqs = mqstream.publish(src, topic)
| # subscribe to the topic "python.topic1"
topic = ["python.topic1", ]
mqs = mqstream.subscribe(topic)
mqs.print()
Configuration properties apply to publish and
subscribe unless stated otherwise.
serverURI
Required String. URI to the MQTT server, either
tcp:... |
Gigers/data-struct | algoritimos/Python/fatorial-while.py | Python | bsd-2-clause | 158 | 0.012658 | def fat(n):
result = 1
while n > 0:
result = result * n
n = n - | 1
return resu | lt
# testes
print("Fatorial de 3: ", fat(3));
|
Dani4kor/Checkio | days-diff.py | Python | mit | 504 | 0.003968 | fro | m datetime import datetime
def days_diff(date1, date2):
"""
Find absolute diff in days between dates
"""
days = datetime(*date1) - datetime(*date2)
print abs(days)
return abs(days.days)
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for au... | 238
|
bgarrels/sky | sky/legacy/comparison.py | Python | bsd-3-clause | 685 | 0.014599 | import sys
import requests
try:
from .helper import *
except SystemError:
from helper import *
def compareRequestsAndSelenium(url):
html1 = str(requests.get(url).text)
try:
driver = webdriver.Firefox()
driver.maximize_window()
driver.get(url)
html2 = str(driver.page... | mpareRequestsAndSelenium(url)
if __name__ == '__main__':
compareReque | stsAndSelenium(sys.argv[1])
|
ecdpalma/napscheduler | napscheduler/util.py | Python | mit | 6,708 | 0.001044 | """
This module contains several handy functions primarily meant for internal use.
"""
from datetime import date, datetime, timedelta
from time import mktime
import re
import sys
from types import MethodType
__all__ = ('asint', 'asbool', 'convert_to_datetime', 'timedelta_seconds',
'time_difference', 'datet... |
if isinstance(obj, str):
obj = obj.strip().lower()
if obj in ('true', 'yes', 'on', 'y', 't', '1'):
return True
if obj in ('false', 'no', ' | off', 'n', 'f', '0'):
return False
raise ValueError('Unable to interpret value "%s" as boolean' % obj)
return bool(obj)
_DATE_REGEX = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
r'(?: (?P<hour>\d{1,2}):(?P<minute>\d{1,2}):(?P<second>\d{1,2})'
r'(?:\.(?P<micro... |
ClearCorp/odoo-clearcorp | exchange_rate_calculated/models/__init__.py | Python | agpl-3.0 | 144 | 0 | # -*- coding: utf- | 8 -*-
# © <YEAR(S)> ClearCorp
# License AGPL-3.0 or later (http:/ | /www.gnu.org/licenses/agpl.html).
import account_move_line
|
markokr/cc | cc/daemon/infosender.py | Python | bsd-2-clause | 5,065 | 0.0077 | #! /usr/bin/env python
"""Read infofiles.
"""
import glob
import os, os.path
import sys
import threading
import time
import skytools
import cc.util
from cc import json
from cc.daemon import CCDaemon
from cc.message import is_msg_req_valid
from cc.reqs import InfofileMessage
class InfoStamp:
def __init__(self,... | t_inc('count')
f.close()
def send_file(self, fs, body):
cfb = cc.util.compress (body, self.compression, {'level': self.compression_level})
self.log.debug ("file compressed from %i to %i", len(body), len(cfb))
if self.use_blob:
data = ''
blob = cfb
els... | blob = None
msg = InfofileMessage(
filename = fs.filename.replace('\\', '/'),
mtime = fs.filestat.st_mtime,
comp = self.compression,
data = data)
if self.msg_suffix:
msg.req += '.' + self.msg_suffix
self.ccpublis... |
hashview/hashview | migrations/versions/ded3fd1d7f9d_.py | Python | gpl-3.0 | 850 | 0.002353 | """empty message
Revision ID: ded3fd1d7f9d
Revises: b70e85abec53
Create Date: 2020-12-30 22:46:59.418950
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'ded3fd1d7f9d'
down_revision = 'b70e85abec53'
branch_labels = None
depe... | ecksum', sa.String(length=256), nullable=False))
op.drop_column('hashfiles', 'hash_str')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('hashfiles', sa.Column('hash_str', mysql.VARCHAR(l | ength=256), nullable=False))
op.drop_column('hashfiles', 'checksum')
# ### end Alembic commands ###
|
runt18/nupic | src/nupic/regions/TestRegion.py | Python | agpl-3.0 | 15,152 | 0.011022 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ss RegionIdentityPolicyBase(object):
""" A base class that must be subclassed by users in order to define the
TestRegion instance's specialization. See also setIdentityPolicyInstance().
"""
__metaclass__ = ABCMeta
@abstractmethod
def initialize(self, testRegionObj):
""" Called from the scope of the reg... | TestRegion instance with which this policy is
associated.
"""
@abstractmethod
def compute(self, inputs, outputs):
"""Perform the main computation
This method is called in each iteration for each phase the node supports.
Called from the scope of the region's PyRegion.compute()... |
UdK-VPT/Open_eQuarter | mole3/tests/plugin_interaction_test.py | Python | gpl-2.0 | 4,712 | 0.002971 | import unittest
import os, sys, imp
from qgis import utils
from qgis.core import QgsVectorLayer, QgsField, QgsProject, QGis
from qgis.PyQt.QtCore import QVariant
from .qgis_models import set_up_interface
from mole3.qgisinteraction import layer_interaction as li
from mole3.qgisinteraction import plugin_interaction as p... | _polygonlayer2')
registry.addMapLayer(point_layer)
registry.addMapLayer(poly_layer1)
registry.addMapLayer(poly_layer2)
psti = pi.PstInteraction(util | s.iface)
psti.set_input_layer(point_layer.name())
map = psti.select_and_rename_files_for_sampling()
appendix = ['R', 'G', 'B', 'a']
poly_fields = psti.pst_dialog.rastItems[poly_layer1.name()]
for i in range(1, len(poly_fields)):
self.assertEqual(poly_fields[i][1], '... |
robwarm/gpaw-symm | gpaw/test/big/scf/b256H2O/b256H2O.py | Python | gpl-3.0 | 4,905 | 0.031804 | # the problem described below was fixed in 9758!
# keep_htpsit=False fails since 9473,
# on some installations (?) with:
# case A (see below in the code):
# RuntimeError: Could not locate the Fermi level!
# or the energies from the 2nd one behave strange, no convergence:
# iter: 1 18:21:49 +1.7 -3608.... | 3.376,-0.501, 2.793),
( 6.002,-0.525, 4.002), ( 6.152, 0.405, 3.660), ( 5.987,-0.447, 4.980),
( 0.649, 3.541, 2.897), ( 0.245, 4.301, 3.459), ( 1.638, 3.457, 3.084),
(-0.075, | 5.662, 4.233), (-0.182, 6.512, 3.776), (-0.241, 5.961, 5.212),
( 3.243, 2.585, 3.878), ( 3.110, 2.343, 4.817), ( 4.262, 2.718, 3.780),
( 5.942, 2.582, 3.712), ( 6.250, 3.500, 3.566), ( 6.379, 2.564, 4.636),
( 2.686, 5.638, 5.164), ( 1.781, 5.472, 4.698), ( 2.454, 6.286, 5.887),
( 6.744, 5.276, 3... |
simonqiang/gftest | app/__init__.py | Python | mit | 888 | 0.003378 | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy i | mport SQLAlchemy
from config import config
from flask.ext.redis import Redis
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
redis1 = Redis()
def create_app(config_name): |
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
app.config['REDIS_HOST'] = 'localhost'
app.config['REDIS_PORT'] = 6379
app.config['REDIS_DB'] = 0
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)... |
carolFrohlich/nipype | nipype/interfaces/mne/__init__.py | Python | bsd-3-clause | 55 | 0 | # -*- coding: utf-8 -*-
| from .base import WatershedBE | M
|
fkaa/iceball | tools/kv62pmf.py | Python | gpl-3.0 | 3,453 | 0.019983 | """
A tool for converting kv6 models into pmf.
GreaseMonkey, 2013 - Public Domain
WARNING: I haven't checked to ensure that X,Y are around the right way.
If you find your models have been flipped inadvertently, let me know! --GM
"""
from __future__ import print_function
import sys, struct
# Backwards compatibilit... | ice-versa
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY2:
# This script didn't use range() anyway, so no problem overwriting it in Py2
import __builtin__
range = getattr(__builtin__, "xrange")
_ord = ord
else:
_ord = lambda x: x
USAGE_MSG = """
usage:
python2 kv62pmf.py in.kv6 out.pmf ptsi... | a number for the 3rd argument")
if not sys.argv[4].isdigit():
raise Exception("expected a number for the 4th argument")
ptsize = int(sys.argv[3])
ptspacing = int(sys.argv[4])
if ptsize < 1 or ptsize > 65535:
raise Exception("point size out of range (1..65535)")
bonename = sys.argv[4]
if PY3:
bonename = bonename.... |
tokamstud/enron-analysis | src/complex/hive_prep.py | Python | gpl-3.0 | 2,895 | 0.071157 | from mrjob.job import MRJob
from mrjob.step import MRStep
def get_id_from_line(line):
if line.find('.","Message-ID: <') > 0:
start = line.find("Message-ID")+13
i=0
for char in line[start:]:
i=i+1
if (not (char.isdigit() or (char == '.'))):
stop = i+start-2
break
return line[start:stop]
class MR... | MRStep(mapper_init=self.mapper_init_count,
mapper=self.mapper_count),
MRStep(mapper=self.mapper_child)
# STEP 1
def mapper_init_count(self):
self.message_id = ''
self.in_body = False
self.body = []
self.after_key = False
self.beginning = False
self.key = False
| def mapper_count(self, _, line):
line = line.strip()
if (line.find('.","Message-ID: <') > 0) and self.in_body and not self.beginning:
yield self.message_id, self.body
self.message_id = ''
self.body = []
self.in_body = False
self.after_key = False
self.beginning = False
self.key = False
if s... |
fishtown-analytics/dbt | scripts/build-dbt.py | Python | apache-2.0 | 29,183 | 0.000069 | import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time
import venv # type: ignore
import zipfile
from typing import Dict
from argparse import ArgumentParser
from dataclasses import dataclass
from pathlib import Path
from urllib.request import urlopen
f... | tdout.decode('utf-8')
def run_command(cmd, cwd=None) -> None:
result = collect_output(cmd, stderr=subprocess.STDOUT, cwd=cwd)
print(result)
def set_version(path: Path, version: Version, part: str):
# bumpversio | n --commit --no-tag --new-version "${version}" "${port}"
cmd = [
'bumpversion', '--commit', '--no-tag', '--new-version',
str(version), part
]
print(f'bumping version to {version}')
run_command(cmd, cwd=path)
print(f'bumped version to {version}')
class PypiBuilder:
_SUBPACKAGES ... |
NTUTVisualScript/Visual_Script | static/javascript/blockly/i18n/create_messages.py | Python | mit | 6,374 | 0.010041 | #!/usr/bin/python
# Generate .js files defining Blockly core and language messages.
#
# Copyright 2013 Google Inc.
# https://developers.google.com/blockly/
#
# 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 t... | nym_file',
default=os.path.join('json', 'synonyms.json'),
help='Path to .json file with synonym definitions')
parser.add_argument('--source_constants_file',
default=os.path.join('json', 'constants.json'),
| help='Path to .json file with constant definitions')
parser.add_argument('--output_dir', default='js/',
help='relative directory for output files')
parser.add_argument('--key_file', default='keys.json',
help='relative path to input keys file')
parser.a... |
yohn89/pythoner.net | pythoner/accounts/admin.py | Python | gpl-3.0 | 915 | 0.006557 | # -*- coding: utf-8 -*-
"""
pythoner.net
Copyright (C) 2013 PYTHONER.ORG
This program is free software: you can redistribute it and/or modify
it under the terms of the G | NU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULA... | nse for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from django.contrib import admin
from models import *
class ProfileAdmin(admin.ModelAdmin):
list_display = ('screen_name','city','introduct... |
stackArmor/security_monkey | security_monkey/watchers/elasticsearch_service.py | Python | apache-2.0 | 4,759 | 0.003572 | # Copyright 2015 Netflix, 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... | _for_slurp()
@iter_account_region(index=self.index, accounts=self.accounts, service_name='es')
def slurp_items(**kwargs):
item_list = []
exception_map = {}
kwargs['exception_map'] = exception_map
account_db = Account.query.filter(Account.name == kwargs['... | _info is None:
return item_list, exception_map
(client, domains) = es_info
app.logger.debug("Found {} {}".format(len(domains), ElasticSearchService.i_am_plural))
for domain in domains:
if self.check_ignore_list(domain["DomainName"]):
... |
helloTC/LearnPython | fluent_python/array_of_sequences/tuple_as_record.py | Python | mit | 1,025 | 0.00878 | outdata1 = divmod(20,8)
# prefix an argument with a star when calling a functi | on to unpack tuple
t = (20,8)
outdata2 = divmod(*t)
import os
# Note that filename = hh.grad
_, filename = os.path.split('/nfs/j3/hh.grad')
# Using * to grab excess items
# Can be used in pyth | on3, but not in python2
# a, b, *rest = range(5)
# a, b, *rest = range(3)
# a, b, *rest = range(2)
# a, *body, c, d = range(5)
# *head, b, c, d = range(5)
# Nested tuple unpacking
a = [('good', (334,213)),
('bad', (231,234))]
for cond, (x, y) in a:
print('x = {0}, y = {1}'.format(x, y))
# Namedtuple
from c... |
rimbalinux/MSISDNArea | django/db/backends/util.py | Python | bsd-3-clause | 4,684 | 0.007472 | import datetime
import decimal
from time import time
from django.utils.hashcompat import md5_constructor
from django.utils.log import getLogger
logger = getLogger('django.db.backends')
class CursorDebugWrapper(object):
def __init__(self, cursor, db):
self.cursor = cursor
self.db = db ... | % (name[:length-hash_len], hash)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
context.prec =... | al_places, context=context))
else:
return u"%.*f" % (decimal_places, value)
|
ramseyboy/tabletop-scanner | tabletopscanner/boardgamegeekapi/search.py | Python | apache-2.0 | 674 | 0.001484 | import xml.etree.cElementTree as et
from collections import OrderedDict
from tableto | pscanner.boardgamegeekapi.parsers import Deserializer
class SearchParser(Deserializer):
def deserialize(self, xml):
tree = et.fromstring(xml)
return [SearchParser.__make_search_result(el) for el in tree.findall('item')]
@staticmethod
def __mak | e_search_result(el):
geekid = geekid = el.attrib['id']
name = el.find('name').attrib['value']
yearpublished = el.find('yearpublished').attrib['value']
return OrderedDict({
'geekid': geekid,
'name': name,
'yearpublished': yearpublished
})
|
abo-abo/edx-platform | cms/djangoapps/contentstore/features/common.py | Python | agpl-3.0 | 12,319 | 0.000812 | # pylint: disable=C0111
# pylint: disable=W0621
from lettuce import world, step
from nose.tools import assert_true, assert_in, assert_false # pylint: disable=E0611
from auth.authz import get_user_by_email, get_course_groupname_for_role
from django.conf import settings
from selenium.webdriver.common.keys import Keys... | o_studio(
uname='robot',
email='robot+studio@edx.org',
password='test',
name='Robot Studio'):
world.log_in(username=uname, password=password, email=email, name=name)
# Navigate to the studio dashboard
world.visit('/')
assert_in(uname, world.css_text('h2.title', timeout=1... | in ("staff", "instructor"):
groupname = get_course_groupname_for_role(course.location, role)
group, __ = Group.objects.get_or_create(name=groupname)
user.groups.add(group)
user.save()
def create_a_course():
course = world.CourseFactory.create(org='MITx', course='999', display_name='Ro... |
briehl/wjr_sdk_test | test/MyContigFilter_server_test.py | Python | mit | 4,171 | 0.007672 | import unittest
import os
import json
import time
from os import environ
from ConfigParser import ConfigParser
from pprint import pprint
from biokbase.workspace.client import Workspace as workspaceService
from MyContigFilter.MyContigFilterImpl import MyContigFilter
class MyContigFilterTest(unittest.TestCase):
... | : wsName})
self.__class__.wsName = wsName
return wsName
def getImpl(self):
return self.__class__.serviceImpl
def getContext(self):
return self.__class__.ctx
def test_filter_contigs_ok(self):
obj_name = "contigset.1"
contig1 = {'id': '1', 'length': 10, 'md5'... | uence': 'agcttttcat'}
contig2 = {'id': '2', 'length': 5, 'md5': 'md5', 'sequence': 'agctt'}
contig3 = {'id': '3', 'length': 12, 'md5': 'md5', 'sequence': 'agcttttcatgg'}
obj1 = {'contigs': [contig1, contig2, contig3], 'id': 'id', 'md5': 'md5', 'name': 'name',
'source': 'source',... |
piotroxp/scibibscan | scib/lib/python3.5/site-packages/astropy/modeling/tests/example_models.py | Python | mit | 8,459 | 0.000236 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Here are all the test parameters and values for the each
`~astropy.modeling.FittableModel` defined. There is a dictionary for 1D and a
dictionary for 2D models.
Explanation of keywords of the dictionaries:
"parameters" : list or dict
Model parame... | sk2D,
Ring2D)
from ..polynomial import Polynomial1D, Polynomial2D
from ..powerlaws import (
PowerLaw1D, BrokenPowerLaw1D, ExponentialCutoffPowerLaw1D,
LogParabola1D)
import numpy as np
#1D Models
models_1D = {
Gaussian1D: {
'parameters': [1, 0, 1],
'x_values': [0, np.sqrt(2), -np.sqrt(2... | 'parameters': [1, 0.1],
'x_values': [0, 2.5],
'y_values': [0, 1],
'x_lim': [-10, 10],
'integral': 0
},
Box1D: {
'parameters': [1, 0, 10],
'x_values': [-5, 5, 0, -10, 10],
'y_values': [1, 1, 1, 0, 0],
'x_lim': [-10, 10],
'integral': 10
... |
danzelmo/dstl-competition | global_vars.py | Python | mit | 32 | 0.03125 | DATA_DIR | = '/media/d/ssd2/dstl | /' |
uclastudentmedia/django-massmedia | massmedia/models.py | Python | apache-2.0 | 14,915 | 0.007643 | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.template.defaultfilters import slugify
from django.conf import settings
from django... | tringIO
import mimetypes
import os
import zipfile
from django_extensions.db.fields import AutoSlugField
# Patch mimetypes w/ any extra types
mimetypes.types_map.update(appsettings.EXTRA_MIME_TYPES)
try:
i | mport cPickle as pickle
except ImportError:
import pickle
try:
from iptcinfo import IPTCInfo
iptc = 1
except ImportError:
iptc = 0
# Try to load a user-defined category model
if appsettings.CATEGORIES_MODULE:
CATEGORIES_MODULE = appsettings.CATEGORIES_MODULE
else:
# Otherwise use dummy categor... |
tgymartin/green-fingers-2d | DW/part2_and_part3/Cohort_6_Team_6/part3_code/prototype.py | Python | gpl-3.0 | 3,524 | 0.018729 | #!/usr/bin/env python
'''
2D Group Members:
> Charlotte Phang
> Lau Wenkie
> Mok Jun Neng
> Martin Tan
> Dicson Candra
'''
#Import relevant modules
import RPi.GPIO as GPIO
import os
import glob
import time
from PIDsm import PID_ControllerSM
### PIN NUMBERS ###
tempPin = 4
motorPin = 12
fanPin = 1... | ('modprobe w1-gpio')
os.system('modprobe w1-therm')
#define directory of the temperature data in the linux filesystem
self.base_dir = '/sys/bus/w1/devices/'
self.device_folder = glob.glob(self.base_dir + '28*')[0]
self.device_file = self.device_folder + '/w1_slave'
def read_... | ice_file
lines = f.readlines()
f.close() #close file to reset the file pointer
return lines
def __call__(self): #function to extract temperature data from the raw data in string
lines = self.read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
... |
Pyco7/django-ajax-views | ajaxviews/conf.py | Python | mit | 1,622 | 0.001233 | from django.conf import settings as django_settings
# noinspection PyPep8Naming
class LazySettings:
@property
def REQUIRE_MAIN_NAME(self):
return getattr(django_settings, 'REQUIRE_MAIN_NAME', 'main')
@property
def DEFAULT_PAGINATE_BY(self):
return getattr(django_settings, 'DEFAULT_PAG... | NFIRMATION(self):
return getattr(django_settings, 'FORM_DELETE_CONFIRMATION', True)
@property
def AUTO_SUCCESS_URL(self):
return getattr(django_settings, 'AUTO_SUCCESS_URL', True)
sett | ings = LazySettings()
|
francois/pycounters | counters/base_counters.py | Python | mit | 499 | 0.022044 | import re
import time
class BaseCounters:
def __init__(self):
self.keyr | e = re.compile('\A[\w.]+\Z')
def ping(self, key):
self.validate_key(key)
self.do_ping(key, int(time.time()))
def hit(self, key, n=1):
self.validate_key(key)
self.do_hit(key, n)
def validate_key(self, key):
if re.match(self.keyre, key):
pass
else:
raise ValueError("Counters k... | \"" % key)
|
vinodkc/spark | python/pyspark/rdd.py | Python | apache-2.0 | 126,212 | 0.001965 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | from pyspark.sql.dataframe import | DataFrame
from pyspark.sql.types import AtomicType, StructType
from pyspark.sql._typing import AtomicValue, RowLike, SQLBatchedUDFType
from py4j.java_gateway import JavaObject # type: ignore[import]
from py4j.java_collections import JavaArray # type: ignore[import]
T = TypeVar("T")
T_co = TypeVar("T... |
panoplyio/panoply-python-sdk | panoply/errors/exceptions.py | Python | mit | 1,017 | 0 | from datetime import datetime
class PanoplyException(Exception):
def __init__(self, args=None, retryable=True):
| super(PanoplyException, self).__init__(args)
self.retryable = retryable
class IncorrectParamError(Exception):
def __init__(self, msg: str = "Incorrect input parametr"):
super().__init__(msg)
class DataSourceException(Exception):
def __init__(self, message, code, exception_cls,
... | essage)
self.message = message
self.code = code
self.phase = phase
self.source_type = source_type
self.source_id = source_id
self.database_id = database_id
self.exception_cls = exception_cls
self.created_at = datetime.utcnow()
class TokenValidationExcept... |
Tong-Chen/scikit-learn | examples/linear_model/plot_ransac.py | Python | bsd-3-clause | 1,671 | 0 | """
===========================================
Robust linear model estimation using RANSAC
===========================================
In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.
"""
import numpy as np
from matplotlib import pyplot as plt
from sklearn import ... | n_samples=n_samples, n_features=1,
n_informative=1, noise=10,
coef=True, random_state=0)
# Add outlier data
np.random.seed(0)
X[:n_outliers] = 3 + 0.5 * np.random.normal(size=(n_outliers, 1))
y[:n_outliers] = -3 + 10 * np.random.normal(size=n_... |
# Fit line using all data
model = linear_model.LinearRegression()
model.fit(X, y)
# Robustly fit linear model with RANSAC algorithm
model_ransac = linear_model.RANSACRegressor(linear_model.LinearRegression())
model_ransac.fit(X, y)
inlier_mask = model_ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
#... |
oscarforri/ambrosio | ambrosio/channels/TelegramChannel.py | Python | gpl-3.0 | 1,405 | 0.003559 | from Channel import Channel
import telepot
class AmbrosioBot(telepot.Bot):
"""AmbrosioBot is my telgram bot"""
def __init__(self, token):
super(AmbrosioBot, self).__init__(token)
self.clist = None
self.chat_id = None
def set_list(self,clist):
self.clist = clist
def on... | 84221:AAHls9d0EkCDfU0wgQ-acs5Z39aibA7BZmc")
self.messages = []
self.bot.set_list(self.messages)
| self.bot.notifyOnMessage()
def get_msg(self):
if self.msg_avail():
return self.messages.pop(0)
def msg_avail(self):
return len(self.messages) > 0
def respond(self, response):
if response is None:
response = "Command not understand"
self.bot.re... |
geminipy/geminipy | geminipy/__init__.py | Python | gpl-3.0 | 10,473 | 0.000095 | """
This module contains a class to make requests to the Gemini API.
Author: Mike Marzigliano
"""
import time
import json
import hmac
import base64
import hashlib
import requests
class Geminipy(object):
"""
A class to make requests to the Gemini API.
Make public or authenticated requests according to th... | 'request': request,
'nonce': self.get_nonce(),
'order_id': order_id
}
return requests.post(url, headers=self.prepare(params))
def active_orders(self):
"""Send a request to get active orders, return the response."""
request = '/v1/orders'
ur... | est
params = {
'request': request,
'nonce': self.get_nonce()
}
return requests.post(url, headers=self.prepare(params))
def past_trades(self, symbol='btcusd', limit_trades=50, timestamp=0):
"""
Send a trade history request, return the response.
... |
staranjeet/fjord | vendor/packages/click/examples/complex/complex/commands/cmd_status.py | Python | bsd-3-clause | 277 | 0 | import click
from complex.cli import pass_context
@click.command('status', short_help='Shows file changes.')
@pass_context
def cli(ctx):
"""Shows file changes in the current working directory."""
ctx.log('Changed files: none')
ctx. | vlog('bla bla bla, | debug info')
|
NSLS-II/replay | replay/search/__init__.py | Python | bsd-3-clause | 527 | 0 | from __future__ import absolute_ | import
import six
import logging
from .. import py3_errmsg
logger = logging.getLogger(__name__)
try:
import enaml
except ImportError:
| if six.PY3:
logger.exception(py3_errmsg)
else:
raise
else:
from .model import (GetLastModel, DisplayHeaderModel, WatchForHeadersModel,
ScanIDSearchModel)
with enaml.imports():
from .view import (GetLastView, GetLastWindow, WatchForHeadersView,
... |
rapydo/do | controller/commands/swarm/join.py | Python | mit | 1,350 | 0.000741 | import typer
from controller import log
from controller.app import Application
from controller.deploy.docker import Docker
@Application.app.command(help="Provide instructions to j | oin new nodes")
def join(
manager: bool = typer.Option(
False, "--manager", show_default=False, help="join new node with manager role"
)
) -> None:
Application.print_command(
Application.serialize_param | eter("--manager", manager, IF=manager),
)
Application.get_controller().controller_init()
docker = Docker()
manager_address = "N/A"
# Search for the manager address
for node in docker.client.node.list():
role = node.spec.role
state = node.status.state
availability = nod... |
impactlab/jps-handoff | webapp/viewer/migrations/0007_auto_20150408_1402.py | Python | mit | 935 | 0.00107 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('viewer', '0006_meter_on_auditlist'),
]
operations = [
migrations.CreateModel(
name='Group',
fields=[... | ),
('name', models.CharField(max_length=64)),
],
options={
},
bases=(models.Model,),
),
migrations.RenameField(
model_name='profiledatapoint',
old_name='kwh',
new_name='kw',
),
migrations.... | anyField(to='viewer.Group'),
preserve_default=True,
),
]
|
jwlawson/tensorflow | tensorflow/contrib/py2tf/pyct/parser.py | Python | apache-2.0 | 1,152 | 0.003472 | # Copyright 2017 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... | under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# Se | e the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Converting code to AST.
Adapted from Tangent.
"""
from __future__ import absolute_import
from __future__ import division
from __future_... |
juliarizza/certificate_generator | models/mail.py | Python | gpl-3.0 | 2,605 | 0.001153 | # -*- coding: utf-8 -*-
import os
import ConfigParser
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from global_functions import app_dir
class Mailer():
"""
Instance to manage the mailing.
... | address=unicode(self.Config.get("Contact", "address")),
phone=unicode(self.Config.get("Contact", "phone"))
)
msg.attach(MIMEText(unicode(body), 'plain', | 'utf-8'))
# Add the certificate file
attachment = open(unicode(path), "rb")
filename = os.path.basename(unicode(path))
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(u'Content-Dispos... |
bpaniagua/SPHARM-PDM | Modules/Scripted/ShapeAnalysisModule/ShapeAnalysisModule.py | Python | apache-2.0 | 88,012 | 0.010192 | import os, sys
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
import csv
from slicer.util import VTKObservationMixin
import platform
import time
import urllib
import shutil
from CommonUtilities import *
from packaging import version
def _setSectionResizeMode(head... | ocess = self.getWidget('label_RescaleSegPostProcess')
self.RescaleSegPostProcess = self.getWidget('checkBox_RescaleSegPostProcess')
self.sx = self.getWidget('SliderWidget_sx')
| self.sy = self.getWidget('SliderWidget_sy')
self.sz = self.getWidget('SliderWidget_sz')
self.label_sx = self.getWidget('label_sx')
self.label_sy = self.getWidget('label_sy')
self.label_sz = self.getWidget('label_sz')
self.LabelState = self.getWidget('checkBox_LabelState')
self.label_ValueLabelN... |
fregaham/DISP | formencode/validators.py | Python | gpl-2.0 | 71,779 | 0.001936 | ## FormEncode, a Form processor
## Copyright (C) 2003, Ian Bicking <ianb@colorstudy.com>
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or ... | . Subclasses are not allowed.
Examples::
>>> cint = ConfirmType(subclass=int)
>>> cint.to_python(True)
True
>>> cint.to_python('1')
Traceback (most recent call last):
...
Invalid: '1' is not a subclass of <type 'int'>
>>> cintfloat = Confirm... | oat.from_python(1)
(1, 1)
>>> cintfloat.to_python(None)
Traceback (most recent call last):
...
Invalid: None is not a subclass of one of the types <type 'float'>, <type 'int'>
>>> cint2 = ConfirmType(type=int)
>>> cint2(accept_python=False).from_python(True)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.