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 |
|---|---|---|---|---|---|---|---|---|
rfmcpherson/killerbee | killerbee/GoodFETAVR.py | Python | bsd-3-clause | 5,235 | 0.025788 | #!/usr/bin/env python
# GoodFET SPI and SPIFlash Client Library
#
# (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
#
# This code is being rewritten and refactored. You've been warned!
import sys, time, string, cStringIO, struct, glob, os;
from GoodFET import GoodFET;
class GoodFETAVR(GoodFET):
AVRAP... | ega88",
0x9403: "ATmega16",
0x9401: "ATmega161",
0x9404: "ATmega162",
0x9402: "ATmega163",
0x9407: "ATmega165",
0x9406: "ATmega | 168",
0x9405: "ATmega169",
0x9502: "ATmega32",
0x958a: "ATmega32U2", #TODO add the other U series.
0x9501: "ATmega323",
0x9503: "ATmega325",
0x9504: "ATmega3250",
0x9503: "ATmega329",
0x9504: "ATmega3290",
0x9507: "ATmega406",
0x9602: "ATme... |
zinderud/ysa | python/first/inheritance.py | Python | apache-2.0 | 468 | 0.027778 |
class Hayvan:
def __init__(self,isim, renk):
self.isim=isim
self.renk=renk
def yuru(self):
print(self.isim+" yurumeye basladi")
def ye(self):
print(self.isim+" yemeye basladi")
class Fare(Hayvan):
def __init__(self,isim,renk):
super().__init__(isim,ren... | my_fare.yuru();
my_f | are.ye() |
franciscogarate/pyliferisk | Examples/Example_2_2_3b.py | Python | gpl-3.0 | 608 | 0.021382 | #!/usr/bin/python
from pyliferisk import MortalityTable
from pylife | risk.mortalitytables import GKM95
import numpy as np
mt = MortalityTable(nt=GKM95)
x = 40 #age
n = 20 #horizon
C = 10000 #capital
i = 0.03 #interest rate
payments = []
for t in range(0,n):
payments.append((mt.lx[x+t] - mt.lx[x+t+1]) / mt.lx[x] * | C)
discount_factor = []
for y in range(0,n):
discount_factor.append(1 / (1 + i) ** (y + 0.5))
print('{0:5} {1:10} {2:10}'.format(' t', 'factor', 'payment'))
for t in range(0,n):
print('{0:2} {1:10} {2:10}'.format(t, np.around(discount_factor[t], 5), np.around(payments[t], 4)))
|
0xMF/pelican | pelican/urlwrappers.py | Python | agpl-3.0 | 2,731 | 0 | import os
import functools
import logging
import six
from pelican.utils import (slugify, python_2_unicode_compatible)
logger = logging.getLogger(__name__)
@python_2_unicode_compatible
@functools.total_ordering
class URLWrapper(object):
def __init__(self, name, settings):
# next 2 lines are r | edundant with the setter of the name property
# but are here for clarity
self.settings = settings
self._name = name
self.slug = slugify(name, self.settings.get('SLUG_SUBSTITUTIONS', ()))
self.name = name
@property
def name(self):
return self._name
@name.sett... | , name):
self._name = name
self.slug = slugify(name, self.settings.get('SLUG_SUBSTITUTIONS', ()))
def as_dict(self):
d = self.__dict__
d['name'] = self.name
return d
def __hash__(self):
return hash(self.slug)
def _key(self):
return self.slug
de... |
nuncjo/Delver | delver/parser.py | Python | mit | 2,824 | 0.001416 | # -*- coding:utf-8 -*-
from urllib.parse import urlparse
from lxml import html
from lxml.html.clean import Cleaner
from .forms import FormWrapper
from .helpers import (
match_form,
filter_element
)
class HtmlParser:
""" Parses response content string to valid html using `lxml.html`
"""
def __i... | ed_url = urlparse(self._url)
self._html_tree.make_links_absolute(
'{url.scheme}://{url.netloc}/'.format(url=parsed_url),
resolve_base_href=True
)
def find_links(self, tags=None, filters=None, match=' | EQUAL'):
""" Find links and iterate through them checking if they are matching given filters and
tags
usage::
>>> import requests
>>> response = requests.get('https://httpbin.org/links/10/0')
>>> tags = ['style', 'link', 'script', 'a']
>>> parser = HtmlParser(re... |
Nitrate/Nitrate | src/tcms/issuetracker/migrations/0005_adjust_issue_report_fields.py | Python | gpl-2.0 | 1,490 | 0.002013 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-29 13:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("issuetracker", "0004_data_migration_set_bugzilla_to_allow_add_case_to_issue"),
]
operations = [
migrations.RemoveFi... | name="issue_report_fmt",
),
migrations.AddField(
model_na | me="issuetracker",
name="issue_report_templ",
field=models.CharField(
blank=True,
default="",
help_text="The issue content template, which could be arbitrary text with format arguments. Nitrate provides these format arguments: <code>TestBuild.name<... |
kienpham2000/stockdelta-api | stockdelta/api/alerts.py | Python | mit | 717 | 0 | from firebase import firebase
from flask import request
from flask.ext.restful import Resource
class BaseAlert(Resource):
db = firebase.FirebaseApplication(
dsn='https://stockdelta.firebaseio.com/',
authentication=None)
class Alerts(BaseAlert):
def get(self):
result = self.db.get(url... | ,"active": Tru | e}')
print result
return result
class Alert(BaseAlert):
def get(self, alert_id):
return {"an alert": alert_id}
|
wireservice/agate-excel | docs/conf.py | Python | mit | 7,310 | 0.006156 | # -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
impo... | '),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = Non | e
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX pre... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/papyon/sip/call_manager.py | Python | gpl-3.0 | 56 | 0.017857 | ../../../../../share/pyshared/papyon | /sip/call_manager.py | |
michath/ConMonkey | testing/mozbase/mozdevice/tests/sut_mkdir.py | Python | mpl-2.0 | 2,854 | 0.001051 | # Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
import mozdevice
import mozl | og
import unittest
from sut import MockAgent
class M | kDirsTest(unittest.TestCase):
def test_mkdirs(self):
subTests = [{'cmds': [('isdir /mnt/sdcard/baz/boop', 'FALSE'),
('isdir /mnt', 'TRUE'),
('isdir /mnt/sdcard', 'TRUE'),
('isdir /mnt/sdcard/baz', 'FALSE'),
... |
proxama/zorp | zorp/serialiser.py | Python | mit | 566 | 0.001767 | """
Zorp serialiser
"""
from bson import BSON
class Serialiser(object):
"""
This is simply a wrapper | for the bson encoder/decoder
that can deal with non-dict types
"""
WRAPPER = "data"
@staticmethod
def encode(obj):
"""
Wrap the object in a dict and bson encode it
"""
return BSON.encode({
Serialiser.WRAPPER: obj
})
@staticmethod
def de... | )[Serialiser.WRAPPER]
|
tulsluper/sanscript | apps/da/scripts/form_capacity.py | Python | gpl-3.0 | 6,110 | 0.002782 | #!/usr/bin/env python3
import os
from settings import JSONDIR, logging
from defs import load_data, dump_data
def sort_storage_records(records, sorted_systems):
try:
records.sort(key=lambda x: sorted_systems.index(x['Storage']))
except:
pass
return records
def sum_3par():
capD = {}
... | AllocCap'],
'RawFree': record['FreeCap'],
}
for key, val in xdict.items():
xdict[key] = float(val)/1024/1024
capD[record['Storage']] = xdict
return capD
def su | m_eva():
capD = {}
filepath = os.path.join(JSONDIR, 'eva', 'system')
data = load_data(filepath, [])
for record in data:
xdict = {
'RawTotal': record['totalstoragespace'],
'RawData': record['totalstoragespace'],
'RawSpare': 0,
'RawAllocated': record... |
openthread/openthread | tools/harness-automation/cases_R140/router_5_5_2.py | Python | bsd-3-clause | 1,876 | 0 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notic... | wing disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS... | IMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUT... |
jantman/pymonitoringapi | examples/get_service_status.py | Python | lgpl-3.0 | 2,213 | 0.003615 | #!/usr/bin/env python
"""
pymonitoringapi example script to find the server type
and version of our monitoring server.
"""
import optparse
import sys
import os
import pprint
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../")))
from pymonitoringapi import MonitoringAPI
V... | (i.e. http://host.example.com/nagios/)')
parser.add_option('-c', '--cgibin', dest='cgibin', default='cgi-bin/',
help='path to nagios cgi-bin directory, rel | ative to url (default: cgi-bin/)')
parser.add_option('-v', '--verbose', dest='verbose', default=False, action='store_true',
help='verbose (debug-level) output')
parser.add_option('-H', '--host', dest='host',
help='hostname to check status for')
parser.add_optio... |
blundeln/pylens | scripts/generate_docs.py | Python | bsd-3-clause | 5,581 | 0.023114 | #
# Copyright (c) 2010-2011, Nick Blundell
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of cond... | IAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABI | LITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
#
# Author: Nick Blundell <blundeln [AT] gmail [DOT] com>
# Organisation: www.nickblundell.org.uk
#
# Description:
#
#
import os
import sys
import re
impor... |
googleapis/google-resumable-media-python | google/_async_resumable_media/_upload.py | Python | apache-2.0 | 37,337 | 0.000214 | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | from an HTTP response.
| Args:
response (object): The HTTP response object.
Raises:
NotImplementedError: Always, since virtual.
"""
raise NotImplementedError("This implementation is virtual.")
@staticmethod
def _get_body(response):
"""Access the response body from an HTTP r... |
GoogleCloudPlatform/training-data-analyst | quests/sparktobq/spark_analysis.py | Python | apache-2.0 | 2,849 | 0.004563 |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--bucket", help="bucket for input and output")
args = parser.parse_args()
BUCKET = args.bucket
from pyspark.sql import SparkSession, SQLContext, Row
spark = SparkSession.builder.appName("kdd").getOrCreate()
sc = spark.sparkContext
data_file = "g... | duration=int(r[0]),
protocol_type=r[1],
service=r[2],
flag=r[3],
src_bytes=int(r[4]),
dst_bytes=int(r[5]),
wrong_fragment=int(r[7]),
urgent=int(r[8]),
hot=int(r[9]),
num_failed_logins=int(r[10]),
num_compromised=int(r[12]),
su_attempted=r[14],
num_root=i | nt(r[15]),
num_file_creations=int(r[16]),
label=r[-1]
)
)
#parsed_rdd.take(5)
sqlContext = SQLContext(sc)
df = sqlContext.createDataFrame(parsed_rdd)
connections_by_protocol = df.groupBy('protocol_type').count().orderBy('count', ascending=False)
connections_by_protocol.show()
df.registerTempTable("connectio... |
MungoRae/home-assistant | homeassistant/components/sensor/zoneminder.py | Python | apache-2.0 | 3,361 | 0 | """
Support for ZoneMinder Sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.zoneminder/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFOR | M_SCHEMA
from homeassistant.const import STATE_UNKNOWN
from homea | ssistant.helpers.entity import Entity
import homeassistant.components.zoneminder as zoneminder
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['zoneminder']
CONF_INCLUDE_ARCHIVED = "include_archived"
DEFAULT_INCLUDE_ARCHIVED = False
PLATFORM_SCHEMA = PLATF... |
biotty/rmg | graphics/py/posterize.py | Python | bsd-2-clause | 3,589 | 0.002229 | #!/usr/bin/env python3
#
# (c) Christian Sommerfeldt OEien
# All rights reserved
from rmg.color import Color, InkColor, white_ink
from rmg.board import Photo, Image, Board
from rmg.plane import XY
from argparse import ArgumentParser
from sys import stderr
from math import sqrt, floor
from copy import copy
... | ring row %d\r" % (row,))
for column in range(q.width):
r.put(ink_post(column, row))
r.close()
status("rendered %dx%d image\n" % ( | q.width, q.height))
|
Glottotopia/aagd | moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/util/diff_html.py | Python | mit | 5,991 | 0.00434 | # -*- coding: iso-8859-1 -*-
"""
MoinMoin - Side by side diffs
@copyright: 2002 Juergen Hermann <jh@web.de>,
2002 Scott Moonen <smoonen@andstuff.org>
@license: GNU GPL, see COPYING for details.
"""
from MoinMoin.support import difflib
from MoinMoin.wikiutil import escape
def i... | n (optional)
@param old_top_class: Custom class for <td> with old_top content (optional)
@param new_top_class: Custom class for <td> with new_top content (option | al)
@param old_bottom_class: Custom class for <td> with old_bottom content (optional)
@param new_bottom_class: Custom class for <td> with new_bottom content (optional)
"""
_ = request.getText
t_line = _("Line") + " %d"
seq1 = old.splitlines()
seq2 = new.splitlines()
s... |
hail-is/hail | hail/python/hailtop/aiocloud/aiogoogle/client/iam_client.py | Python | mit | 272 | 0.003676 | from .base_client impor | t GoogleBaseClient
class GoogleIAmClient(GoogleBaseClient):
def __init__(self, project, **kwargs):
super().__init__(f'https://iam.googleapis.com/v1/projects/{project}', **kwargs)
# https://cloud.google.com/iam/docs/ref | erence/rest
|
forfuturellc/peterhellberg | peterhellberg/main.py | Python | mit | 1,258 | 0.000795 | '''
The Core of peterhellberg
'''
import requests
from . import metadata
def parse(url, use_ssl=False):
'''Send a http request to the remote server
Return the response, as a dictionary
Raises requests.exceptions.ConnectionError in event of a network error
Raises requests.exceptions.HTTPError in even... | if isinstance(exception, requests.exceptions.ConnectionError):
print("error: network error")
elif isinstance(exception, requests.exceptions.HTTPError):
print("error: invalid HTTP response")
elif isinstance(exception, requests.except | ions.Timeout):
print("error: request timeout")
elif isinstance(exception, requests.exceptions.TooManyRedirects):
print("error: too many redirects")
else:
print("error: unknown exception")
print exception
|
algorythmic/bash-completion | test/t/test_java.py | Python | gpl-2.0 | 1,508 | 0 | import pytest
from conftest import is_bash_type
@pytest.mark.bashcomp(
pre_cmds=("CLASSPATH=$PWD/java/a:$PWD/java/bashcomp.jar",)
)
class TestJava:
@pytest.fixture(scope="class")
def can_list_jar(self, bash):
return (
is_bash_type(bash, "zipinfo")
or is_bash_type(bash, "un... | if can_list_jar:
assert completion == "b bashcomp.jarred c. toplevel".split()
else:
assert completion == "b c.".split()
@pytest.mark. | complete("java -classpath java/bashcomp.jar ")
def test_3(self, completion, can_list_jar):
if can_list_jar:
assert completion == "bashcomp.jarred toplevel".split()
else:
assert not completion
@pytest.mark.complete("java -cp java/bashcomp.jar:java/a/c ")
def test_4(se... |
cloudera/hue | desktop/core/ext-py/pycryptodomex-3.9.7/lib/Cryptodome/SelfTest/Util/test_strxor.py | Python | apache-2.0 | 10,618 | 0.00292 | #
# SelfTest/Util/test_strxor.py: Self-test for XORing
#
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided tha... | term2 = unhexlify(b"383d4ba02057331 | 4395b")
self.assertRaises(TypeError, strxor, term1, term2, output=term1)
def test_output_ro_memoryview(self):
"""Verify result cannot be stored in read-only memory"""
term1 = memoryview(unhexlify(b"ff339a83e5cd4cdf5649"))
term2 = unhexlify(b"383d4ba020573314395... |
smly/nips17_adversarial_attack | defense/import_from_tf_baseline/dump_ens_adv_inception_resnet_v2.py | Python | apache-2.0 | 30,348 | 0 | # -*- coding: utf-8 -*-
import os
import sys
import math
from pathlib import Path
import scipy.misc
import h5py
import numpy as np
import tensorflow as tf
import torch
import torch.nn as nn
import click
from models.slim.nets.inception_resnet_v2 import (
inception_resnet_v2,
inception_resnet_v2_arg_scope)
sl... | nch_3/Conv2d_0b_1x1', outdir=outdir)
def dump_block35(sess, name='Repeat/block35_1', outdir='./dump'):
dump_conv2d(sess, name=name+'/Branch_0/Conv2d_1x1', outdir=outdir)
dump_conv2d(sess, name=name+'/Branch_1/Conv2d_0a_1x1', outdir=outdir)
dump_conv2d(sess, name=name+'/Branch_1/Conv2d_0b_3x3', outdir=outd... | _conv2d(sess, name=name+'/Branch_2/Conv2d_0c_3x3', outdir=outdir)
dump_conv2d_nobn(sess, name=name+'/Conv2d_1x1', outdir=outdir)
def dump_mixed_6a(sess, name='Mixed_6a', outdir='./dump'):
dump_conv2d(sess, name=name+'/Branch_0/Conv2d_1a_3x3', outdir=outdir)
dump_conv2d(sess, name=name+'/Branch_1/Conv2d_0a... |
eamars/webserver | site-package/index2.py | Python | mit | 3,741 | 0.00294 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import mysql.connector
import datetime
HEADER_TEMPLATE = \
"HTTP/1.1 200 OK\r\n" \
"Server: webhttpd/2.0\r\n" \
"Cache-Control: no-cache, no-store, must-revalidate\r\n" \
"Connection: keep-alive\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
... | border-collapse: collapse;
}
table th {
background: #00cccc;
color: #fff;
text-transform: uppercase;
font-size: 12px;
... | }
h3 {
font:1.2em normal Arial,sans-serif;
color:#34495E;
text-align:center;
letter-spacing:-2px;
font-size:2.5em;
m... |
entrepidea/projects | python/tutorials/algo/leetcode/easy/is_sebsequence.py | Python | gpl-3.0 | 641 | 0.014041 | """
Given two strings s and | t, return true if s is a subsequence of t, or false otherwise.
https://leetcode.com/problems/is-subsequence/
Date: 10/29/21
"""
def is_seq(s,t):
ls = list(s)
lt = list(t)
idx = []
for e in ls:
if e in lt:
idx.append(lt.index(e))
if len(idx)>1 and idx[len(idx)-1]<idx[le... | 'ahbgdc'
print(is_seq(s,t))
s = 'axc'
t = 'ahbgdc'
print(is_seq(s,t))
s = 'acb'
t = 'ahbgdc'
print(is_seq(s,t))
|
beproud/bpcommons | tests/test_forms_field.py | Python | bsd-2-clause | 1,310 | 0.00229 | #:coding=utf-8:
from django.test import TestCase as DjangoTestCase
from django.forms import Form
from beproud.django.commons.forms import EmailField
__all__ = (
'EmailFieldTest',
'JSONFormFieldTest',
'JSONWidgetTest',
)
class EmailTestForm(Form):
email = EmailField(label="email")
class EmailFiel... | e(form.is_valid())
def test_keitai_email(self):
form = EmailTestForm({"email": "-spam..eggs-@softbank.ne.jp"})
self.assertTrue(form.is_valid())
form = EmailTestForm({"email": ".*&$.-spam..!!eggs!!-.*.@ezweb.ne.jp"})
self.assertTrue(form.is_valid())
def test_plus_email(self):
... | email(self):
form = EmailTestForm({"email": "aaa spam+extra@eggs.com email@email.com"})
self.assertFalse(form.is_valid())
def test_longtld(self):
form = EmailTestForm({"email": "spam@eggs.engineer"})
self.assertTrue(form.is_valid())
def test_punycode(self):
form = Email... |
plilja/project-euler | problem_16/power_digit_sum.py | Python | apache-2.0 | 111 | 0.009009 | def power_digit_sum | (exponent):
power_of_2 = str(2 ** exponent)
return sum([int(x) for x in power_of | _2]) |
xalt/xalt | proj_mgmt/py_build_tools/build_python_filter_routine.py | Python | lgpl-2.1 | 3,443 | 0.01946 | # -*- python -*-
# Git Version: @git@
#-----------------------------------------------------------------------
# XALT: A tool that tracks users jobs and environments on a cluster.
# Copyright (C) 2013-2014 University of Texas at Austin
# Copyright (C) 2013-2014 University of Tennessee
#
# This library is free softwar... | ment("--confFn", dest='confFn', action="store", help="python config file")
parser.add_argument("--xalt_cfg", dest='xaltCFG', action="store", help="XALT std config")
parser.add_argument("--input", dest='input', action="store", help="input template file")
parser.add_argument("--outpu... | action="store", help="output file")
args = parser.parse_args()
return args
def convert_template(pattern, replaceA ,inputFn, outputFn):
try:
f = open(inputFn,"r")
except IOError as e:
print("Unable to open \"%s\", aborting!" % (inputFn))
sys.exit(-1)
outA = []
for line in f:
... |
lnielsen/invenio | invenio/ext/babel/selectors.py | Python | gpl-2.0 | 2,593 | 0.00887 | # -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2012, 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option... | This information will then be available in the session['ln'].
"""
from invenio.base.i18n import wash_language
required_ln = None
passed_ln = request.values.get('ln', type=str)
if passed_ln:
## If ln is specified explictly as a GET or POST argument
## let's take it!
require... | quired_ln:
## But only if it was a valid language
required_ln = None
if required_ln:
## Ok it was. We store it in the session.
session["ln"] = required_ln
if not "ln" in session:
## If there is no language saved into the session...
user_language = current_... |
OpusVL/odoo | addons/stock/wizard/make_procurement_product.py | Python | agpl-3.0 | 5,960 | 0.003859 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | of the user currently logged in
@param fields: List of fields for which we want default values
@param context: A standard dictionary
@return: A dictionary which of fields with values.
"""
if context is None:
context = {}
record_id = context.get('active_id')
... | 'active_model') == 'product.template':
product_ids = self.pool.get('product.product').search(cr, uid, [('product_tmpl_id', '=', context.get('active_id'))], context=context)
if len(product_ids) == 1:
record_id = product_ids[0]
else:
raise orm.except_orm... |
dantebarba/docker-media-server | plex/Sub-Zero.bundle/Contents/Libraries/Shared/subliminal_patch/refiners/omdb.py | Python | gpl-3.0 | 2,505 | 0.001597 | # coding=utf-8
import os
import subliminal
import base64
import zlib
from subliminal import __short_version__
from subliminal.refiners.omdb import OMDBClient, refine as refine_orig, Episode, Movie
from subliminal_patch.http import TimeoutSession
class SZOMDBClient(OMDBClient):
def __init__(self, version=1, sessio... | # get the response as json
j = r.json()
# check response status
if j['Response'] == 'False':
return N | one
return j
def refine(video, **kwargs):
refine_orig(video, **kwargs)
if isinstance(video, Episode) and video.series_imdb_id:
video.series_imdb_id = video.series_imdb_id.strip()
elif isinstance(video, Movie) and video.imdb_id:
video.imdb_id = video.imdb_id.strip()
omdb_client =... |
dataplumber/nexus | analysis/tests/algorithms/StandardDeviationSearch_test.py | Python | apache-2.0 | 9,139 | 0.002954 | """
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology. All rights reserved
"""
import json
import unittest
import urllib
from multiprocessing.pool import ThreadPool
from unittest import skip
import numpy as np
from mock import Mock
from nexustiles.model.nexusmodel import Tile, BBox
from... | response = self.fetch(path)
self.assertEqual(200, response.code)
@skip("Integration test only. Works only if you have Solr and Cassandra running locally with data ingested")
def test_integration_all_in_tile(self):
params = {
"ds": "AVHRR_OI_L4_GHRSST_NCEI_CLIM",
... | longitude": "-177.775",
"latitude": "-78.225",
"day": "1"
}
path = StandardDeviationSearch.StandardDeviationSearchHandlerImpl.path + '?' + urllib.urlencode(params)
response = self.fetch(path)
self.assertEqual(200, response.code)
print response.body
... |
mozilla/webowonder | bin/generate_l10n_css_overides.py | Python | bsd-3-clause | 1,931 | 0.00725 | #!/usr/bin/env python
"""
{'friendly_name': '',
'string_id': '',
'css_selector': ''},
"""
elements = [
{'friendly_name': 'Golden Tickets',
'string_id': 'magic-tickets',
'css_selector': '#magic-tickets'},
{'friendly_name': 'Marvels Await Poster',
'string_id': 'marve... | 'submit-demo',
'css_selector': '#submit-demo a'},
{'friendly_name' | : 'Mozilla Presents',
'string_id': 'mozilla-presents',
'css_selector': '#home-link'},
{'friendly_name': 'This Way',
'string_id': 'this-way',
'css_selector': '#this-way'},
{'friendly_name': 'That Way',
'string_id': 'that-way',
'css_selector': '#that-way'},
... |
mrdon/flask | werkzeug/wrappers.py | Python | bsd-3-clause | 76,207 | 0.000276 | # -*- coding: utf-8 -*-
"""
werkzeug.wrappers
~~~~~~~~~~~~~~~~~
The wrappers are simple request and response objects which you can
subclass to do whatever you want them to do. The request object contains
the information transmitted by the client (webbrowser) and the response
object contains al... | to the request object, there is also a class called `Request` which
subclasses `BaseRequest` and all the important mixins.
It's a good idea to create a custom subclass of the :class:`BaseRequest`
and add missing functionality either via mixins o | r direct implementation.
Here an example for such subclasses::
from werkzeug.wrappers import BaseRequest, ETagRequestMixin
class Request(BaseRequest, ETagRequestMixin):
pass
Request objects are **read only**. As of 0.5 modifications are not
allowed in any place. Unlike the l... |
dials/dials | tests/algorithms/indexing/test_max_cell.py | Python | bsd-3-clause | 2,598 | 0.001155 | from __future__ import annotations
import random
import pytest
import scitbx.matrix
from cctbx import sgtbx
from cctbx.sgtbx import bravais_types
from dials.algorithms.indexing.max_cell import find_max_cell
from dials.array_family import flex
@pytest.fixture(params=bravais_types.acentric)
def setup(request):
... | ace_group_symbol)
cs = sgi.any_compatible_crystal_symmetry(volume=random.randint(1e4, 1e6))
ms = cs.build_miller_set(anomalous_flag=True, d_min=3).expand_to_p1()
# the reciprocal matrix
B = scitbx.matrix.sqr(cs.unit_cell().fractionalization_matrix()).transpose()
# randomly select 25% of reflection... | ction_table()
refl["rlp"] = B.elems * ms.indices().as_vec3_double()
refl["imageset_id"] = flex.int(len(refl))
refl["xyzobs.mm.value"] = flex.vec3_double(len(refl))
d = {}
d["crystal_symmetry"] = cs
d["reflections"] = refl
return d
@pytest.mark.parametrize(
"histogram_binning,nearest_n... |
stefanseefeld/qmtest | qm/label.py | Python | gpl-2.0 | 6,102 | 0.003933 | ########################################################################
#
# File: label.py
# Author: Alex Samuel
# Date: 2001-03-17
#
# Contents:
# Label
#
# Copyright (c) 2001, 2002 by CodeSourcery, LLC. All rights reserved.
#
# For license terms see the file COPYING.
#
#######################################... | labels:
if not result:
# If the label is empty so far, l is the first component.
result = l
elif result and result[-1] == self._sep:
# If the label thus far ends with a sepa | rator, we do not
# want to add another one.
result += l
else:
result = result + self._sep + l
return self.__class__(result)
def Split(self):
"""Split the label into a pair '(directory, basename)'.
returns -- A pair '... |
phelmig/outside_ | mvp/outside/frontend_auth/__init__.py | Python | mit | 1,006 | 0.006958 | """
frontend_auth is a wrapper around the `django.contrib.auth.view` Views.
* **templates/** Contains the templates for login / pw change / pw reset views and the password_reset emails
* **auth_mixins.py** Provides a simple mixin that tests if `instance.agency == request.user.agencyemployee.agency`, more to come
... | simple wrapper around `django.contrib.auth.forms` to use placeholders instead of labels
* **urls.py** Creates `django.contrib.auth.views` for with the following names:
* login - Login
* logout - Logout -> Redirect to 'login'
* change_password - unused view to change the password
* p... | the requested pw reset
* password_reset_confirm - The view after the user clicked on the reset link in the mail
* password_reset_complete - The view after the manual password reset
""" |
HewlettPackard/python-proliant-sdk | examples/Redfish/ex31_set_license_key.py | Python | apache-2.0 | 2,431 | 0.014809 | # Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 requ... | = "None"
# iLO_password = "None"
# When running remotely connect using the iLO secured (https://) address,
# iLO account name, and password to send https requests
# | iLO_https_url acceptable examples:
# "https://10.0.0.100"
# "https://f250asha.americas.hpqcorp.net"
iLO_https_url = "https://10.0.0.100"
iLO_account = "admin"
iLO_password = "password"
# Create a REDFISH object
try:
REDFISH_OBJ = RedfishObject(iLO_https_url, iLO_account, i... |
jasonstack/cassandra | pylib/cqlshlib/cqlshhandling.py | Python | apache-2.0 | 10,355 | 0.001545 | # 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... | s = r'''
<helpCommand> ::= ( "HELP" | "?" ) [topic]=( /[a-z_]*/ )*
;
'''
cqlsh_tracing_cmd_syntax_rules = r'''
<tracingCommand> ::= "TRACING" ( switch=( "ON" | "OFF" ) )?
;
'''
cqlsh_expand_cmd_syntax_rules = r'''
<expandCommand> ::= "EXPAND" ( switch=( "ON" | "OFF" ) )?
... | ;
'''
cqlsh_login_cmd_syntax_rules = r'''
<loginCommand> ::= "LOGIN" username=<username> (password=<stringLiteral>)?
;
'''
cqlsh_exit_cmd_syntax_rules = r'''
<exitCommand> ::= "exit" | "quit"
;
'''
cqlsh_clear_cmd_syntax_rules = r'''
<clearCommand> ::= "CLEAR" | "CLS"
... |
vrutkovs/dogtail | dogtail/i18n.py | Python | gpl-2.0 | 10,076 | 0.002084 | # -*- coding: utf-8 -*-
"""
Internationalization facilities
Authors: David Malcolm <dmalcolm@redhat.com>
"""
__author__ = """David Malcolm <dmalcolm@redhat.com>, Zack Cerza <zcerza@redhat.com>"""
import config
import os
import re
import gettext
from logging import debugLogger as logger
from __builtin__ import unic... | match = re.match(inString, outString)
matched = match is not None
return matched
matched = False
# the 'ts' variable keeps track of whether we're working with
# translated strings. it's only used for debugging purposes.
#ts = 0
# print string, str(self)
... | ingsMatch(translatedString, string)
if not matched:
matched = translatedString == string
if matched:
return matched
# ts=0
return stringsMatch(self.untranslatedString, string)
def __str__(self):
"""
Provide a meaningful debug v... |
DarrenBellew/CloudCompDT228-3 | Lab3/1000FibNumber.py | Python | mit | 158 | 0.006329 | var = 2
start = 1
last = 1
while(len(str(start)) < 1000):
var=var+1
temp = start
s | tart = start+last
| last = temp
print("Final: " + str(var))
|
walchko/pygecko | dev/services/test.py | Python | mit | 1,384 | 0.001445 | #!/usr/bin/env python3
#
#
# copyright Kevin Walchko
#
# Basically a rostopic
from __future__ import print_function
import argparse
import time
# from pygecko import TopicSub
from pygecko.transport import zmqTCP, GeckoCore
from pygecko.multiprocessing import GeckoPy
from pygecko.test import GeckoSimpleProcess
# from ... | eckopy.Subscriber([topic], f)
geckopy.spin()
if __name__ == '__main__':
p = GeckoSimpleProcess()
p.start(func=subscriber, name='subscriber', kwargs=args)
# while True:
# try:
# time.sleep(1)
# except KeyboardInterrupt:
# break
#
# # shutdown the proces... | .1)
|
alcides/rdflib | rdflib/sparql/sql/RelationalOperators.py | Python | bsd-3-clause | 4,107 | 0.012661 |
class NoResultsException(Exception):
def __init__(self):
Exception("No Results.")
class RelationalOperator(object):
def __init__(self, parent):
self.parent = parent
def GenSql(self, sqlBuilder):
"""
Main external interface for SQL generation.
The client co... | child classes.")
def AdjustCostEstimate(self,cost,colDist):
# Returns (cost, colDist, varSet)
raise Exception("AdjustCostEstimate must be overridden in child classes.")
class RelationalTerminalExpOperator(object):
def BuildTerminalExpression(self,sqlBuilder, tupleTable):
raise Exc... | ust be overridden in child classes.")
def BuildSqlExpression(sqlBuilder,tupleTable):
raise Exception("BuildSqlExpression must be overridden in child classes.")
def GetDataTypeExp(self,sqlBuilder):
raise Exception("GetDataTypeExp must be overridden in child classes.")
def Ge... |
fraoustin/flask-monitor | flask_monitor/util.py | Python | gpl-2.0 | 634 | 0.015773 | # -*- coding: utf-8 -*-
def toflat(obj, ns=""):
res = {}
for key in obj:
if type(obj[key]) is dict:
subdict = toflat(obj[key], "%s%s" % (ns,key[0].upper()+key[1:] | ))
for k in subdict:
res[k[0].upper()+k[1:]] = subdict[k]
else:
res["%s%s" % (ns, key[0].upper()+key[1:])] = str | (obj[key])
return res
def todict(obj):
res = {}
for key in obj:
if type(obj[key]) is dict:
subdict = todict(obj[key])
for k in subdict:
res[k] = subdict[k]
else:
res[key] = obj[key]
return res
|
lucastanure/GoGo-Real-Software | core/communication/serial/serialposix.py | Python | gpl-3.0 | 25,395 | 0.005828 | #!/usr/bin/env python
#
# Python Serial Port Extension for Win32, Linux, BSD, Jython
# module for serial IO for POSIX compatible systems, like Linux
# see __init__.py
#
# (C) 2001-2010 Chris Liechti <cliechti@gmx.net>
# this is distributed under a free software license, see license.txt
#
# parts based on code from Gran... | use defaults from linux otherwise
TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415
TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416
TIOCMBIC = | hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417
TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418
#TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001
TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002
TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') ... |
markflyhigh/incubator-beam | sdks/python/apache_beam/options/pipeline_options_validator_test.py | Python | apache-2.0 | 12,764 | 0.005719 | #
# 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... | []},
]
for case in test_cases:
errors = get_validator(case['temp_location'],
case['staging_location']).validate()
self.assertEqual(
self.check_errors_for_arguments(errors, case['errors']), [])
def test_project(self):
| def get_validator(project):
options = ['--job_name=job', '--staging_location=gs://foo/bar',
'--temp_location=gs://foo/bar']
if project is not None:
options.append('--project=' + project)
pipeline_options = PipelineOptions(options)
runner = MockRunners.DataflowRunne... |
toobaz/pandas | pandas/tests/reshape/test_qcut.py | Python | bsd-3-clause | 6,328 | 0.000474 | import os
import numpy as np
import pytest
from pandas import (
Categorical,
DatetimeIndex,
Interval,
IntervalIndex,
NaT,
Series,
TimedeltaIndex,
Timestamp,
cut,
date_range,
isna,
qcut,
timedelta_range,
)
from pandas.api.types import CategoricalDtype as CDT
from pan... | )
ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0])
result = labels.categories.left.values
assert np.allclose(result, ex_bins[:-1], atol=1e-2)
result = labels.categories.right.values
assert np.allclose(result, ex_bins[1:], atol=1e-2)
ex_levels = cut(arr, ex_bins, include_lowest | =True)
tm.assert_categorical_equal(labels, ex_levels)
def test_qcut_bounds():
arr = np.random.randn(1000)
factor = qcut(arr, 10, labels=False)
assert len(np.unique(factor)) == 10
def test_qcut_specify_quantiles():
arr = np.random.randn(100)
factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0])
... |
jarretraim/euler_py | 1-10/03.py | Python | apache-2.0 | 1,446 | 0.040111 | #!/usr/bin/env python
# Python 3 required
# THIS TAKES WAAAAY TO LONG. ONLY SOLVED IT BY LETTING IT RUN
# OVERNIGHT ACCIDENTALLY :/
import locale
import sys
import math
import timeit
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59... | 3, 197, 199]
def is_prime(num):
for i in PRIMES:
if i >= num:
break
if num % i == 0:
#print ("%d is divisible by %d" % (num, i))
return False
for i in range(PRIMES[-1], int(math.sqrt(num)), 2):
if num % i == 0:
return False
return True
def is_prime2(num):
k = | 3
while k*k <= num:
if num % k == 0:
return False
k += 2
return True
def main():
num = int(sys.argv[1])
print("Factoring %s" % locale.format("%d", num, grouping=True))
if num % 2 == 0:
prime_factors = [2]
else:
prime_factors = []
pager = 0
for i in range(3, num, 2):
if num % i == 0:
print ... |
opesci/devito | benchmarks/user/make-pbs.py | Python | mit | 2,496 | 0.002404 | import os
import click
from benchmark import option_simulation
import devito
@click.group()
def menu():
pass
@menu.command(name='generate')
@option_simulation
@click.option('-nn', multiple=True, default=[1], help='Number of nodes')
@click.option('-ncpus', default=1, help='Number of cores *per node*') # Shoul... | E=openmp
export DEVITO_LOGGING=DEBUG
%(export)s
cd benchmarks/user
""" # noqa
template_cmd = """\
DEVITO_MPI=%(mpi)s mpiexec python benchmark.py bench -P %(problem)s -bm O2 -d %(shape)s -so %(space_order | )s --tn %(tn)s -x 1 --arch %(arch)s -r %(resultsdir)s\
""" # noqa
# Generate one PBS file for each `np` value
for nn in kwargs['nn']:
args['nn'] = nn
cmds = []
for i in kwargs['mpi']:
args['mpi'] = i
cmds.append(template_cmd % args)
cmds = ' \n'.join(cm... |
isolationism/django-cleaver | django_cleaver/imagecreator.py | Python | bsd-3-clause | 2,540 | 0.001575 |
# Python standard library
from os import path, listdir
from ConfigParser import ConfigParser
# Third-party libraries
from imagecraft import ImageGenerator
# Django settings
from django.conf import settings
# This module
from cleaver import ini_to_context, flatten_context
# Retrieve execution params
MEDIA_ROOT = g... | RCE")
if not CLEVERCSS_IMAGE_OUTPUT:
raise ValueError("You must define CLEVERCSS_IMAGE_OUTPUT")
class DynamicImageGenerator(ImageGenerator):
"""Dynamically generates images by using arguments instead of constants"""
#layers = None
_default_source_path = CLEVERCSS_IMAGE_SOURCE
_default_output_path... | ""Constructor"""
self.layers = layers
self.output_filename = output_filename
super(DynamicImageGenerator, self).__init__(color_dict, source_path,
output_path)
def generate_images():
"""Reads the context file and uses it to execute all CLE... |
chtyim/infrastructure-puppet | modules/buildbot_asf/files/configscanner.py | Python | apache-2.0 | 12,920 | 0.016718 | #!/usr/bin/env python
############################################################
# ConfigScanner - A buildbot config scanner and updater #
# Also does ReviewBoard (and at some point Bugzilla?) #
# Built for Python 3, works with 2.7 with a few tweaks #
#####################################################... | s.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se =... | sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""Star... |
DudLab/nanshe | tests/test_nanshe/test_converter.py | Python | bsd-3-clause | 2,908 | 0.005158 | __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Mar 30, 2015 08:25:33 EDT$"
import collections
import json
import os
import os.path
import shutil
import tempfile
import numpy
import h5py
import vigra
import vigra.impex
import nanshe.util.iters
import nanshe.util.xnumpy
import nanshe.io.xtiff
... | 100
)
)
)
):
each_filename = os.path.join(self.temp_dir, "test_tiff_" + str(i) + ".tif")
each_data = se... | numpy.tagging_reorder_array(each_data, to_axis_order="czyxt")[0, 0],
os.path.join(self.temp_dir, "test_tiff_" + str(i) + ".tif"), "")
def test_main(self):
params = {
"axis" : 0,
"channel" : 0,
"z_index" : 0,
"pages_to_chan... |
alexandrucoman/vbox-neutron-agent | neutron/tests/unit/plugins/sriovnicagent/test_pci_lib.py | Python | apache-2.0 | 4,204 | 0 | # Copyright 2014 Mellanox Technologies, 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 t... | s(exc.IpCommandError,
self.pci_wrapper.get_assigned_macs,
[self.VF_INDEX])
def test_get_vf_state_enable(self):
with mock.patch.object(self.pci_wrapper,
"_as_root") as mock_as_root:
mock_as_root.return_val... | result = self.pci_wrapper.get_vf_state(self.VF_INDEX)
self.assertTrue(result)
def test_get_vf_state_disable(self):
with mock.patch.object(self.pci_wrapper,
"_as_root") as mock_as_root:
mock_as_root.return_value = self.VF_LINK_SHOW
r... |
dseredyn/velma_scripts | scripts/test_hierarchy_control.py | Python | bsd-3-clause | 18,738 | 0.007792 | #!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... | autils.MarkerPublisher()
def spin(self):
simulation = True
rospack = rospkg.RosPack()
env_file=rospack.get_path('velma_scripts') + '/data/jar/cabinet_test.env.xml'
srdf_path=rospack.get_path('velma_description') + '/robots/'
print "creating interface for Velma..."
... | .OpenraveInstance()
openrave.startOpenraveURDF(env_file=env_file, viewer=True)
openrave.readRobot(srdf_path=srdf_path)
openrave.setCamera(PyKDL.Vector(2.0, 0.0, 2.0), PyKDL.Vector(0.60, 0.0, 1.10))
velma.waitForInit()
openrave.updateRobotConfigurationRos(velma.js_pos)
... |
libvirt/autotest | client/virt/tests/clock_getres.py | Python | gpl-2.0 | 1,155 | 0.000866 | import logging, os
from autotest_lib.client.common_lib import error
from autotest_lib.client.bin import utils
def run_clock_getres(test, params, env):
"""
Verify if guests using kvm-clock as the time source have a sane clock
resolution.
@param test: kvm test object.
@param params: Dictionary with... | ""
source_name = "test_clock_getres/test_clock_getres.c"
source_name = os.path.join(test.virtdir, "deps", source_name)
dest_name = "/tmp/test_clock_ge | tres.c"
bin_name = "/tmp/test_clock_getres"
if not os.path.isfile(source_name):
raise error.TestError("Could not find %s" % source_name)
vm = env.get_vm(params["main_vm"])
vm.verify_alive()
timeout = int(params.get("login_timeout", 360))
session = vm.wait_for_login(timeout=timeout)
... |
amitsaha/learning | python/collapse_range.py | Python | unlicense | 1,067 | 0.004686 | '''
Given a number o | f integer intervals, collapse them:
Input: [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
Output: [(0, 1), (3, 8), (9, 12)]
'''
def collapse_range(slots):
# order based on the first slot
ordered_slots = sorted(slots, key=lambda range: range[0])
merged_slots = [] |
i = 0
j = 0
while i < len(ordered_slots):
j = i+1
l, u = ordered_slots[i]
while j < len(ordered_slots):
if ordered_slots[i][1] >= ordered_slots[j][0]:
u = ordered_slots[j][1]
i += 1
j += 1
continue
... |
smartybit/stepic_webtech1 | web/hello.py | Python | mit | 221 | 0.027149 | # | !/usr/bin/python
def app(environ, start_response):
request = environ['QUERY_STRING']
start_response("200 OK", [
("Content-Type", "text/plain"),
])
return [request.replace('&','\n') ] | |
RLovelett/qt | doc/src/diagrams/contentspropagation/customwidget.py | Python | lgpl-2.1 | 6,694 | 0.007619 | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of the test suite of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License... | caption.setMargin(2)
layout.addWidget(caption, 1, 0, Qt.AlignCenter | Qt.AlignTop)
if qt == "4.0":
contentsWidget = CustomWidget(label)
contentsWidget.setAttribute(Qt.WA_ContentsPropagated, True)
layout.addWidget(contentsWidget, 0, 1, Qt.AlignCenter)
| caption = QLabel("With WA_ContentsPropagated set", label)
caption.setMargin(2)
layout.addWidget(caption, 1, 1, Qt.AlignCenter | Qt.AlignTop)
elif qt == "4.1":
autoFillWidget = CustomWidget(label)
autoFillWidget.setAutoFillBackground(True)
layout.addWidget(autoFillWidget, 0,... |
eldarion/formly | formly/tests/urls.py | Python | bsd-3-clause | 249 | 0.004016 | from django.conf.urls import include, url
from django.views.generic import T | emplateView
urlpatterns = [
url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", | include("formly.urls", namespace="formly")),
]
|
bl8/bockbuild | packages/glib.py | Python | mit | 1,520 | 0.046711 | class GlibPackage (GnomeXzPackage):
def __init__ (s | elf):
GnomePackage.__init__ (self,
'glib',
version_major = '2.30',
| version_minor = '3')
self.darwin = Package.profile.name == 'darwin'
if Package.profile.name == 'darwin':
#link to specific revisions for glib 2.30.x
self.sources.extend ([
'https://trac.macports.org/export/62644/trunk/dports/devel/glib2/files/config.h.ed',
'https://trac.macports.org/export/87503/tru... |
nestof/domoCore | com/nestof/domocore/domain/Parameter.py | Python | gpl-3.0 | 482 | 0.006224 | # -*- coding: utf-8 -*-
'''
Created on 23 mars 2014
@author: nestof
'''
class Parameter(object):
'''
classdocs
'''
tableName = 'parametrage'
colCodeName = 'code'
colTypeName = 'type'
colValueName = 'valeur'
colCommentName = 'commentaire'
def __init__(self):
... | elf._value = None
| self._comment = None
|
liushu2000/django-crispy-formwizard | contact/views.py | Python | gpl-2.0 | 9,658 | 0.003935 | from django.shortcuts import redirect, render_to_response, render
from django.contrib.formtools.wizard.views import SessionWizardView
from django import forms, http
from models import Contact
from forms import ContactForm2
import collections
from datatableview.views import XEditableDatatableView, DatatableView
from dat... | uestContext
from django.utils import translation
from django.utils.translation import check_for_language
def set_language(request):
next = request.REQUEST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseR... | if hasattr(request, 'session'):
request.session['django_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
translation.activate(lang_code)
return response
@csrf_exempt
def users_plain(request):
#users = Contac... |
MrYsLab/PyMata | examples/digital_analog_io/callback_buttonLed_toggle.py | Python | agpl-3.0 | 2,453 | 0.000408 | #!/usr/bin/env python
"""
Copyright (c) 2015-2017 Alan Yorinks All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
Version 3 as published by the Free Software Foundation; either
or (at your option) any later version.... | ic License for more details.
You should have received a copy of the GNU AFFERO GEN | ERAL PUBLIC LICENSE
along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
This example illustrates using callbacks to toggle an LED. Each time the
button switch is pressed the LED state will toggle to the opposite state.
The latch is re... |
netsoc/admin_utils | freshers_signup.py | Python | gpl-3.0 | 4,811 | 0.002702 | #!/usr/bin/env python3
import datetime
import json
import os
import time
import signal
# attempt to ignore ctrl-z
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
def blinking(string):
return '\33[5m' + string + '\33[0m'
BANNER = """ W e l c o m e t o
______ __
/ ____ \ ___ / /__________ _____
/ / ... | break
except (KeyboardInterrupt, EOFError):
continue
continue
def main():
timestamp = datetime.datetime.now().strftime("%Y-%m-%d")
filename = "freshers_{}.json".format(timestamp)
if not os.path.isfile(f | ilename):
with open(filename, 'w') as f:
json.dump([], f)
signups(filename)
if __name__ == '__main__':
main()
|
rcuza/init | devops/templates/python/python_class.py | Python | isc | 501 | 0 | #!/usr/bin/env python
# encoding: utf-8
"""
${TM_NEW_FILE_BASENAME}.py
Created by ${TM_FULLNAME} on ${TM_DATE}.
Copyright (c) ${TM_YEAR} ${TM_ORGANIZATION_NAME}. All rights reserved.
"""
from __f | uture__ import absolute_import, division, print_func | tion
import sys
import os
import unittest
class ${TM_NEW_FILE_BASENAME}:
def __init__(self):
pass
class ${TM_NEW_FILE_BASENAME}Tests(unittest.TestCase):
def setUp(self):
pass
if __name__ == '__main__':
unittest.main()
|
uclouvain/OSIS-Louvain | assessments/tests/business/test_score_encoding_progress.py | Python | agpl-3.0 | 14,789 | 0.004328 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this licens... | g/licenses/.
#
##############################################################################
from random import randint
from django.test import TestCase
from assessments.business import score_encoding_progress
from attribution.tests.factories.attribution import AttributionFactory
from attribution.tests.models import... |
ibbad/dna-lceb-web | app/api_v1_0/__init__.py | Python | apache-2.0 | 331 | 0.003021 | """
Initialization | script for restapi for the application.
"""
from flask import Blueprint
from app.common.logging import setup_logging
api = Blueprint('api', __name__)
# Setup logger
# api_log = setup_logging(__name__, 'logs/api.log', maxFilesize=1000000,
# backup_count=5)
from . import views, e | rrors
|
YeoLab/gscripts | gscripts/general/submit_fastqc.py | Python | mit | 403 | 0.009926 | from gscripts import qtools
import sys, os
if not os.path.exists("fastqc/"):
os.mkdir("fastqc")
cmds = []
Sub = qtools.Submitter()
for fileName in sys.argv[1:]:
fastqc_command = "fastqc -o fastqc %s" | %fileName
cmds.append(fastqc_command)
Sub.job(command_list=cmds, sh_file="runFastqc.sh", job_name="Fastqc", array=True, queue="h | ome", nodes=1, ppn=1, submit=True, max_running=1000)
|
devdelay/home-assistant | tests/helpers/test_entity_component.py | Python | mit | 10,909 | 0 | """The tests for the Entity component helper."""
# pylint: disable=protected-access,too-many-public-methods
from collections import OrderedDict
import logging
import unittest
from unittest.mock import patch, Mock
import homeassistant.core as ha
import homeassistant.loader as loader
from homeassistant.helpers.entity im... | platform_setup = Mock(return_value=None)
loader.set_component(
'test_component',
MockModule('test_component', setup=component_setup))
loader.set_component('test_domain.mod2',
MockPlatform(platform_setup, ['test_component']))
component = ... | MAIN, self.hass)
assert not component_setup.called
assert not platform_setup.called
component.setup({
DOMAIN: {
'platform': 'mod2',
}
})
assert component_setup.called
assert platform_setup.called
def test_setup_recovers_when... |
bronikkk/tirpan | tests/accept_mir09.py | Python | gpl-3.0 | 1,313 | 0.007616 | #!/usr/bin/env python
"""
Created on 28.10.2014
@author: evg-zhabotinsky
"""
from test_mir_common import *
mir = tirpan_get_mir('test_mir09.py')
n = find_mir_nodes(mir,
x_call = func_checker('x'),
y_call = func_checker('y'),
z_call = func_checker('z'),
... | hecker(n.x_call.left))
n | .y_if = find_node_down_mir_nojoin(n.y_call, if_cond_checker(n.y_call.left))
n.z_if = find_node_down_mir_nojoin(n.z_call, if_cond_checker(n.z_call.left))
n.join = find_node_down_mir(n.a_call, isinstance_checker(ti.mir.JoinMirNode))
find_node_down_mir_nojoin(mir, same_node_checker(n.x_call))
find_node_down_mir_nojoin(n.... |
skilledindia/pyprimes | src/pyprimes/speed.py | Python | mit | 4,872 | 0.00349 | # -*- coding: utf-8 -*-
## Part of the pyprimes.py package.
##
## Copyright © 2014 Steven D'Aprano.
## See the file __init__.py for the licence terms for this software.
"""\
=====================================
Timing the speed of primes algorithms
=====================================
"""
from __future__ imp... | records.append((number/t, t, name))
timer.stop()
sys.stdout.write("\r%-69s\n" % "Done!")
print ('Total elapsed time: %.1f seconds' % timer.elapsed)
print ('')
records.sort()
print (heading)
for speed, elapsed, name in records:
print ("%-36s %4.2f %8.1f" % (name, elapsed, spee... | ==========================\n')
VERY_SLOW = [awful.primes0, awful.primes1, awful.primes2, awful.turner]
SLOW = [awful.primes3, awful.primes4, probabilistic.primes]
FAST = [sieves.cookbook, sieves.croft, sieves.sieve, sieves.wheel]
MOST = SLOW + FAST
ALL = VERY_SLOW + MOST
run(VERY_SLOW + SLOW, 1000)
run([awful.primes... |
itskewpie/tempest | tempest/api/compute/volumes/test_volumes_negative.py | Python | apache-2.0 | 4,352 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 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.apach... | st import exceptions
from tempest.test import attr
class VolumesNegativeTest(base.BaseComputeTest):
_interface = 'json'
@cl | assmethod
def setUpClass(cls):
super(VolumesNegativeTest, cls).setUpClass()
cls.client = cls.volumes_extensions_client
if not cls.config.service_available.cinder:
skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
raise cls.skipException(skip_msg)
... |
shenson/cobbler | cobbler/modules/authz_ownership.py | Python | gpl-2.0 | 7,391 | 0.000541 | """
Authorization module that allow users listed in
/etc/cobbler/users.conf to be permitted to access resources, with
the further restriction that cobbler objects can be edited to only
allow certain users/groups to access those specific objects.
Copyright 2008-2009, Red Hat, Inc and Others
Michael DeHaan <michael.deha... | source.find("read_autoinstall_snipppet") != -1:
return True
obj = None
if resource.find("remove") != -1:
if resource == "remove_distro":
obj = api_handle.find_distro(arg1)
elif resource == "remove_p | rofile":
obj = api_handle.find_profile(arg1)
elif resource == "remove_system":
obj = api_handle.find_system(arg1)
elif resource == "remove_repo":
obj = api_handle.find_repo(arg1)
elif resource == "remove_image":
obj = api_handle.find_image(arg1)
... |
RafaelPalomar/girder | girder/api/v1/file.py | Python | apache-2.0 | 18,950 | 0.002058 | # -*- coding: utf-8 -*-
import cherrypy
import errno
from ..describe import Description, autoDescribeRoute, describeRoute
from ..rest import Resource, filtermodel
from ...constants import AccessType, TokenScope
from girder.exceptions import AccessException, GirderException, RestException
from girder.models.assetstore ... | lf.route('DELETE', ('upload', ':id'), self.cancelUpload)
self.route('GET', ('offset',), self.requestOffset)
self.route('GET', (':id',), self.getFile)
self.route('GET', (':id', 'downlo | ad'), self.download)
self.route('GET', (':id', 'download', ':name'), self.downloadWithName)
self.route('POST', (), self.initUpload)
self.route('POST', ('chunk',), self.readChunk)
self.route('POST', ('completion',), self.finalizeUpload)
self.route('POST', (':id', 'copy'), self.cop... |
BeenzSyed/tempest | tempest/services/database/json/database_client.py | Python | apache-2.0 | 1,757 | 0.007399 | # Copyright 2012 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from tempest.common.rest_client import RestClient
class DatabaseClient(RestClient):
def __init__(self,
config,
... | username,
password,
auth_url,token_url,
tenant_name)
self.service = self.config.database.catalog_type
def list_flavors(self):
resp, b... |
ueg1990/flask-restful | tests/test_reqparse.py | Python | bsd-3-clause | 29,848 | 0.000905 | # -*- coding: utf-8 -*-
import unittest
from mock import Mock, patch
from flask import Flask
from werkzeug import exceptions, MultiDict
from werkzeug.wrappers import Request
from werkzeug.datastructures import FileStorage
from flask_restful.reqparse import Argument, RequestParser, Namespace
import six
import decimal
i... | ertEqu | als(arg.action, u"append")
def test_choices(self):
arg = Argument("foo", choices=[1, 2])
self.assertEquals(arg.choices, [1, 2])
def test_default_dest(self):
arg = Argument("foo")
self.assertEquals(arg.dest, None)
def test_default_operators(self):
arg = Argument("fo... |
quantmind/lux | lux/ext/odm/fields.py | Python | bsd-3-clause | 3,012 | 0 | from pulsar.utils.log import lazyproperty
from lux.models import fields
from lux.utils.data import as_tuple
from sqlalchemy.orm.exc import NoResultFound
def get_primary_keys(model):
"""Get primary key properties for a SQLAlchemy model.
:param model: SQLAlchemy model class
"""
mapper = model.__mappe... | or prop in self.related_keys]
)
value = {self.related_keys[0].key: value}
query = self.session.query(self.related_model)
try:
if self.columns:
result = query.filter_by(**{
prop.key: value.get(prop.key)
for pr... | # Use a faster path if the related key is the primary key.
result = query.get([
value.get(prop.key) for prop in self.related_keys
])
if result is None:
raise NoResultFound
except NoResultFound:
# The related-obj... |
USGSDenverPychron/pychron | pychron/processing/unmix.py | Python | apache-2.0 | 4,643 | 0.001077 | # ===============================================================================
# Copyright 2012 Jake Ross
#
# 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 AN... |
kevinwuhoo/randomcolor-py | tests/test_randomcolor_visual.py | Python | mit | 2,617 | 0.001911 | import randomcolor
import random
def main():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = ra... | "%d random colors with %s hue" % (i, hue),
rand_color.generate(hue=hue, count=i)
))
# test all luminosities
for luminosity in luminosities:
i = rand_int()
colors.append((
"%d random colors with %s luminosity" % (i, luminosity),
rand_color.gen... | luminosity = random.choice(luminosities)
format_ = random.choice(formats)
colors.append((
"%d random colors with %s hue, %s luminosity, and %s format"
% (i, hue, luminosity, format_),
rand_color.generate(hue=hue, luminosity=luminosity,
... |
TeamEOS/external_chromium_org | tools/perf/metrics/system_memory.py | Python | bsd-3-clause | 4,647 | 0.006025 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from metrics import memory
from metrics import Metric
class SystemMemoryMetric(Metric):
"""SystemMemoryMetric gathers system memory statistic.
This met... | tats_start = self._browser.memory_stats
def Stop(self, page, tab):
"""Prepare the re | sults for this page.
The results are the differences between the current system memory stats
and the values when Start() was called.
"""
assert self._memory_stats_start, 'Must call Start() first'
self._memory_stats_end = self._browser.memory_stats
# |trace_name| and |exclude_metrics| args are no... |
supermeng/lain-sdk | tests/test_lain_conf.py | Python | mit | 81,042 | 0.000913 | # -*- coding: utf-8 -*-
import json
import yaml
import pytest
from unittest import TestCase
from lain_sdk.yaml.parser import (
LainConf, ProcType, Proc,
just_simple_scale,
render_resource_instance_meta, DEFAULT_SYSTEM_VOLUMES,
DOMAIN,
MIN_SETUP_TIME, MAX_SETUP_TIME, MIN_KILL_TIMEOUT, MAX_KILL_TIMEO... | nf()
hello_conf | .load(meta_yaml, meta_version, None)
assert hello_conf.appname == 'hello'
assert hello_conf.procs['web'].port[80].port == 80
assert hello_conf.procs['web'].cmd == []
def test_lain_conf_port_with_type(self):
meta_yaml = '' |
google/mirandum | alerts/ytsubs/migrations/0004_migrate_updater.py | Python | apache-2.0 | 1,359 | 0.004415 | # -*- coding: utf-8 -*-
# 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
#
# Un... | 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.
from __future__ import unicode_literals
from d... | in", "UpdaterEvent")
for event in SubEvent.objects.all():
try:
ue = UpdaterEvent.objects.get(pk=event.updaterevent_ptr_id)
ue.base_updater = event.updater.updater_ptr
ue.save()
except Exception:
pass
class Migration(migrations.Migration):
depende... |
thundernet8/WRGameVideos-Server | app/auth/views.py | Python | gpl-2.0 | 2,080 | 0.002404 | # coding=utf-8
import os
import time
import urllib
import urllib2
import random
import string
import json
from flask import url_for
from flask import redirect
from flask import request
from flask import session
from flask import flash
from flask import current_app
from flask.ext.login import login_user
from . import ... | ndom.choice(string.digits) for _ in range(10))
session['state'] = state
query = dict(response_type='code', client_id=app_key, tstamp=timestamp, sign=sign, state=state, redirect_url=redirect_url)
url = (current_app.c | onfig['API_SERVER_OPEN_URL'] or 'http://api.parser.cc/open/v1.0/')+'authorize?'+urllib.urlencode(query)
return redirect(url)
|
diogo149/Lasagne | lasagne/theano_extensions/conv.py | Python | mit | 8,695 | 0.006325 | """
Alternative convolution implementations for Theano
"""
import numpy as np
import theano
import theano.tensor as T
## 1D convolutions
def conv1d_sc(input, filters, image_shape=None, filter_shape=None, border_mode='valid', subsample=(1,)):
"""
using conv2d with a single input channel
"""
if borde... | ilter_length, stride))
num_steps = filter_length // stride
output_length = (input_length - filter_length + stride) // stride
# pad the input so all the shifted dot products fi | t inside. shape is (b, c, l)
padded_length = (input_length // filter_length) * filter_length + (num_steps - 1) * stride
# at this point, it is possible that the padded_length is SMALLER than the input size.
# so then we have to truncate first.
truncated_length = min(input_length, padded_length)
inp... |
eljefe6a/kafka | tests/kafkatest/tests/upgrade_test.py | Python | apache-2.0 | 3,776 | 0.002913 | # 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 use ... | "partitions": 3,
"replication-factor": 3,
"min.insync.replicas": 2}})
self.zk.start()
self.kafka.start()
# Producer and con... | r
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.producer = VerifiableProducer(
self.test_context, self.num_producers, self.kafka, self.topic,
throughput=self.producer_throughput, version=LATEST_0_8_2)
# TODO - reduce ... |
kamiben/starred | item.py | Python | mit | 1,978 | 0.039939 | import datetime
class Item(object):
def __init__(self, item):
self.title = item['title'].encode("utf-8")
self.url = self.get_starred_url(item)
self.content = self.get_content(item)
self.datestamp = item['published']
self.date = datetime.datetime.fromtimestamp(self.datestamp).strftime('%m-%Y')
def gens... | t):
def __init__(self):
self.list = []
def add(self, item):
self.list.append(item)
def date_equal(self, item, date):
# check if date is equal to item.date, returns true or false. For usage in grab_date
return item.date == date
def grab_date(self, date):
# Filter the Item list with the provided date... | = true)
# Returns an array of items
return [ x for x in self.list if self.date_equal(x, date) ] |
leaot/Huffpost-Articles-in-Twitter-Trends | Python/article_engin.py | Python | mit | 314 | 0.003185 | # collect all the artic | les' title in a list from different sections
from search_articles import get_articles_name
def get_articles(sections):
i = 1
title_list = []
for section in sections:
for title in get_articles_name(str(section)):
title_list += [title]
return | title_list |
cricketclubucd/davisdragons | platform-tools/systrace/catapult/common/py_trace_event/py_trace_event/trace_time.py | Python | mit | 7,242 | 0.009804 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ctypes
import ctypes.util
import logging
import os
import platform
import sys
import time
import threading
GET_TICK_COUNT_LAST_NOW = 0
# If GET_TICK... | le < GET_TICK_COUNT_LAST_NOW:
GE | T_TICK_COUNT_WRAPAROUNDS += 1
GET_TICK_COUNT_LAST_NOW = current_sample
final_ms = GET_TICK_COUNT_WRAPAROUNDS << 32
final_ms += GET_TICK_COUNT_LAST_NOW
return final_ms / 1000.0
_NOW_FUNCTION = WinNowFunctionImpl
def InitializeNowFunction(plat):
"""Sets a monotonic clock for... |
andreasBihlmaier/arni | arni_countermeasure/src/arni_countermeasure/countermeasure_node.py | Python | bsd-2-clause | 3,842 | 0.00026 | from constraint_handler import *
from rated_statistic_storage import *
import rospy
from arni_msgs.msg import RatedStatistics
from arni_core.host_lookup import *
from std_srvs.srv import Empty
import helper
import time
class CountermeasureNode(object):
"""A ROS node.
Evaluates incoming rated statistics with ... | ster_subscriber()
self.__register_services()
def __register_subscriber(self):
"""Register to the rated statistics."""
rospy.Subscriber(
"/statistics_rated", RatedStatistics,
self.__rated_statistic_storage.callback_rated_statistic)
rospy.Subscriber(
... | , RatedStatistics,
HostLookup().callback_rated)
def __register_services(self):
"""Register all services"""
rospy.Service(
"~reload_constraints", Empty, self.__handle_reload_constraints)
def __handle_reload_constraints(self, req):
"""Reload all constraints from p... |
TAlonglong/trollduction-test | aapp_runner/aapp_dr_runner.py | Python | gpl-3.0 | 72,713 | 0.003782 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014, 2015, 2016 Adam.Dybbroe
# Author(s):
# Adam.Dybbroe <adam.dybbroe@smhi.se>
# Janne Kotro fmi.fi
# Trygve Aspenes
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as ... | objdict:
if objdict[key] and len(objdict[key]) > 0:
objdict[key].remove(start_end_times)
LOG.debug("Release/reset job-key " + str(key) + " " +
str(starttime) + " " + str(endtime) +
" from job registry")
LOG.debug("Register: " + str(... | LOG.warning("Nothing to reset/release - " +
"Register didn't contain any entry matching: " +
str(key))
return
class AappLvl1Processor(object):
"""
Container for the Metop/NOAA level-1 processing based on AAPP
"""
def __init__(self, runner_config):
"""
... |
OpenImageIO/oiio | testsuite/oiiotool-pattern/run.py | Python | bsd-3-clause | 3,464 | 0.01097 | #!/usr/bin/env python
# test --create
command += oiiotool ("--create 320x240 3 -d uint8 -o black.tif")
command += oiiotool ("--stats black.tif")
# test --pattern constant
command += oiiotool ("--pattern constant:color=.1,.2,.3,1 320x240 4 -o constant.tif")
command += oiiotool ("--stats constant.tif")
# test --patte... | 10,64,250,400 " +
"-line:color=0,1,0,1 250,100,10,184 " +
"-line:color=0,0.5,0,0.5 250,200,10,182 " +
"-line:color=0,0.25,0,0.25 100,400,10,180 " +
"-line:color=.5,.5,0,0.5 100,100,120,100,120,100,120,120,120,120,10 | 0,120,100,120,100,100 " +
"-box:color=0,0.5,0.5,0.5 150,100,240,180 " +
"-d uint8 -o lines.tif")
# test --box
command += oiiotool ("--pattern checker:color1=.1,.1,.1:color2=0,0,0 256x256 3 " +
"--box:color=0,1,1,1 150,100,240,180 " +
... |
Lrcezimbra/ganso-music | gansomusic/core/models.py | Python | gpl-3.0 | 355 | 0 | from django.db import m | odels
class Music(models.Model):
url = models.CharField('URL', max_length=255)
title = models.CharField('título', max_length=200, blank=True)
artist = models.CharField('artista', max_length=200, blank=True)
genre = models.CharField('gênero', max_length=100, blank=True | )
file = models.FileField(upload_to='')
|
sadanandb/pmt | src/pyasm/web/__init__.py | Python | epl-1.0 | 931 | 0.003222 | ###########################################################
#
# Copyri | ght (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed i | n any way without written permission.
#
#
#
# web framework interface and implementations
from web_environment import *
from palette import *
from callback import *
# security for redirects
from url_security import *
# global web container
from web_container import *
from web_state import *
# basic widget classes
... |
dalou/django-extended | setup.py | Python | bsd-3-clause | 2,148 | 0.00419 | #from __future__ import print_function
import ast
import os
import sys
import codecs
import subprocess
from fnmatch import fnmatchcase
from distutils.util import convert_path
from setuptools import setup, find_packages
def find_version(*parts):
try:
version_py = os.path.join(os.path.dirname(__file__), 'dj... | find_packages(exclude=('tests*',)),
zip_safe=False,
license='MIT',
classifiers=[
'Development Status :: | 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
# test_suite='runtests.runtests... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationpolicylabel.py | Python | apache-2.0 | 9,779 | 0.038757 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | nderscore characters.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my authentication policy label" or 'authentication policy label').
"""
try :
self._labelname = labelname
except Exc... | :
ur"""The new name of the auth policy label.<br/>Minimum length = 1.
"""
try :
return self._newname
except Exception as e:
raise e
@newname.setter
def newname(self, newname) :
ur"""The new name of the auth policy label.<br/>Minimum length = 1
"""
try :
self._newname = newname
except Excep... |
gsnbng/erpnext | erpnext/education/doctype/student_group/student_group.py | Python | agpl-3.0 | 5,632 | 0.022905 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
from erpnext.education.utils import validate_duplicate_student
from ... | pe.student_name
from
`tabProgram Enrollment` pe {condition2}
where
pe.academic_year = %(ac | ademic_year)s {condition1}
order by
pe.student_name asc
'''.format(condition1=condition1, condition2=condition2),
({"academic_year": academic_year, "academic_term":academic_term, "program": program, "batch": batch, "student_category": student_category, "course": course}), as_dict=1)
@frappe.wh... |
labepi/destate | gui/AutomataManage.py | Python | gpl-2.0 | 16,796 | 0.002739 | # vim: set fileencoding=utf-8 :
# Copyright (C) 2008 Joao Paulo de Souza Medeiros.
#
# Author(s): João Paulo de Souza Medeiros <ignotus21@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... | 888888',
'fontsize': '10',
'fontname': 'Monospaced'}
TRANSITION_TEXT = "(%s . %s) -> %s"
LAMBDA_TRANSITION_TEXT = "(%s . &) -> %s"
class AutomataManage(bw.BWVBox):
"""
"""
def __init__(self):
"""
"""
bw.BWVBox.__init__(self, spacing=2)
self.set_s... | r()
self.__create_widgets()
def __create_widgets(self):
"""
"""
self.__automaton_list = AutomatonList(self)
self.__automaton_view = AutomatonView()
self.__command = Command(self.execute_command,
self.parse_command)
self.bw_... |
sassoftware/rbuild | plugins/createprojectbranch.py | Python | apache-2.0 | 8,529 | 0.00129 | #
# Copyright (c) SAS Institute 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 w... | else:
if argSet['auth-type'] not in AUTH_TYPES:
raise errors.BadParameterError(
"Unknown authentication type.")
# collect authentication information based on the user's auth type
if argSet['auth-type'] == USERPASS:
... | if 'username' not in argSet:
argSet['username'] = ui.getResponse(
'External username', required=True)
if 'password' not in argSet:
argSet['password'] = ui.getPassword(
'External password', verify=True)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.