prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from django.db import models
class TastingCategory(models.Model):
title = models.CharField(max_length=128)
singularTitle = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
def __unicode__(self):
return self.title
class Tasting(models.Model):
category = models.For... | dels.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date d'ajout")
def __unicode__(self):
return self.category.title + " " + self.name
class WhiskyType(models.Model):
type = models.CharField(max_length=128)
def __un | icode__(self):
return self.type
class CoffeeCountry(models.Model):
country = models.CharField(max_length=128)
def __unicode__(self):
return self.country
class Whisky(Tasting):
old = models.IntegerField()
type = models.ForeignKey('WhiskyType', on_delete=models.CASCADE)
degAlcool ... |
from django.core.exceptio | ns import ImproperlyConfigured
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
import warnings
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUs... | er(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
#assert False, "in user manager"
now = timezone.now()
if not email:
raise ValueError('The given ... |
import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
... | app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
... | ales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
... |
can redistribute it and/or modify
# it under the terms of the GNU Affero 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 ... | else:
c.append({'write_cell_func': report_ | xls.xls_types[c[3]]})
# Set custom cell style
if s_len > 6 and s[6] is not None:
c.append(s[6])
else:
c.append(None)
# Set cell formula
if s_len > 7 and s[7] is not None:
... |
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
"""
l_indices = list(indices)
for i, indx in enumerate(l_indices):
if not isinstance(indx, int):
l_indices[i] = self.index(indx)
e = 1
... | return f.func(*newargs)
if f.has(KroneckerDelta) and _has_simple_delta(f, limits[0]):
return deltasummation(f, limits)
dif = b - a
definite = dif.is_Integer
# Doing it directly may be faster if there are very few terms.
if definite and (dif < 100):
return eval_sum_direct(f, (i, a, ... | # this can save time when b-a is big.
# We should try to transform to partial fractions
value = eval_sum_symbolic(f.expand(), (i, a, b))
if value is not None:
return value
# Do it directly
if definite:
return eval_sum_direct(f, (i, a, b))
def eval_sum_direct(expr, limits):
f... |
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloo | p()
| |
#! /usr/bin/env python
# coding=utf8
#
# Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#... | print "Building libc..."
tmpdir = tempfile.mkdtemp()
buildOut = builddir + "/libc"
olddir = os.getcwd()
os.chdir(tmpdir)
shutil.copy(inputLibcA, tmpdir + "/libc.a")
os.system(ar + " x libc.a")
glue = glue_name
shutil.copy(glue, tmpdir + "/" + os.path.ba | sename(glue_name))
shutil.copy(pedigree_c_name, tmpdir + "/" + os.path.basename(pedigree_c_name))
objs_to_remove = ["init", "getpwent", "signal", "fseek", "getcwd", "rename", "rewinddir", "opendir", "readdir", "closedir", "_isatty", "basename", "setjmp"]
for i in objs_to_remove:
try:
o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA
#
# 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/l... |
# WITHOUT WARRANTIES O | R CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This module is still in proof of concept, and subject to change.
#
from datetime import datetime
# IkaLog Output Plugin: Write 'Alive Squids' CSV data
... |
import pytest
from thefuck.types import Command
from thefuck.rules.git_push_without_commits import (
fix,
get_new_command,
match,
)
command = 'git push -u origin master'
expected_error = '''
error: src refspec master does not match any.
error: failed to push some refs to 'git@github.com:User/repo.git'
'''... | mmand', [Command(command, expected_error)])
def test_match(command):
assert match(command)
@pytest.mark.parametrize('command, result', [(
Command(command, expected_error),
fix.form | at(command=command),
)])
def test_get_new_command(command, result):
assert get_new_command(command) == result
|
# -*- coding: utf-8 -*-
from bpy.types import PropertyGroup
from bpy.props import StringProperty, IntProperty, BoolProperty, FloatProperty, FloatVectorProperty
from mmd_tools.core.bone import FnBone
def _updateMMDBoneAdditionalTransform(prop, context):
prop['is_additional_transform_dirty'] = True
p_bone = co... | pointer():
FnBone.apply_additional_transformation(prop.id_data)
def _getAdditionalTransformBone(prop):
arm = prop.id_data
bone_id = prop.get('additional_transform_bone_id', - | 1)
if bone_id < 0:
return ''
fnBone = FnBone.from_bone_id(arm, bone_id)
if not fnBone:
return ''
return fnBone.pose_bone.name
def _setAdditionalTransformBone(prop, value):
arm = prop.id_data
prop['is_additional_transform_dirty'] = True
if value not in arm.pose.bones.keys():
... |
# Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# | a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distribu | ted 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 neutron.common import constants
from neutron.extensions import portbindings
from neutron.openstack.com... |
# -*- | coding: utf-8 -*-
'''
Created on 2014-04-09
@author: Krzysztof Langner
'''
# import iclogger.file_logger as Logger
import iclogger.dynamodb_logger as Logger
if __name__ == "__main__":
Log | ger.app.run(debug=True) |
import unittest
class TestGenearate(unittest.TestCase):
def setUp(self):
self.seq = ra | nge(10)
def test_smoke(self):
"Basic smoke test that should pickup any silly errors"
import external_naginator
external_naginator.__name__ == "external_naginator"
if __name__ == '__main__':
unittest.ma | in()
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Description:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
More practic | e:
If you have figured out the O(n) solution,
try coding another solution using the divide and conquer approach, which is more subtle.
Tags: Array, Dynamic Programming, Divide and Conquer
'''
class Solution(object):
# O(n) runtime; O(1) space - 局部最优和全局最优解法
def maxSubArray(self, nums):
""" |
:type nums: List[int]
:rtype: int
"""
global_max, local_max = float("-inf"), 0
for i in nums:
local_max = max(i, i+local_max)
global_max = max(local_max, global_max)
return global_max
# Divide and Conquer
|
d limitations
# under the License.
import tempfile
from cloudfiles.errors import ContainerNotEmpty
from django import http
from django import template
from django.contrib import messages
from django.core.urlresolvers import reverse
from mox import IgnoreArg, IsA
from horizon import api
from horizon import test
fr... | ntainers)
handled = table.maybe_handle()
|
self.assertEqual(handled['location'], CONTAINER_INDEX_URL)
def test_delete_container_nonempty(self):
self.mox.StubOutWithMock(api, 'swift_delete_container')
exception = ContainerNotEmpty('containerNotEmpty')
api.swift_delete_container(
IsA(http.HttpRequest),
... |
ng it."),
'categ_ids': fields.many2many('calendar.event.type', 'meeting_category_rel', 'event_id', 'type_id', 'Tags'),
'attendee_ids': fields.one2many('calendar.attendee', 'event_id', 'Attendees', ondelete='cascade'),
'partner_ids': fields.many2many('res.partner', 'calendar_event_res_partner_rel... | starttime:
start = openerp.fields.Datetime.from_string(starttime)
startdate = tz.localize(start) # Add "+hh:mm" timezone
startdate = startdate.replace(hour=8) # Set 8 AM in localtime
| startdate = startdate.astimezone(pytz.utc) # Convert to UTC
value['start_datetime'] = datetime.strftime(startdate, DEFAULT_SERVER_DATETIME_FORMAT)
elif start:
value['start_datetime'] = start
if endtime:
end = datetime.strptime(endtime.split(... |
import sys, time
from django.conf import settings
from django.db import connection, transaction, backend
from django.core import management, mail
from django.dispatch import dispatcher
from django.test import signals
from django.template import Template
# The prefix to put on the default database name when creating
# ... | inal test renderer
- Restoring the email sending functions
"""
Template.render = Template.original_render
del Template.original_render
mail.SMTPConnection = mail.original_SMTPConnection
del mail.original_SMTPConnection
del mail.outbox
def _set_autocommit(connectio... | ommit mode."
if hasattr(connection.connection, "autocommit"):
connection.connection.autocommit(True)
elif hasattr(connection.connection, "set_isolation_level"):
connection.connection.set_isolation_level(0)
def get_mysql_create_suffix():
suffix = []
if settings.TEST_DATABASE_CHARSET:
... |
# ============================================================================
# FILE: size.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license
# ============================================================================
from defx.base.column import Base, Highlights
from defx.context im... | 9
def get_with_highlights(
self, context: Context, candidate: Candidate
) -> typing.Tuple[str, Highlights]:
path = candidate['act | ion__path']
if not readable(path) or path.is_dir():
return (' ' * self._length, [])
size = self._get_size(path.stat().st_size)
text = '{:>6s}{:>3s}'.format(size[0], size[1])
return (text, [(self.highlight_name, self.start, self._length)])
def _get_size(self, size: float)... |
import random
from Person import Person
class House(object):
def __init__(self):
self.rooms = []
self.actors = []
def __str__(self):
house_string = ""
for room in self.rooms:
house_string = house_string + str(room) + "\n\n"
return house_string[:-2]
def... | d = False
while not placed:
i = random.randint(0, len(self.rooms) | - 1)
if self.rooms[i].can_enter:
self.rooms[i].addActor(person)
placed = True
def addRooms(self, rooms):
for room in rooms:
if room not in self.rooms:
self.rooms.append(room)
def hasRoomType(self, roomType):
for room in s... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | proto.v0 import schema_pb2
from tensorflow_metadata.proto.v0 import statistics_pb2
# TODO(https://issues.apache.org/jira/ | browse/SPARK-22674): Switch to
# `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is
# resolved.
from tfx_bsl.types import tfx_namedtuple # pylint: disable=g-bad-import-order
# LINT.IfChange(custom_stat_names)
_MAX_LENGTH_DIFF_NAME = 'max_length_diff'
_MIN_LENGTH_DIFF_NAME = 'min_length_diff'
_MIS... |
# -*- coding: utf-8 -*-
from openerp import models, fields, api
class School(models.Model):
_name = 'royalty.school'
name = fields.Char('Name', size=255, required=True)
address_line1 = fields.Char( 'Address 1', size=255 )
address_line2 = fields.Char( 'Address 2', size=255 )
city... | rganization Abbreviation', size=75 )
active = fields.Boolean( 'Organization Active', default=True )
old_id = fields.Integer( 'Legacy ID' | )
products = fields.One2many( 'product.product', 'school_id', 'Products' )
contacts = fields.One2many( 'royalty.contact', 'school_id', 'Contacts' )
|
from unittest import mock
import pytest
from mitmproxy.test import tflow
from mitmproxy.net.http import http1
from mitmproxy.net.tcp import TCPClient
from mitmproxy.test.tutils import treq
from ... import tservers
class TestHTTPFlow:
def test_repr(self): |
f = tflow.tflow(resp=True, err=True)
assert repr(f)
class TestInvalidRequests(tservers.HTTPProxyT | est):
ssl = True
def test_double_connect(self):
p = self.pathoc()
with p.connect():
r = p.request("connect:'%s:%s'" % ("127.0.0.1", self.server2.port))
assert r.status_code == 400
assert b"Unexpected CONNECT" in r.content
def test_relative_request(self):
... |
#encoding=utf-8
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = "liyi"
__date__ = "2017-07-06"
import os
import sys
import argparse
import collections
import logging
import codecs
import charset
def generate_vocab(source_paths, save_path, d... | ounter()
for i, path in enumerate(source_paths):
f = codecs.open(path, "r", "utf-8")
while True:
line = f.readline()
if not line:
break
if delimiter == "":
tokens = list(line.strip())
else:
tokens = line.strip().split(delimiter)
tokens = [_ for _ in token... | okens)
##filter vocab
if filter_en is True or filter_num is True:
new_vocab_cnt = collections.Counter()
for word in vocab_cnt:
skip = False
for index, char in enumerate(word):
if filter_en and charset.is_alphabet(char):
skip = True
elif filter_num and charset.is_number... |
name = raw_inp | ut("Enter your name:")
print "Hello" , na | me
|
rd_set,
implicit_first_group_key=None,
keyword_repeat_allowed=True,
group_repeated_keywords=None,
only_found_keywords=False,
):
"""
Return dictionary with keywords as keys and following arguments as value.
For example when keywords are "first" and "seconds" then for arg_list
["first", 1,... | ouping():
if not group_repeated_keywords:
return []
# implicit_first_group_key is not keyword: when it is in
# group_repeated_keywords but not in keyword_set is considered as
# unknown.
unknown_keywords = set(group_repeated_keywords) - set(keyword_set)
if unkn... | set: {0}".format(
", ".join(unknown_keywords)
)
)
return group_repeated_keywords
def get_completed_groups():
completed_groups = groups.copy()
if not only_found_keywords:
for keyword in keyword_set:
if keyword not in... |
from djan | go.apps import AppConfig
class MoocConfig(AppConfig):
| name = 'mooc'
|
import sympy
x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2
df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))
xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[0 | ][0]), (x2,xs[0][1])])
lambda_xs = H_xs.eigenvals()
count = 0
for i in lambda_xs.keys():
| if i.evalf() <= 0:
count += 1
if count == 0:
print 'Local minima'
elif count == len(lambda_xs.keys()):
print 'Lacal maxima'
else:
print 'Saddle point'
|
f cluster is passed,
restrict addresses to public and cluster networks.
Note: Some optimizations could be done here in the multi module (such as
skipping the source and destination when they are the same). However, the
unoptimized version is taking ~2.5 seconds on 18 minions with 72 addresses
for ... | ddresses from all addresses on all minions.
| If cluster is specified, restrict addresses to cluster and public networks.
If exclude is specified, remove matching addresses. See Salt compound matchers.
within exclude individual ip address will be remove a specific target interface
instead of ping from, the ping to int... |
#!/usr/local/bin/python3.5
import itertools
import sys
from .stuff import word_set
__version__ = "1.1.0"
def find_possible(lst):
"""
Return all possible combinations of letters in lst
@type lst: [str]
@rtype: [str]
"""
returned_list = []
for i in range(0, len(lst) + 1):
for subs... | e word_set
returned_list.append(word)
return returned_list
def main():
"""
Main function to run the program
"""
anagram_lst = []
anagram = sys.argv[1]
for char in anagram:
anagram_lst.append(char)
possible_words = find_possible(anagram_lst)
actual_words = retu... | for item in set(actual_words):
# Running through in set form prevents duplicates
print(item)
|
# %% [markdown]
# # sklearn-porter
#
# Repository: [https://github.com/nok/sklearn-porter](https://github.com/nok/sklearn-porter)
#
# ## RandomForestClassifier
#
# Documentation: [sklearn.ensemble.RandomForestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html)
# %... | X, y)
# %% [markdown]
# ### Transpile classifier
# %%
from sklearn_porter import Porter
porter = Porter(clf, language='js')
output = porter.export(embed_data=True)
print(output)
# %% [markdown]
# ### Run classification in JavaScript
# %%
# Save classifier:
| # with open('RandomForestClassifier.js', 'w') as f:
# f.write(output)
# Run classification:
# if hash node 2/dev/null; then
# node RandomForestClassifier.js 1 2 3 4
# fi
|
ast_audit_txn:
res = {}
payload_data = last_audit_txn[TXN_PAYLOAD][TXN_PAYLOAD_DATA]
for ledger_id in payload_data[AUDIT_TXN_STATE_ROOT].keys():
fake_pp = BlsBftReplicaPlenum._create_fake_pre_prepare_for_multi_sig(
ledger_id,
pa... | er(
lambda item: not quorums.bls_signatures.is_reached(len(list(item[1].values()))),
sigs_for_request.items()
)
)
if sigs_invalid:
for lid, sigs in sigs_invalid:
logger.debug(
'{}Can not create bls signatures for... | 'There are only {} signatures for ledger {}, '
'while {} required for multi_signature'.format(BLS_PREFIX,
key_3PC,
len(list(sigs.values())),
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-28 14:28
from __future__ import unicode | _literals
from django.db import migrations, models
cl | ass Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Molecule design set library table.
"""
from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy import Float
from sqlalchemy impo... | Column('final_volume', Float,
CheckConstraint('final_volume > 0'),
| nullable=False),
Column('final_concentration', Float,
CheckConstraint('final_concentration > 0'),
nullable=False),
Column('number_layouts', Integer,
CheckConstraint('number_layouts > 0'),
nulla... |
from .careful impo | rt *
from .noisy import *
from . import streams
from . import resetable
from lasagne.updat | es import * |
'''Publish sensor events to MQTT broker.'''
import logging
import paho.mqtt.publish as mqtt_pub
import paho.mqtt.client as mqtt
import socket
class MqttPublisher():
'''Publish sensor events to an MQTT broker.'''
def __init__(self, broker, topic_prefix='/sensors'):
'''Initialize a MqttPublisher inst... | ems. Just log
# the exception and try again next time.
try:
topic = self.get_topic(evt)
msg = "Publishing to topic '{0}'."
logging.debug(msg.format(topic))
# This fixes the protocol version to MQTT v3.1, because
# the current version of the ... | mqtt_pub.single(
topic=topic,
payload=evt.toJSON(),
hostname=self.broker,
protocol=mqtt.MQTTv31)
except:
logging.exception('Publish of MQTT value failed.')
def publish_events(self, evts):
'''Publish a list of sen... |
from ft.db.dbtestcase import DbTestCase
from passerine.db.session import Session
from passerine.db.common import ProxyObject
from passerine.db.uow import Record
from passerine.db.entity import entity
from passerine.db.mapper import link, CascadingType, AssociationType
@entity('test_db_uow_ass_one_to_many_computer')
cl... | data = c.driver.find_one(c.name, {'name': 'c'})
self.assertIsNotNone(data)
self.assertEqual(boss.delegates[2].id, data['_id'])
data = c.driver.find_one(c.name, {'name': 'boss'})
| self.assertEqual(3, len(data['delegates']))
for delegate in boss.delegates:
self.assertIn(delegate.id, data['delegates'])
def test_cascading_on_delete_with_some_deps(self):
c = self.session.collection(Developer)
boss = c.filter_one({'name': 'boss'})
boss.delegates[0].... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | t tensorflow as tf
# pylint: disable=g-import-not-at-top
# pylint: disabl | e=g-bad-import-order
# pylint: disable=unused-import
# Note: cpuinfo and psutil are not installed for you in the TensorFlow
# OSS tree. They are installable via pip.
try:
import cpuinfo
import psutil
except ImportError as e:
tf.logging.error("\n\n\nERROR: Unable to import necessary library: {}. "
... |
else:
ftmp = lib.H5TmpFile()
eris_vvop = ftmp.create_dataset('vvop', (nvir,nvir,nocc,nmo), dtype)
orbsym = _sort_eri(mycc, eris, nocc, nvir, eris_vvop, log)
mo_energy, t1T, t2T, vooo, fvo, restore_t2_inplace = \
_sort_t2_vooo_(mycc, orbsym, t1, t2, eris)
cpu1 = log.timer_d... | vooo = lib.take_2d(vooo.reshape(nvir,-1), v_sorted, oo_idx)
vooo = vooo.reshape(nvir,nocc,nocc,nocc)
| #:t2T = t2.transpose(2,3,1,0)
#:t2T = ref_t2T[v_sorted][:,v_sorted][:,:,o_sorted][:,:,:,o_sorted]
#:t2T = ref_t2T.reshape(nvir,nvir,-1)[:,:,oo_sorted]
t2T = lib.transpose(t2.reshape(nocc**2,-1))
oo_idx = numpy.arange(nocc**2).reshape(nocc,nocc).T[o_sorted][:,o_sorted]
oo_idx ... |
# ===============================================================================
# Copyright (c) 2014 Geoscience Australia
# 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... | uce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither Geoscience Australia nor the names of its contributors may be
# used to endorse or promote products derived from this sof... | or written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONT... |
is = axis[1:]
self.position_sign[i] = -1.0
if axis not in ('x','y','z'):
rospy.logwarn('Invalid axis %s given in [axes_mapping]' % axis)
self.position_axes[i] = ['x','y','z'].index(axis)
self.workspace = self.change_axes(self.workspace)
# Rate parameters
self.rate_pivot = np.zero... | e the first command sent to the slave is equal to its current position6D
self.command_pos = np.array(self.slave_pos)
self.command_rot = np.array(self.slave_rot)
# Start the timer that will publish the ik commands
self.command_timer = rospy.Timer(rospy.Duration(1.0/self.publish_frequency | ), self.publish_command)
self.draw_timer = rospy.Timer(rospy.Duration(1.0/10.0), self.draw_position_region)
self.loginfo('State machine state: GO_TO_CENTER')
@smach.cb_interface(outcomes=['lock', 'succeeded', 'aborted'])
def go_to_center(user_data, self):
if not np.allclose(np.zeros(3), self.m... |
# coding: utf-8
from rest_framework import viewsets
from kpi.models import UserAssetSubscription
from kpi.serializers.v2.user_asset_subscription import (
UserAssetSubscriptionSerializer,
)
from kpi.utils.object_permission import get_database_user
class UserAssetSubscriptionViewSet(viewsets.ModelViewSet):
que... | criteria['asset__uid'] = self.request.query_params[
| 'asset__uid']
return UserAssetSubscription.objects.filter(**criteria)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
|
#!/usr/bin/env python2
#-*-indent-tabs-mode: nil-*-
import sys
import os.path
import gi
from gi.repository import Gtk, Gio
SCHEMAS = "org.cinnamon.desklets.launcher"
LAUNCHER_KEY = "launcher-list"
HOME_DIR = os.path.expanduser("~")+"/"
CUSTOM_LAUNCHERS_PATH = HOME_DIR + ".cinnamon/panel-launchers/"
EDITOR_DIALOG_UI... | return file_name
class Application:
def __init__(self, file_name):
self.file_name = file_name
self._path = None
self.icon_name = None
self.title = None
self.command = None
if (os.path.exists(CUSTOM_LAUNCHERS_PATH + file_name)):
self._path = CUSTOM_LAU... | self._path:
self._file = open(self._path, "r")
while self._file:
line = self._file.readline()
if len(line)==0:
break
if (line.find("Name") == 0 and (not "[" in line)):
self.title = line.replace("Name","").re... |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you c | an redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in th | e 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.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <ht... |
ec : int, optional
Explicitly specify total number of vectors
(in case word vectors are appended with document vectors afterwards).
"""
_save_word2vec_format(fname, self.vocab, self.syn0, fvocab=fvocab, binary=binary, total_vec=total_vec)
@classmethod
def load_word2vec_... | ""
return _load_word2vec_format(
cls, fname, fvocab=fvocab, binary=binary, encoding=encoding, unicode_errors=unicode_errors,
limit=limit, datatype=datatype)
@staticmethod
def vector_distance(v | ector_1, vector_2):
"""Compute poincare distance between two input vectors. Convenience method over `vector_distance_batch`.
Parameters
----------
vector_1 : numpy.array
Input vector.
vector_2 : numpy.array
Input vector.
Returns
-------
... |
from django.conf import settings
from django.utils import httpwrappers
from django.core.mail import mail_managers
import md5, os
class CommonMiddleware:
"""
"Common" middleware for taking care of some basic operations:
- Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS
- URL r... | ings.DEFAULT_CHARSET)).hexdigest()
if request.META.get('HTTP_IF_NONE_MATCH') == etag:
response = | httpwrappers.HttpResponseNotModified()
else:
response['ETag'] = etag
return response
def _is_ignorable_404(uri):
"Returns True if a 404 at the given URL *shouldn't* notify the site managers"
for start in settings.IGNORABLE_404_STARTS:
if uri.startswith(start):
... |
# -*- coding: utf-8 -*-
import requests
import urlparse
class TV(object):
def __init__(self, url):
self.url = url
self.chan = None
self.stream = None
def _post(self, endpoint, json):
url = urlparse.urljoin(self.url, endpoint)
try:
requests.post(url, json= | json)
except:
pass
def _json(self, action, data='', options='live'):
return {
'action': action,
'data': data,
'options': options
}
def start(self, chan, stream, modus):
self.ch | an = chan
self.stream = stream
json = self._json('start', data=stream, options=modus)
self._post('playback', json)
def stop(self):
self.chan = None
self.stream = None
json = self._json('stop')
self._post('playback', json)
def play(self):
json =... |
import os
import unittest
from robot.utils.asserts import assert_equal, assert_true
from robot.utils.etreewrapper import ETSource, ET
from robot.utils import IRONPYTHON, PY3
PATH = os.path.join(os.path.dirname(__file__), 'test_etreesource.py')
if PY3:
unicode = str
class TestETSource(unittest.TestCase):
d... | tion(source, '<in-memory file>')
assert_true(source._opened.closed)
with ETSource(xml) as src:
assert_equal(ET.parse(src).getroot().tag, 'tag')
def test_non_ascii_string_repr(self):
self._verify_string_representation(ETSource(u'\xe4'), u'\xe4')
def _verify_string_representa... | ittest.main()
|
# Django
from django.conf.urls import patterns, url
# local Django
from organization.views import OrganizationCreateView, OrganizationDeleteView, OrganizationListView, OrganizationUpdateView
urlpatterns = patterns(
'',
url(r'^create/$', OrganizationCreateView.as_view(), name='create'),
url(r'^delete/(?P<o... | dit/(?P<organization_id>\d+)$',
OrganizationUpdateView.as_view(),
name='edit'),
url | (r'^list/$', OrganizationListView.as_view(), name='list'),
)
|
w_authors = True
# ------ Sphinx
# Add any paths that contain templates here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]#templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '... | ch_options = {'type': 'default'}
# The name of a javascrip | t file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'GPydoc'
# -- Options for LaTeX output ---------------------------------------------
lat... |
return d
def get_section_pattern(self, section):
regexp = '(.*):(.*)'
sec = re.match(regexp, section)
if sec:
Global.current_hosts = self.pattern_stripping(sec.group(2))
section = sec.group(1)
section = section.lower().replace('-', '_')
section = [... | perf['stripesize'] = 256
perf['dalign'] = {
'raid6': perf['stripesize'] * perf['diskcount'],
'raid10': perf['stripesize'] * perf['diskcount']
}[perf['di | sktype']]
else:
perf['dalign'] = 256
perf['diskcount'] = perf['stripesize'] = 0
else:
perf = dict(disktype='jbod')
perf['dalign'] = 256
perf['diskcount'] = perf['stripesize'] = 0
self.create_var_files(perf, False, Global.gro... |
import unittest
from gi.repository import GElektra as kdb
TEST_NS = "user/tests/gi_py3"
class Constants(unittest.TestCase):
def setUp(self):
pass
def test_kdbconfig_h(self):
self.assertIsInstance(kdb.DB_SYSTEM, str)
self.assertIsInstance(kdb.DB_USER, str)
self.assertIsInstance(kdb.DB_HOME, str)
self.... | nce(kdb.VERSION_MICRO, int)
self.assertIsNone(kdb.KS_END)
class KDB(unittest.TestCase):
def test_ctor(self):
self.assertIsInstance(kdb.KD | B(), kdb.KDB)
error = kdb.Key()
self.assertIsInstance(kdb.KDB(error), kdb.KDB)
def test_get(self):
with kdb.KDB() as db:
ks = kdb.KeySet()
db.get(ks, "system/elektra")
import os
if os.getenv("CHECK_VERSION") is None:
key = ks["system/elektra/version/constants/KDB_VERSION"]
self.assertEqual(... |
#
# Read KRW-USD rates
#
# We have data from 1994 to 2009
years = range(1994, 2010)
# read one year into list data
def read_year(yr, data):
fname = "data/%d.txt" % yr
f = open(fname, "r")
for l in f:
date1, value1 = l.split()
value = float(value1)
# convert to KRW per USD
value = int(1.0 / value... | or d, v in data:
if v < vm:
vm = v
dm = d
return dm, vm
def find_max(data):
vm = 0
dm = None
for d, v in data:
if v > vm:
vm = v
dm = d
return dm, vm
def main():
data = read_all()
print "Minimum:", find_min(data) |
print "Maximum:", find_max(data)
for yr in years:
avg = average(data, yr)
print yr, avg
main()
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os, sys
from ipdl.ast import Visitor
from ipdl.ast import IN, OUT, INOUT, ASYNC, SYNC, RPC
class CodePrinter:
... | ageDecls: msgDecl.accept(self)
self.println()
for transStmt in p.transitionStmts: transStmt.accept(self)
| self.dedent()
self.println('}')
self.write('}\n'* len(p.namespaces))
def visitManagerStmt(self, mgr):
self.printdentln('manager '+ mgr.name +';')
def visitManagesStmt(self, mgs):
self.printdentln('manages '+ mgs.name +';')
def visitMessageDecl(self, msg):
self.p... |
#!/usr/bin/env python
# Copyright (c) 2013. Mark E. Madsen <mark@madsenlab.org>
#
# This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details.
| """
Description here
"""
import logging as log
def check_liveness(ax, model, args, simco | nfig, timestep):
diff = timestep - model.get_time_last_interaction()
num_links = model.agentgraph.number_of_edges()
if (diff > (5 * num_links)):
#log.debug("No interactions have occurred since %s - for %s ticks, which is 5 * %s network edges", model.get_time_last_interaction(), diff, num_links)
... |
#!/usr/bin/env python3
import sys
import os
import time
import atexit
from signal import SIGTERM
import logging
import logging.handlers
# load the config
from foostat import config
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
filehandler = logging.handlers.TimedRotatingFileHandler(config["files"]["lo... | rr.write(message)
sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.setsid()
os.umask(0)
# Do second fork.
try:
pid = os.fork()
if pid > 0:
# Exit from second parent.
sys.exit(0)
... | d()))
# Redirect standard file descriptors.
sys.stdout.flush()
sys.stderr.flush()
si = open(self.stdin, 'r')
so = open(self.stdout, 'a+')
se = open(self.stderr, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
... |
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from pyvirtualdisplay import Display
__PROCESSOR = 'lxml'
__OFFERS_CLASS = 'offer-listing'
__PRICE_CLASS = 'dollars'
__FLIGHT_DURATION_CLASS = 'duration-emphasis'
__LAYOVR_CLASS = ''
__AIRLINE_CLASS = ''
def get_page_offers(url):
display =... | er_object is not None:
prices_list.append(offer_object)
return prices_list
def __parse_offers_list(html_content):
soup = BeautifulSoup(html_content, __PROCESSOR)
offers = soup.find_all('li', class_=__OFFERS_CLASS)
return offers
def __get_offer_object(offer_html):
offer_price = __get_... | not None and offer_duration is not None and offer_airline is not None:
return {'price': offer_price.strip(), 'duration': offer_duration.strip(), 'airline': offer_airline.strip()}
def __get_offer_price(offer_html):
offer_element = __find_element_using_class(offer_html, 'span', __PRICE_CLASS)
if offer_e... |
"""Procedures to initialize the full text search in PostgresQL"""
from django.db import connection
def setup_full_text_search(script_path):
"""using pos | tgresql database connection,
installs the plsql language, if necessary
and runs the stript, whose path is given as an argument
"""
fts_init_query = open(script_path).read()
cursor = connection.cursor()
try:
#test if language exists
cursor.execute("SELECT * FROM pg_language WHERE... | ql")
#run the main query
cursor.execute(fts_init_query)
finally:
cursor.close()
|
################################################################################
#
# Copyright 2015-2020 Félix Brezo and Yaiza Rubio
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Softwa... | /foro/member.php?u=" + "<HERE_GOES_THE_USER_ID>"
########################
# Defining valid modes #
########################
self.isValidMode = {}
self.isValidMode["phonefy"] = False
self.isValidMode["usufy"] = True
self.isValidMode["searchfy"] = | False
######################################
# Search URL for the different modes #
######################################
# Strings with the URL for each and every mode
self.url = {}
#self.url["phonefy"] = "http://anyurl.com//phone/" + "<phonefy>"
self.url["usu... |
if coords[2 * left + inc] == t:
swap_item(ids, coords, left, j)
else:
j += 1
swap_item(ids, coords, j, right)
if j <= k:
left = j + 1
if k <= j:
right = j - 1
def _swap_item(self, ids, coords, i, ... | stack.append(right)
stack.append(nextAxis)
return result
def _sq_dist(self, ax, ay, bx, by):
dx = ax - bx
dy = ay - by
return dx * dx + dy * dy
class Cluster(object):
def __init__(self, x, y, num_points, id, props):
super(Cluster, self).__init__()
... | ints = num_points
self.zoom = float("inf")
self.id = id
self.props = props
self.parent_id = None
self.widget = None
# preprocess lon/lat
self.lon = xLng(x)
self.lat = yLat(y)
class Marker(object):
def __init__(self, lon, lat, cls=MapMarker, options=... |
import os
import string
import random
from fabric.api import env
from fabric.colors import green
from literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME,
DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES,
DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME,
DEFAULT_WEBSERVER, WEB_CHOIC... | S_CHOICES[env.os]
env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os])
env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os])
env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os])
env['virtualenv_path... | ath, env.virtualenv_name)
env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name)
env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER)
env['database_manager_name'] = DB_CHOICES[env.database_manager]
env['database_username'] = getattr(env, 'dat... |
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
('', include('imago.urls')),
url(r'^report/(?P<module_na | me>[a-z0-9_]+)/$', 'reports.views.report', name='report'),
url(r'^represent/(?P<module_name>[a-z0-9_]+)/$', 'reports.views.represent', name='represent'),
url(r'^warnings/$', ' | reports.views.warnings', name='warnings'),
url(r'^$', 'reports.views.home', name='home'),
)
|
from django.http import Http404
from django.shortcuts import render
from . import models
def index(request):
# Generate counts of some of the main objects
num_projects = models.Project.objects.all().count()
num_tasks = models.Tasks.objects.all().count()
num_fundings = models.Fundings.objects.all().co... | ]
featured_projects = models.Project.objects.all().filter(featured=1)
# Render the HTML template
return render(
request,
'home.html',
context={'projects': projects, 'featured': featured_projects, 'num_projects':num_projects, 'num_ | tasks':num_tasks, 'num_fundings':num_fundings, 'num_projects_goal':num_projects_goal},
)
def project(request, slug):
try:
p = models.Project.objects.get(slug=slug)
except models.Project.DoesNotExist:
raise Http404("Project does not exist")
return render(
request,
'sampl... |
from hel | per import greeting
if "__name__" == "__main__":
greeti | ng('hello') |
from datetime import timedelta
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT
from openerp.osv import orm
import openerp.tests.common as test_common
from .common import BaseAgreementTestMixin
class TestAgreementPriceList(test_common.TransactionCase,
BaseAgreementTestMixin):
"""... | ), 45.0)
self.assertEqual(
self.agreement.get_price(
| -10, currency=self.browse_ref('base.EUR')
), 70.0)
def test_01_failed_wrong_currency(self):
"""Tests that wrong currency raise an exception"""
with self.assertRaises(orm.except_orm):
self.agreement.get_price(0, currency=self.browse_ref('base.USD'))
|
from fabric.context_managers import settings
from golive.layers.base import BaseTask, DebianPackageMixin, IPTablesSetup
from golive.stacks.stack import environment
from golive.utils import get_remote_envvar
class RabbitMqSetup(BaseTask, DebianPackageMixin):
package_name = "rabbitmq-server"
GUEST_USER = "guest... | (environment.hosts, IPTablesSetup.DESTINATION_ALL, "4369"),
(environment.hosts, IPTablesSetup.DESTINATION_ALL, "8612"),
(environment.hosts, IPTablesSetup.DESTINATION_ALL, "5672"),
]
iptables = IPTablesSetup()
iptables.prepare_rules(allow)
iptables.set... | def status(self):
out = self.run("sudo %s status" % self.RABBIT_INITSCRIPT)
self._check_output(out, "running_applications", self.NAME)
def _set_listen_port(self):
self.append(self.__class__.RABBITMQ_CONFIGFILE,
"[{kernel, [ {inet_dist_listen_min, 9100}, {inet_dist_li... |
from __future__ import absolute_import
__all__ = ("DebugMeta",)
from sentry.interfaces.base import Interface
from sentry.utils.json import prune_empty_keys
class DebugMeta(Interface):
"""
Holds debug meta information for processing stacktraces
and similar things. This information is deleted after event... | for system symbols. If not defined, system symbols are not looked up.
``images``:
a list of debug images and their mappings.
"""
ephemeral = False
path = "debug_meta"
external_type = "debugmeta"
@classmethod
def to_python(cls, data):
return cls(
ima | ges=data.get("images", None) or [],
sdk_info=data.get("sdk_info"),
is_debug_build=data.get("is_debug_build"),
)
def to_json(self):
return prune_empty_keys(
{
"images": self.images or None,
"sdk_info": self.sdk_info or None,
... |
#!/usr/bin/python
import sys
import os
if len(sys | .argv) >= 4 :
filename = sys.argv[1]
row_i = int(sys.argv[2])-1
target_ls_filename = sys.argv[3]
output_filename = sys.argv[4]
else:
print("usage: python selectrow.py filename row_i target_ls_filename")
print("or ./selectrow.py filename row_i target_ls_filename")
sys.exit(1)
################... | ##################################
file = open(filename,'r')
dt = {}
for line in file:
ls=line.strip().split('\t')
if not dt.has_key(ls[row_i]):
dt[ ls[row_i] ] = []
dt[ ls[row_i] ].append( line.strip() )
file.close()
################################################################################
... |
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from .forms import LoginForm
class LoginViewTest(TestCase):
def setUp(self):
self.client = Client()
self.response = self.client.get(reve... | _is_not_optional(self):
# form = self.make_validated_form(username='')
# self.assertTrue(form.errors)
# def test_password_is_not_optional(self):
# form = self.make_validated_form(password='')
# self.assertTrue(form.errors)
def | test_form(self):
form = self.make_validated_form()
self.assertFalse(form.errors)
def make_validated_form(self, **kwargs):
data = {
'username': 'admin',
'password': '123',
}
data.update(kwargs)
form = LoginForm(data)
form.is_valid()
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ----------------------
from msrest.s | erialization import Model
class Usage(Model):
"""Describes Storage Resource Usage.
:param unit: The unit of measurement. Possible values include: 'Count',
'Bytes', 'Seconds', 'Percent', 'CountsPerSecond', 'BytesPerSecond'
:type unit: str or :class:`UsageUnit
<azure.mgmt.storage.v2015_06_15.mode... |
""" Django-admin autoregister -- automatic model registration
## sample admin.py ##
from yourproject.autoregister import autoregister
# register all models defined on each app
autoregister('app1', 'app2', 'app3', ...)
"""
from django.db.models import get_models, get_app
from django.con | trib import admin
from django.contrib.admin.sites import AlreadyRegistered
def autoregister(*app_list):
for app_name in app_list:
app_models = get_app(app_name)
for model in get_models(app_models):
try:
| admin.site.register(model)
except AlreadyRegistered:
pass
autoregister('utility') |
from common import *
import conduit.datatypes.File as File
import conduit.utils as Utils
import os
import tempfile
import datetime
import random
import stat
tmpdir = tempfile.mkdtemp()
ok("Created tempdir %s" % tmpdir, True)
contents = Utils.random_string()
name = Utils.random_string()+".foo"
tmpFile = File.TempFile... | 2)
#check that subsequent renames/mtimes are always deferred
#w | hen the file is a tempfile
nn = i+"-renamed-again"
f.force_new_filename(nn)
ok("tempfile filename ok again", f.get_filename() == nn)
mtime2 = datetime.datetime.now()
f.set_mtime(mtime2)
ok("tempfile set_mtime ok again", f.get_mtime() == mtime2)
#check we can create a second tempfile wit... |
create_mock_client()
bad_client.async_client_connect = AsyncMock(return_value=False)
# Confirmation sync_client_connect fails.
with patch(
"homeassistant.components.hyperion.client.HyperionClient",
side_effect=[good_client, bad_client],
):
result = await _configure_flow(hass, r... | c def test_auth_create_token_approval_declined(hass: HomeAssistantType) -> None:
"""Verify correct behaviour when a token request is declined."""
result = await _init_flow(hass)
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
with patch... | , return_value=client
):
result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_FAIL)
with patch(
"hom... |
#!/usr/bin/env python3
# Python libs
import os.path
import sys
import icebox
# FIXME: Move this into icebox
parts = [
# LP Series (Low Power)
"lp384",
"lp1k",
"lp8k",
# Unsupported: "lp640", "lp4k" (alias for lp8k),
# LM Series (Low Power, Embedded IP)
# Unsupported: "lm1k", "lm2k",
... | if ':' in package:
continue
for v in versions(part):
device = "{}.{}".format(v, package)
| print(device)
|
'''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati... | ,[g,h],[f,h],[e,h],[d,h],[c,h],[b,h],[a,h]], \
[[h,f],[g,f],[f,g],[e,g],[d,g],[c,g],[b,g],[a,g]], \
[[h,e],[g,e],[f,e],[e,f],[d,f],[c,f],[b,f],[a,f]], \
[[h,d | ],[g,d],[f,d],[e,d],[d,e],[c,e],[b,e],[a,e]], \
[[h,c],[g,c],[f,c],[e,c],[d,c],[c,d],[b,d],[a,d]], \
[[h,b],[g,b],[f,b],[e,b],[d,b],[c,b],[b,c],[a,c]], \
[[h,a],[g,a],[f,a],[e,a],[d,a],[c,a],[b,a],[a,b]]]
self.ALL_PINS = [a,b,c,d,e,f... |
# Copyright © 2016-2017 Simon McVittie
# SPDX-License-Identifier: GPL-2.0+
# (see vectis/__init__.py)
import os
import pwd
import shutil
import subprocess
from tempfile import TemporaryDirectory
from debian.debian_support import (
Version,
)
from vectis.commands.new import vmdebootstrap_argv
from vectis.error im... | rsion = subprocess.check_output(
['dpkg-query', '-W', '-f${Version}', 'vmdebootstrap'],
universal_newlines=True).rstrip('\n')
except subprocess.CalledProcessException:
| # non-dpkg host, guess a recent version
version = Version('1.7')
debootstrap_version = Version('1.0.89')
else:
version = Version(version)
debootstrap_version = subprocess.check_output(
['dpkg-query', '-W', '-f${Version}', 'debootstrap'],
universal_newlines=T... |
شلوار",
"شلوارو": "شلوار",
"شلواروں": "شلوار",
"شلواریں": "شلوار",
"شمے": "شمہ",
"شمشیر": "شمشیر",
"شمشیرو": "شمشیر",
"شمشیروں": "شمشیر",
"شمشیریں": "شمشیر",
"شمارے": "شمارہ",
"شمارہ": "شمارہ",
"شمارو": "شمارہ",
"شماروں": "شمارہ",
"شمع": "شمع",
"شمعو": "شمع",
"شمعوں": "شمع",
"شمعیں": "شم... | ِترانا": "اِترانا",
"اِترانی": "اِترانا",
"اِتراتے": "اِترانا",
"اِتراتا": "اِترانا",
"اِتراتی": "اِترانا",
"اِتراتیں": "اِترانا",
"اِتراؤ": "اِترانا",
"اِتراؤں": "اِترانا | ",
"اِترائے": "اِترانا",
"اِترائی": "اِترانا",
"اِترائیے": "اِترانا",
"اِترائیں": "اِترانا",
"اِترایا": "اِترانا",
"اُڑ": "اُڑنا",
"اُڑے": "اُڑنا",
"اُڑں": "اُڑنا",
"اُڑا": "اُڑنا",
"اُڑانے": "اُڑنا",
"اُڑانا": "اُڑنا",
"اُڑاتے": "اُڑنا",
"اُڑاتا": "اُڑنا",
"اُڑاتی": "اُڑنا",
"اُڑاتیں": "ا... |
""" Cisco_IOS_XR_patch_panel_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR patch\-panel package configuration.
This module contains definitions
for the following management objects\:
patch\-panel\: patch\-panel service submode
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All right... | ble = None
self.ipv4 = None
self.password = | None
self.user_name = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-patch-panel-cfg:patch-panel'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if self._is_pr... |
eor.graphql.core.utils.reordering import perform_reordering
from saleor.product import models
SortedModel = models.AttributeValue
def _sorted_by_order(items):
return sorted(items, key=lambda o: o[1])
def _get_sorted_map():
return list(
SortedModel.objects.values_list("pk", "sort_order").order_by("s... | bottom of the list.
"""
qs = SortedModel.objects
nodes = sorted_entries_seq
target_node_pos | , new_rel_sort_order = operation
operations = {nodes[target_node_pos].pk: new_rel_sort_order}
expected = _sorted_by_order(
[
(node.pk, node.sort_order + op)
for node, op in zip(nodes, expected_operations)
]
)
perform_reordering(qs, operations)
actual = _ge... |
# -*- | coding: utf-8 -*-
import unittest
from test.basetestcases import PluginLoadingMixin
class StatisticsLoadingTest (PluginLoadingMixin, unittest.TestCase):
def getPluginDir(self):
"""
Должен возвращать путь до папки с тестируемым плагином
"""
return | "../plugins/statistics"
def getPluginName(self):
"""
Должен возвращать имя плагина, по которому его можно
найти в PluginsLoader
"""
return "Statistics"
|
able.
"""
try:
workbench = util.check_output('which wb_command')
workbench = workbench.strip()
except:
workbench = None
return workbench
def find_fsl():
"""
Returns the path of the fsl bin/ folder, or None if unavailable.
"""
# Check the FSLDIR environment varia... | lates():
"""
Returns the hcp scene templates path. If the shell variable
HCP_SCENE_TEMPLATES is set, uses that. Otherwise returns the defaults
stored in the ciftify/data/scene_templates folder.
"""
dir_hcp_templates = os.getenv('HCP_SCENE_TEMPLATES')
if dir_hcp_templates is None:
ci... | find_ciftify_global():
"""
Returns the path to ciftify required config and support files. If the
shell variable CIFTIFY_DATA is set, uses that. Otherwise returns the
defaults stored in the ciftify/data folder.
"""
dir_templates = os.getenv('CIFTIFY_DATA')
if dir_templates is None:
c... |
#!/usr/bin/env python
#
# Copyright 2020 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest
import random, numpy
from gnuradio import digital, blocks, channels
class qa_linear_equalizer(gr_unittest.TestCase):
... | self.data = data = [0]*4+[random.getrandbits(8) for i in range(payload_size)]
self.gain = gain = .001 # LMS gain
self.corr_thresh = corr_thresh = 3e6
self.num_taps = num_taps = 16
|
def tearDown(self):
self.tb = None
def transform(self, src_data, gain, const):
SRC = blocks.vector_source_c(src_data, False)
EQU = digital.lms_dd_equalizer_cc(4, gain, 1, const.base())
DST = blocks.vector_sink_c()
self.tb.connect(SRC, EQU, DST)
self.tb... |
#
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 CO... | ee the License for the specific language governing permissions and
# limitations under the License.
#
# Authenticates user for accessing the ISB-CGC Endpoint APIs.
#
# May be run from the command line or in scripts/ipython.
#
# The credentials file can be copied to any machine from which you want
# to access the API.
#... |
# encoding: 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 model 'UserKey'
db.create_table('sshkey_userkey', (
('id', self.gf('django.db.models.... | : {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.Cha... | o': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'def... |
lue(key)
assert headers['Sec-Websocket-Accept'] == accept
extensions = self._parse_extensions_header(headers)
for ext in extensions:
if (ext[0] == 'permessage-deflate' and
self._compression_options is not None):
self._create_compressors('client', ... | = self.FIN
else:
finbit = 0
frame = struct.pack("B", finbit | opcode | flags)
l = len(data)
if self.mask_outgoing:
mask_bit = 0x80
else:
mask_bit = 0
if l < 126:
frame += struct.pack("B", l | mask_bit)
elif l <= 0xFF... | mask = os.urandom(4)
data = mask + _websocket_mask(mask, data)
frame += data
self._wire_bytes_out += len(frame)
try:
return self.stream.write(frame)
except StreamClosedError:
self._abort()
def write_message(self, message, binary=False):
... |
cable no se agrupan por lotes.
elif isinstance(articulo, (pclases.Pale, pclases.Caja)):
#, pclases.Bolsa)):
lote = articulo.partidaCem
self.rellenar_info_partida_cemento(lote, txtvw)
else:
escribir(txtvw, "¡NO SE ENCONTRÓ INFORMACIÓN!\n"
"P... | "%s.\n" % (
adeda.numalbaran,
utils.str_fecha(adeda.fecha)))
elif isinstance(objeto, pclases.PartidaCarga):
escribir(txtvw,
"Se consumió el %s en la p... | e carga %s.\n"%(
utils.str_fecha(fecha),
objeto.codigo),
("_rojoclaro", "cursiva"))
if articulo.articulo.en_almacen():
escribir(txtvw,
"El artículo está en... |
from images import fields
from product | _images.models import ProductImage
class ImagesFormField(fields.ImagesFormField):
def __init__(self):
super().__init__(ProductIma | ge)
|
from __future__ import print_function
from __future__ import unicode_literals
import io
import os.path
import pipes
import sys
from pre_commit import output
from pre_commit.util import make_executable
from pre_commit.util import mkdirp
from pre_commit.util import resource_filename
# This is used to identify the hoo... | ook_type))
skip_on_missing_conf = 'true' if skip_on_missing_conf else 'false'
contents = io.open(resource_filename('hook-tmpl')).read().format(
sys_executable=pipes.quote(sys.executable),
hook_type=hook_type,
hook_specific=hook_specific_contents,
config_f... | e-commit installed at {}'.format(hook_path))
# If they requested we install all of the hooks, do so.
if hooks:
install_hooks(runner)
return 0
def install_hooks(runner):
for repository in runner.repositories:
repository.require_installed()
def uninstall(runner, hook_type='pre-commit... |
int | ervals = [[10,20],[6,15],[0,22]]
print(sorted(interval | s)) |
self.Step (M | essage = "Receptionist- | N ->> Klient-N [genvej: fokus-modtagerliste] (måske)")
self.Step (Message = "Receptionist-N ->> Klient-N [retter modtagerlisten]")
|
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils.data import flt, nowdate, getdate, cint
class MoneyTransfere... | .from_company + " - "+self.abbr_to,
"com | pany": self.to_company,
"parent_account":"حساب استلام من"+" - "+self.abbr_to })
self.dummy_to=dummy_to[0][0]
dummy_from = frappe.db.get_values("Account", {"name": "حساب ارسال الي"+" - "+self.to_company + " - "+self.abbr,
"company": self.from_company,
"parent_account":"حساب ارسال"+" - "+self.abbr })
self... |
from django.conf.urls import patterns, url, include
from .views import empty_view, empty_view_partial, empty_view_wrapped, absolute_kwargs_view
other_patterns = patterns('',
url(r'non_path_include/$', empty_view, name='non_path_include'),
url(r'nested_path/$', 'urlpatterns_reverse.views.nested_view'),
)
url... | e/(\w+)', empty_view, name="insensitive"),
url(r'^test/1/?', empty_view, name="test"),
url( | r'^(?i)test/2/?$', empty_view, name="test2"),
url(r'^outer/(?P<outer>\d+)/', include('urlpatterns_reverse.included_urls')),
url(r'^outer-no-kwargs/(\d+)/', include('urlpatterns_reverse.included_no_kwargs_urls')),
url('', include('urlpatterns_reverse.extra_urls')),
# This is non-reversible, but we shoul... |
# Django settings for hikeplanner project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Jaime', 'jaime.m.mccandless@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': ... | ication used by Django's runserver.
WSGI_APPLICATION = 'src.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"hikes/templates"... | D_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.gis',
'hikes',
# Uncomment the next line to enable admin documentat... |
rom rhn.client import rhnHardware
rhnHardware.updateHardware()
# FIXME (20050415): Proper output method
print "Hardware profile refresh successful"
if action == "showall" or action == "show_available" \
or action == "showall_with_channels" or action == "show_a... | tus(self):
if self._activestatus:
self._activestatus = False
print
def askYesNo(self, question, default=False):
self.hideStatus()
mask = default and _("%s (Y/n): ") or _("%s (y/N): ")
res = raw_input(mask % question).strip().lowe | r()
print
if res:
return (_("yes").startswith(res) and not
_("no").startswith(res))
return default
def askContCancel(self, question, default=False):
self.hideStatus()
if default:
mask = _("%s (Continue/cancel): ")
else:
... |
y the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy o... | try:
i | f dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
if (response is None or
not isinstance(response, dict) or
'Status' not in response):
#log.exc... |
import os
import zipfile
import csv
from django.core.management.base import BaseCommand
from django.db import transaction
from django.conf import settings
from ...models import Service
def get_service(row):
for region in 'EA', 'EM', 'WM', 'SE', 'SW':
col = 'TNDS-' + region
if row[col]:
... | floor,
assistance_service=row['Assistance Service'] == 'TRUE',
| mobility_scooter=row['MobilityScooter'] == 'TRUE')
class Command(BaseCommand):
@transaction.atomic
def handle(self, *args, **options):
path = os.path.join(settings.DATA_DIR, 'accessibility-data.zip')
with zipfile.ZipFile(path) as archive:
for path in archive... |
import re
CJDNS_IP_REGEX = re.compile(r'^fc[0-9a-f]{2}(:[0-9a-f]{4}){7}$', re.IGNORECASE)
class Node(object):
def __init__(self, ip, version=None, label=None):
if not valid_cjdns_ip(ip):
raise ValueError('Invalid IP address')
if not valid_version(version):
raise ValueErro... | f.ip = ip
self.version = int(version)
self.label = ip[-4:] or label
def __lt__(self, b):
return self.ip < b.ip
def __repr__(self):
return 'Node(ip="%s", version=%s, label="%s")' % | (
self.ip,
self.version,
self.label)
class Edge(object):
def __init__(self, a, b):
self.a, self.b = sorted([a, b])
def __eq__(self, that):
return self.a.ip == that.a.ip and self.b.ip == that.b.ip
def __repr__(self):
return 'Edge(a.ip="{}", b.... |
from app import | db
class Pets(db.Model):
__tablename__ = 'pets'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), unique=True)
color = db.Column(db.String(30))
pet = db.Column(db.String(10))
def __init__(self, name, color, pet):
self.name = name
self.color = color... | {}>'.format(self.id)
|
t.
# import sys
# import os
from pygments.lexers.web import PhpLexer
from sphinx.highlighting import lexers
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make i... | ---------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.ifc | onfig',
'sphinx.ext.todo',
]
# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# ... |
lSize/2**20,2))
else:
if totalSize!=-1 :
print ('\r','%.2f'%round(blockNum*blockSize/2**20,2),
'/','%.2f'%round(totalSize/2**20,2),
'MB ','%.2f'%round(blockNum*blockSize/totalSize*100,2),'%',end='')
else:
print ('\r','%.2f'%round(block... | connectionError=True
resetCounter+=1
else:
raise
except urllib.error.URLError as errinfo:
| # URL Error
if (isinstance(errinfo.reason,socket.gaierror) and
errinfo.reason.errno==-2):
# Name or service not known, usually caused by internet break or wrong server address
connectionError=True
resetCounter+=1
time.sleep(... |
def do | _something():
for i in range(100):
p | rint(i)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.