prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
def f(x):
return x + 1
rais | e V | alueError("I do not want to be imported")
|
Here we print an expression that may contain Indexed objects, they
# correspond to arrays in the generated code. The low-level implementation
# involves looping over array elements and possibly storing results in temporary
# variables or accumulate it in the assign_to object.
lhs_prin... | # } ^.................. the accumulator
#
# We check if the expression already contains the
# lhs, and raise an exception if it does, as that
# syntax is currently undefined. FIXME: What wo... | if assign_to is None:
raise AssignmentError(
"need assignment variable for loops")
if term.has(assign_to):
raise ValueError("FIXME: lhs present in rhs,\
this is undefin... |
None, "cual entidad remover un atributo?", 'Eliminar Atributo', '')
if dlg.ShowModal() == wx.ID_OK:
response = dlg.GetValue()
for elemento in self.GetActiveChild().entidades:
if elemento.nombre == response:
ejecute.DlgEliminarAtributo(self.GetActiveChild().canvas, elemento)""... | lf.locale.AddCatalog(language[self.data["idioma"]])
idioma = language[self.data["idioma"]]
for menu in self.menuFile.GetMenuItems():
if menu.GetId() != -2:
menu.SetText(self.translation(archivo[menu.GetId()]))
menu.SetHelp(self.translation(archivoHelp[menu.GetId()]))
... | menu in self.menuVer.GetMenuItems():
if menu.GetId() != -2:
menu.SetText(self.translation(archivo[menu.GetId()]))
menu.SetHelp(self.translation(archivoHelp[menu.GetId()]))
for menu in self.menuTool.GetMenuItems():
if menu.GetId() != -2:
menu.SetText(self.... |
g>
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 3 only.
##
## Gajim is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; wi... | self.label.show()
return
if self.data_form_widget.title:
self.window.set_title('%s - Search - Gajim' % \
self.data_form_widget.title)
else:
self.is_form = False
self.data_form_widget = config.FakeDataForm(obj.data)
... | h_button.set_sensitive(True)
def on_result_treeview_cursor_changed(self, treeview):
if self.jid_column == -1:
return
(model, iter_) = treeview.get_selection().get_selected()
if not iter_:
return
if model[iter_][self.jid_column]:
self.add_contact_b... |
definovanou v konstruktoru (self.shape).
U modelu je potřeba brát v potaz polohu objektu. Ta je udávána pomocí
crinfo. To je skupina polí s minimální a maximální hodnotou pro každou osu.
Trénování je prováděno opakovaným voláním funkce train_one().
:param model_margin: stanovuje velikost okraje v mod... | nx, maxx], [miny, maxy], [minz, maxz]]
"""
# Průměrování
mdl = self.model / se | lf.data_number
print(mdl.shape)
print(crinfo)
# mdl_res = imma.image.resize_to_shape(mdl, crinfo[0][]
uncr = qmisc.uncrop(mdl, crinfo, image_shape, resize=True)
return uncr
def train_one(self, data,voxelSize_mm):
"""
Trenovani shape modelu
data se vez... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-18 14:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testapp', '0001_initial | '),
]
operations = | [
migrations.AlterField(
model_name='cat',
name='sex',
field=models.CharField(choices=[('F', 'Female'), ('M', 'Male')], max_length=1),
),
]
|
consecutive characters to a
single '_', but this has been removed. This functionality should
possibly be added as a new function."""
return s.replace("/", "\\").lower()
def isabs(s):
"""Return whether a path is absolute.
Trivial in Posix, harder on the Mac or MS-DOS.
For DOS it is... | urn the head (dirname) part of a path."""
return split(p)[0]
def commonprefix(m):
"""Return the longest prefix of all list elements."""
if not m: return ''
prefix = m[0]
for item in | m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0: return ''
break
return prefix
# Get size, mtime, atime of files.
def getsize(filename):
"""Return the size of a file, reported by os.s... |
#!/usr/bin/env python
'''
Command to send dynamic filesystem information to Zagg
'''
# vim: expandtab:tabstop=4:shiftwidth=4
#
# Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a... | er out xvda{2} (???) and nvme devices past 2
return {
k:v for (k, v) in metric_dict.iteritems() if not r.match(k)
}
def zero_mount_percentages(metric_dict):
""" Make all mounts report 0% used """
return {
k:0 for (k, v) in metric_dict.iteritems()
}
def main():
""" Main functi... | to run the check """
args = parse_args()
metric_sender = MetricSender(verbose=args.verbose, debug=args.debug)
filesys_full_metric = ['filesys.full']
filesys_inode_derived_metrics = {'filesys.inodes.pused' :
'filesys.usedfiles / (filesys.usedfiles + filesys.freefil... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
"OT-MONO2-8-colon.dcm",
tfio.image.dicom_tags.StudyIns | tanceUID,
b"1.3.46.670589.17.1.7.1.1.16",
),
("OT-MONO2-8-colon.dcm", tfio.image.dicom_tags.Rows, b"512"),
("OT-MONO2-8-colon.dcm", tfio.image.dicom_tags.Columns, b"512"),
("OT-MONO2-8-colon.dcm", tfio.image.dicom_tags.SamplesperPixel, b"1"),
(
"US-PAL-8-1... |
# test driver to verify that new version of code works
import opiniongame.config as og_cfg
import opiniongame.IO as og_io
import opiniongame.coupling as og_coupling
import opiniongame.state as og_state
import opiniongame.opinions as og_opinions
import opiniongame.adjacency as og_adj
import opiniongame.selection as og_s... | state.initialOpinions = og_opinions.initialize_opinions(config.popSize, config.ntopics)
# maybe you want to do Consensus and nonConsensus. Finding consensus is easier!
# assuming pop_size = 20, ten people at 1, nine people at 0 and and one person
| # at 0.5 will be polarization, but, still ...
resultMatrix[i][j][0] = polarized
resultMatrix[i][j][1] = notPolarized
resultMatrix[i][j][2] = aveIters/100.0
rdict = {}
rdict['results'] = resultMatrix
og_io.saveMatrix('output.mat', rdict)
|
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana 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
#
# ... | self.gpt = GPUTensor
def test_empty_creation(self):
tns = self.gpt([])
expected_shape = (0, )
while len(expected_shape) < tns._min_dims:
| expected_shape += (1, )
assert tns.shape == expected_shape
def test_1d_creation(self):
tns = self.gpt([1, 2, 3, 4])
expected_shape = (4, )
while len(expected_shape) < tns._min_dims:
expected_shape += (1, )
assert tns.shape == expected_shape
def te... |
import lxml
import requests
def requests_session():
"""
Get a suitable requests session for use in SmartBot.
In particular, this sets the `User-Agent` header to the value of
'SmartBot'.
"""
session = requests.Session()
session.headers.update({"User-Agent": "SmartBot"})
return session
... | se, content_type="text/html"):
return response.headers.get("Content-Type", "").startswith(content_type)
def get_title(url):
"""Get the title of a website."""
try:
page = requests_session().get(url, timeout=5, stream=True)
if page.status_code == 200 and _check_content_type(page):
... | tree = lxml.html.fromstring(page.content)
title = tree.cssselect("title")[0].text_content()
return title.strip().replace("\n", "").replace("\r", "")
except requests.exceptions.Timeout:
return "Timeout!"
except IndexError: # no title element
return "No title."
def s... |
#-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | //www.rennes.supelec.fr/ren/rd/cidre/ |
#+-------------------------------------------------------------- | -------------+
#+---------------------------------------------------------------------------+
#| File contributors : |
#| - Georges Bossert <georges.bossert (a) supelec.fr> |
#| - Frédéric Guihéry <frederic.guihery (a) amossys.fr> ... |
"""
homeassistant.config
~~~~~~~~~~~~~~~~~~~~
Module to help with parsing and generating configuration files.
"""
import logging
import os
from homeassistant.exceptions import HomeAssistantError
from homeassistant.const import (
CONF_LATITUDE, CONF_LONGITUDE, CONF_TEMPERATURE_UNIT, CONF_NAME,
CONF_TIME_ZONE)
... | ation_info()
if location_info:
if location_info.use_fahrenheit:
info[CONF_TEMPERATURE_UNIT] = 'F' |
for attr, default, prop, _ in DEFAULT_CONFIG:
if prop is None:
continue
info[attr] = getattr(location_info, prop) or default
# Writing files with YAML does not create the most human readable results
# So we're hard coding a YAML template.
try:
with ... |
from namespace_class import *
try:
p = Private1()
error = 1
except:
error = 0
if (error):
raise Runti | meError, "Private1 is private"
try:
p = Private2()
error = 1
except:
error = | 0
if (error):
raise RuntimeError, "Private2 is private"
EulerT3D.toFrame(1,1,1)
b = BooT_i()
b = BooT_H()
f = FooT_i()
f.quack(1)
f = FooT_d()
f.moo(1)
f = FooT_H()
f.foo(Hi)
|
"""
Django settings for BenHoboCo project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside | the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
GET_SOLO_TEMPLATE_TAG_NAME = | 'get_solo'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b&r86v3qyzx=d^8p8k4$c!#imhb+jys*$g@yxz8#vt83@r-va_'
# SECURITY WARNING: don't run with de... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rdrf', '0022_merge'),
]
operations = [
migrations.AddField(
model_name='rdrfcontext',
na | me='context_form_group',
field=models.ForeignKey(blank=True,
to='rdrf.ContextFormGroup',
null=True,
| on_delete=models.SET_NULL),
),
]
|
# -*- coding: utf8 -*-
# SDAPS - Scripts for data acquisition with paper based surveys
# Copyright(C) 2008, Christoph Simon <post@christoph-simon.eu>
# Copyright(C) 2008, Benjamin Berg <benjamin@sipsolutions.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | elf.images.append(image)
image.sheet = self
def get_page_image(self, page):
| # Simply return the image for the requested page.
# Note: We return the first one we find; this means in the error case
# that a page exists twice, we return the first one.
for image in self.images:
if image.page_number == page and image.survey_id == self.survey.survey_i... |
# -*- coding: utf-8 -*-
"""
**********************
Minimum Dominating Set
**********************
A dominating set for a graph G = (V, E) is a subset D of V such that every
vertex not in D is joined to at least one member of D by some edge. The
domination number gamma(G) is the number of vertices in a smallest dominat... | # reduce the cost for the rest
for node in min_set - dom_set:
cost_func[node] = alpha
# add the node to the dominating set and reduce what we must cover
dom_set.add(dom_node)
del sets[dom_node]
vertices = vertices - min_set
return dom_set
def min_edge_dominati... | inating_set : set
Returns a set of dominating edges whose size is no more than 2 * OPT.
"""
if not graph:
raise ValueError("Expected non-empty NetworkX graph!")
return nx.maximal_matching(graph)
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
... | cd = c.subtract(d)
x = ab.cross_product(bc)
y = bc.cross_product(cd)
cosine = x.dot_product(y) / (x.value() * y.value())
return math.degrees(math.acos(cosine))
def main():
a = Vector(*tuple(map(float, input().strip().split())))
b = Vector(*tuple(map(float, input().strip().split())))
c = V... | int('%.2f' % torsional_angle(a, b, c, d))
if __name__ == '__main__': # pragma: no cover
main()
class TestCode(unittest.TestCase):
def generalized_test(self, which):
sys.stdin = open(__file__.replace('.py', f'.{which}.in'), 'r')
sys.stdout = io.StringIO()
expected = open(__file__.rep... |
# Author: Marcin Serwach
# https://github.com/iblis-ms/conan_gbenchmark
from conans import ConanFile, CMake, tools
import os
import sys
import shutil
class GbenchmarkConan(ConanFile):
name = 'GBenchmark'
version = '1.3.0'
license = 'MIT L | icence'
url = 'https://github.com/iblis-ms/conan_gbenchmark'
description = 'Conan.io su | pport for Google Benchmark'
settings = ['os', 'compiler', 'build_type', 'arch', 'cppstd']
options = {
'BENCHMARK_ENABLE_TESTING': [True, False],
'BENCHMARK_ENABLE_LTO': [True, False]
}
default_options = ('BENCHMARK_ENABLE_TESTING=False',
'BENCHMARK_ENA... |
# -*- coding | : utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class HackernewsscraperItem(scrapy.Item):
# define the fields for your item here like:
title = scrapy.Field()
link = s | crapy.Field()
|
from django import forms
from .models import doctor
class ContactForm(forms.Form):
message = forms.CharField()
class SignUpForm(forms.ModelForm):
class Meta:
model = doctor
fields = ['full_name', 'email']
class are | aForm(forms.For | m):
messag = forms.CharField(required=False)
|
import os
from segments import Segment, theme
from utils import colors, glyphs
class CurrentDir(Segment):
bg = colors.background(theme.CURRENTDIR_BG)
fg = colors.foreground(theme.CURRENTDIR_FG)
def init(self, cwd):
home = os.path.expanduser('~')
self.text = cwd.replace(home, '~')
class... | , cwd):
self.text = ' ' + glyphs.WRITE_ONLY + ' '
if os.access(cwd, os.W_OK):
self.active = False
class Venv(Segment):
bg = colors.background(theme.VENV_BG)
fg = colors.foreground(theme.VENV_FG)
def init(self):
env = os.getenv('VIRTU | AL_ENV')
if env is None:
self.active = False
return
env_name = os.path.basename(env)
self.text = glyphs.VIRTUAL_ENV + ' ' + env_name |
import os
import sys
from .interfaces import Interface
from .search import SearchManager
from .cache im | port CacheManager
from .select import Select
from .help import | Inspector
from .users import Users
from .packages import Packages
|
# Copyright 2016 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, ... | moves.zip(_POW2, curr_bits))
byte_vals.append(char_val)
return bytes(byte_vals)
class RSAVerifier(b | ase.Verifier):
"""Verifies RSA cryptographic signatures using public keys.
Args:
public_key (rsa.key.PublicKey): The public key used to verify
signatures.
"""
def __init__(self, public_key):
self._pubkey = public_key
@_helpers.copy_docstring(base.Verifier)
def veri... |
# coding: utf-8
import numpy as np
from common.functions import *
from common.util import im2col, col2im
class Relu:
def __init__(self):
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0
return out
def backward(self, do... | self.db = np.sum(dout, axis=0)
dx = dx.reshape(*self.original_x_shape) # 入力データの形状に戻す(テンソル対応)
return dx
class SoftmaxWithLoss:
def __init__(self):
self.loss = None
self.y = None # softmaxの出力
self.t = None # 教師データ
def forward(self, x, t):
self.t = t
... | lf, dout=1):
batch_size = self.t.shape[0]
if self.t.size == self.y.size: # 教師データがone-hot-vectorの場合
dx = (self.y - self.t) / batch_size
else:
dx = self.y.copy()
dx[np.arange(batch_size), self.t] -= 1
dx = dx / batch_size
return dx
... |
from setuptools import setup, find_packages
import os
version = '0.5'
setup(name='uwosh.emergency.master',
version=version,
description="",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from http:... | e :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='',
author='Nathan Van Gheem',
author_email='vangheem@gmail.com',
| url='http://svn.plone.org/svn/plone/plone.example',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['uwosh', 'uwosh.emergency'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'uwosh.simpleemergency>=... |
__author__ = 'harsha'
class ForceReply(object):
def __init__(self, force_reply, selective):
self.force_reply = force_reply
self.selective = selective
def get_force_reply(self):
return self.force_reply
def get_selective(self):
return self.selective
| def __str | __(self):
return str(self.__dict__) |
# Copyright (c) 2014-2016, NVIDIA CORPORATION. All | rights reserved.
from __future__ import absolute_import
from . import caffe_train
from digits import test_utils
def test_caffe_imports():
test_utils.skipIfNotFramework('caffe')
impo | rt numpy
import google.protobuf
|
ding: utf-8 -*-
#
# agnez documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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 configu... | u'Agnez Documentation',
[u'Eder Santana'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, ti | tle, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'agnez',
u'Agnez Documentation',
u'Eder Santana',
'agnez',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If fals... |
/python
# -*- coding: utf-8 -*-
"""
Script to upload images to wikipedia.
Arguments:
-keep Keep the filename as is
-filename Target filename without the namespace prefix
-noverify Do not ask for verification of the upload description if one
is given
-abortonwarn: Abort upload o... | ))
if match.group(2): # suffix too
suffix = match.group | (2).lower()
if suffix == "k":
suffix = 1000
elif suffix == "m":
suffix = 1000000
elif suffix == "ki":
suffix = 1 << 10
... |
from time import sleep
from os.path import join
import pytest
from cosmo_tester.framework.examples import get_example_deployment
from cosmo_tester.framework.test_hosts import Hosts, VM
from cosmo_tester.test_suites.snapshots import (
create_snapshot,
download_snapshot,
restore_snapshot,
upload_snapsho... | ager, vm = manager_and_vm
example = get_example_deployment(
manager, ssh_key, logger, 'inplace_restore', test_config, vm)
try:
yield example
finally:
if example.installed:
example.uninstall()
def test_inplace_restore(manager_and_vm,
example,
... | r,
logger):
manager, vm = manager_and_vm
snapshot_name = 'inplace_restore_snapshot_{0}'.format(manager.image_type)
snapshot_path = join(str(module_tmpdir), snapshot_name) + '.zip'
example.upload_and_verify_install()
create_snapshot(manager, snapshot_name, logger)
down... |
from pathlib import Path
import re
from setuptools import setup
setup_dir = Path(__file__).resolve().parent
version = re.search(
r'__version__ = "(.*)"',
Path(setup_dir, 'tldr.py').open().read()
)
if version is None:
raise SystemExit("Could not determine version to use")
version = version.group(1)
with op... | ])],
install_requires=required,
tests_require=[
'pytest',
'pytest-runner',
],
version=version,
python_ | requires='~=3.6',
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"O... |
import unittest
import sys
sys.path.insert(0, "..")
from sections.sections import Circle
import test_sections_generic as generic
class TestPhysicalProperties(generic.TestPhysicalProperties, unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sectclass = Circle
cls.dimensions = dic... |
cls.rp = 5.0, 4.0
cls.A = 28.274333882308138
cls._I0 = 63.61725123519331, 63.61725123519331, 0.0
cls._I = 63.61725123519331, 63.61725123519331, 0.0
cls._cog = 0.0, 0.0
def test_check_dimensions(self):
self.assertRaises(Val... | elf.section.set_dimensions, r=0)
if __name__ == "__main__":
unittest.main()
|
"""API integration tests factories."""
import factory
from django_common.auth_backends import User
from factory.django import DjangoModelFactory
from samaritan.models import Address, ChurchRole, MembershipType, ChurchGroup, Member
class UserFactory(DjangoModelFactory):
"""Factory for users."""
username = f... | for member in extracted:
self.members.add(member)
class MembershipTypeFactory(DjangoModelFactory):
"""Membership Type Factory."""
name = factory.Faker('name')
description = factory.Faker('text')
class Meta:
model = MembershipType
class MemberFactory(DjangoModelFactory):
... | r('name')
date_of_birth = factory.Faker('date_this_century')
telephone = factory.Faker('random_int', min=0, max=99999999)
address = factory.SubFactory(AddressFactory)
email = factory.Faker('email')
details = factory.Faker('text')
is_baptised = factory.Faker('boolean')
baptismal_date = factor... |
"""ユーザー設定用モジュール."""
import os
DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'app1',
'app2',
]
ROOT_URLCONF = 'project.urls'
WSGI_APPLICATION = [
# 'wsgiref.validate.validator',
'ngo.wsgi.RedirectAp | p',
'ngo.wsgi.WSGIHandler',
]
"""
以下のように読み込まれていきます
app = None
app = WSGIHandler(None)
app = RedirectApp(app)
app = validator(app)
"""
# TEMPLATES = ('ngo.backends.Ngo', [])
"""
TEMPLATES = (
'ngo.backends.Ngo',
[os.path.join(BASE_DIR, 'template'), os.path.join(BASE_DIR, 'template2')]
)
"... |
]
"""
STATIC_URL = 'static'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media'
|
plit
else:
shell_split = shlex.split
try:
while True:
arg = itr.next()
if arg.strip() in ['-I', '-isystem']:
# extract paths handling quotes and multiple paths
paths += shell_s... | dError()
@classmethod
def find_best(cls):
global _cla | sses
for possible_cls in _classes:
if possible_cls.detect():
return possible_cls()
# PackageKit dbus interface contains bitfield constants which
# aren't introspectable
PK_PROVIDES_ANY = 1
PK_FILTER_ENUM_NOT_INSTALLED = 1 << 3
PK_FILTER_ENUM_NEWEST = 1 << 16
PK_FILTER_ENUM_ARCH = 1 ... |
# Copyright (c) 2018 PaddlePaddle 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 app... |
x = fluid.layers.data(name='x', shape=[3], dtype='float32')
output = fluid.layers.sampling_id(x)
place = fluid.CPUPlace()
exe = fluid.Executor(place=place)
exe.run(fluid.default_startup_program())
feed = {
'x': np.array(
[[0.2, 0.3, 0.5], [0... | pe='float32')
}
output_np = exe.run(feed=feed, fetch_list=[output])[0]
self.assertEqual(output.shape[0], -1)
self.assertEqual(len(output.shape), 1)
self.assertEqual(output_np.shape[0], 2)
self.assertEqual(len(output_np.shape), 1)
if __name__ == "__main__":
unittest... |
# 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
# d... | <xmldsig:Reference URI="#a5f02efb0bff4044b294b4583c7dfc5d">
<xmldsig:Transforms>
<xmldsig:Transform
Algorithm="http://www.w3.org/2000/09/xmldsig#
| enveloped-signature"/>
<xmldsig:Transform
Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</xmldsig:Transforms>
<xmldsig:DigestMethod
Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<xmldsig:DigestValue>
0KH2CxdkfzU+6eiRhTC+mbObUKI=
... |
# https://codecombat.com/play/level/if-stravaganza?
#
# Debes Comprar & Equipar:
# 1. Reloj de Pulsera Simple
# 2. Programática II
#
# ¡Derrota a los ogros desde dentro de su pro | pio campamento!
while True:
enemy = hero.findNearestEnemy()
# Usa la sentencia if para comprobar si existe un enemigo
# Ataca al enemigo si existe:
if enemy:
| hero.attack(enemy) * 2
|
tr:
field_type = "unicode"
else:
field_type = "unicode"
result.append(dict(name=key, type=field_type))
return result
def apply(self, session=None, **kwargs):
result = super(WMISourceType, self).apply(
result_type=self.type_name, *... | ame)
if not result:
if self.unsupported_source_types:
raise errors.FormatError(
"No supported sources: %s" % (
self.unsupported_source_types,))
raise errors.FormatError("No available sources.")
return result
def ... | supported_os = art_definition.get(
"supported_os", definitions.SUPPORTED_OS)
undefined_supported_os = set(supported_os).difference(
definitions.SUPPORTED_OS)
if undefined_supported_os:
raise errors.FormatError(
u'supported operating system: {} '
... |
import sys
try:
| from gensim.models.word2vec_inner import FAST_VERSION
print('FAST_VERSION ok ! Retrieved with value ', FAST_VERSION)
sys.exit()
except ImportError:
print('Failed... fall back to plain numpy (20-80x slower training than the above)')
| sys.exit(-1)
|
# usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 13:15:05 2017
@author: Vijayasai S
"""
# Use python3
from haversine import distance
from datetime import datetime
from dateutil import tz
import my_dbscan as mydb
import alert_update as au
from pymongo import MongoClient
import pandas as pd
im... | :{"$gte":datetime(year,month,day,hr,mins,0)}},{"timestamp":{"$lte":datetime(year,month,day,hr_next,mins_next,0)}}], "ride_id":ride_id})
coll_2 = db.tapola_rank_15_manual_clus_alert
|
au.Generate_alert(df_2, coll_2)
print ("Generating alert and saving in the database\n")
time.sleep(1)
count += 1
except KeyError:
pass
return
|
# © 2019 ForgeFlow S.L.
# © 2019 Serpent Consulting Services Pvt. Ltd.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class StockWarehouse(models.Model):
_inherit = "stock.warehouse"
def _default_operating_un... | def _check_location(self):
for rec in self:
if (
rec.warehouse_id.operating_unit_id
and rec.warehouse_id
and rec.location_id
and rec.warehouse_id.operating_unit_id
!= rec.location_id.operating_unit_id
):
... | UserError(
_(
"Configuration Error. The Operating Unit of the "
"Warehouse and the Location must be the same. "
)
)
|
REEZE: ('Freeze Restrictions', 'mdi:cancel'),
TYPE_FREEZE_PROTECTION: ('Freeze Protection', 'mdi:weather-snowy'),
TYPE_HOT_DAYS: ('Extra Water on Hot Days', 'mdi:thermometer-lines'),
TYPE_HOURLY: ('Hourly Restrictions', 'mdi:cancel'),
TYPE_MONTH: ('Month Restrictions', 'mdi:cancel'),
TYPE_RAINDELAY:... | ering.stop_all()
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
@_verify_domain_control
async def stop_program(call):
"""Stop a program."""
aw | ait rainmachine.client.programs.stop(call.data[CONF_PROGRAM_ID])
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
@_verify_domain_control
async def stop_zone(call):
"""Stop a zone."""
await rainmachine.client.zones.stop(call.data[CONF_ZONE_ID])
async_dispatcher_send(hass, ZONE_... |
import unittest
import os
import os.path
import json
# The folder holding the test data
data_path = os.path.dirname(__file__)
# Set the temporal config for testing
os.environ['TIMEVIS_CONFIG'] = os.path.join(data_path, 'config.py')
import timevis
class TestExp | eriment(unittest.TestCase):
def setUp(self):
self.app = timevis.app.test_client()
self.url = '/api/v2/experiment'
def test_post(self):
name = os.path.join(data_path, 'post_exp.json')
with open(name) as file:
obj = json.load(file)
resp = self.app.post(self... |
def test_get(self):
resp = self.app.get(self.url)
self.assertIsNotNone(resp.data)
def test_put(self):
name = os.path.join(data_path, 'put_exp.json')
with open(name) as file:
obj = json.load(file)
resp = self.app.put(self.url, data=json.dumps(obj),
... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Sun 21. Feb 22:22:07 2016
# by: The Resource Compiler for PyQt (Qt v4.8 | .5)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00 | \x00\x02\xf9\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x24\x00\x00\x00\x24\x08\x06\x00\x00\x00\xe1\x00\x98\x98\
\x00\x00\x00\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\
\xa7\x93\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\
\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00... |
path': inputPath})
hasharray = json.dumps(hasharray)
msg = '{"sign":{"meta":"sign message", "data":%s}}' % (hasharray)
dbb_client = self.plugin.get_client(self)
if not dbb_client.is_paired():
raise Exception("Could no... | TYPE_ADDRESS
info = tx.output_info.get(address)
if info is not None:
index, xpubs, m = info
changePath = self.get_derivation() + "/%d/%d" % index
changePubkey = self.derive_pubkey(index[0], index[1])
... | dbb_signatures = []
steps = math.ceil(1.0 * len(hasharray) / self.maxInputs)
for step in range(int(steps)):
hashes = hasharray[step * self.maxInputs : (step + 1) * self.maxInputs]
msg = '{"sign": {"meta":"%s", "data":%s, "checkpub":%s} }' % ... |
__author__ = 'dimitris'
import os
# Flask Configuration
basedir = os.path.abspath( | os.path.dirname(__file__))
SECRET_KEY = 'knaskndfknasdfiaosifoaignaosdnfoasodfnaodgnas'
PREFERRED_URL_SCHEME = 'https'
#SqlAlchemy Configuration
DB_NAME = 'puzzles.db'
SQLALCHEMY_DATABASE_URI = 'sqlite | :///' + os.path.join(basedir, DB_NAME)
#Cache Configuration
CACHE_TYPE = 'simple' |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from setuptools import setup
from glob import glob
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python ::... | up(
name="goatools",
version=__version__,
author='Haibao Tang',
author_email='tanghaibao@gmail.com',
packages=['goatools'],
scripts=glob('scripts/*.py'),
license='BSD',
classifiers=classifiers,
url='http://github.com/tanghaibao/goatools',
description="Python scripts | to find enrichment of GO terms",
long_description=open("README.rst").read(),
install_requires=['fisher', 'xlsxwriter', 'statsmodels']
)
|
from StringIO import StringIO
import textwrap
import importer
d | ef test_import_csv():
current = StringIO(textwrap.dedent('''\
status,qty,type,transaction_date,posting_date,description,amount
A,,,2016/11/02,,This is a test,$4.53
'''))
new = StringIO(textwrap.dedent('''\
"Trans Date", "Summary", "Amount"
5/2/2007, R... | is a test , $4.53
5/2/2007, Regal Theaters, $15.99
'''))
mapping = {
'Trans Date': 'transaction_date',
'Summary': 'description',
'Amount': 'amount'
}
importer.save_csv(current, new, mapping, '%m/%d/%Y')
lines = current.getvalue().splitlines()
asse... |
ge(self, cr, uid, ids, name, args, context=None):
result = dict.fromkeys(ids, False)
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = tools.image_get_resized_images(obj.image, avoid_resize_medium=True)
return result
def _set_image(self, cr, uid, id, name, ... | pricelist_ids = plobj.name_search(
cr, uid, pricelist, operator='=', context=context, limit=1)
pricelist = pricelist_ids[0][0] if pricelist_ids else pricelist
if isinstance(pricelist, (int, long)):
products = self.browse(cr, uid, ids, context=co... | icelist, context=context)
price = plobj._price_get_multi(cr,uid, pl, qtys, context=context)
for id in ids:
res[id] = price.get(id, 0.0)
for id in ids:
res.setdefault(id, 0.0)
return res
def get_history_price(self, cr, uid, product_tmpl... |
#!/usr/bin/env python
import sys
from weather import Weather
def main(args):
weather = Weather()
| location = weather.lookup_by_location(args[1])
condition = location.forecast()[0]
if condition:
return condition['text'] + ' with high of ' + condition['high'] + ' and low of ' + condition['low']
else:
return "City not found. It's probably raining m | eatballs. Please try again."
if __name__ == '__main__':
main(sys.argv) |
# -*- coding: utf-8 -*-
# This file is | part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.http import HttpResponseRedirect
from shuup import configuration
def toggle_all_seeing(req... | all_seeing_key = "is_all_seeing:%d" % request.user.pk
is_all_seeing = not configuration.get(None, all_seeing_key, False)
configuration.set(None, all_seeing_key, is_all_seeing)
return HttpResponseRedirect(return_url)
|
rom Catalog.Schema import DBSchema
from Query.Operators.TableScan import TableScan
from Query.Operators.Select import Select
from Query.Operators.Project import Project
from Query.Operators.Union import Union
from Query.Operators.Join import Join
from Query.Operators.GroupBy import GroupBy
from Query.... | return iter(self.root)
# Plan and statistics information.
# Returns a description for the entire query plan, based on the
# description of each individual operator.
def explain(self):
if self.root:
planDesc = []
indent = ' ' * 2
for (depth, operator) in self.flatten():
planDes... |
return '\n'.join(planDesc)
# Returns the cost of this query plan. Each operator should determine
# its own local cost added to the cost of its children.
def cost(self):
return self.root.cost()
# Plan I/O, e.g., for query shipping.
def pack(self):
raise NotImplementedError
def unpack(sel... |
import streamcorpus as sc
import cuttsum.events
import cuttsum.corpora
from cuttsum.trecdata import SCChunkResource
from cuttsum.pipeline import ArticlesResource, DedupedArticlesResource
import os
import pandas as pd
from datetime import datetime
from collections import defaultdict
import matplotlib.pylab as plt
plt.st... | nfltr,
| })
df = pd.DataFrame(coverage)
df_u = df.mean()
df_u["event"] = "mean"
print pd.concat([df, df_u.to_frame().T]).set_index("event")
exit()
with open("article_count.tex", "w") as f:
f.write(df_sum.to_latex())
import os
if not os.path.exists("plots"):
os.makedirs("plots")
import cuttsum.judgements
ndf = cut... |
from flask import session
from appconfig import *
class UserModel:
def __init__(self):
from models import Tag
from models import Post
from models import User
self.Tag = Tag.Tag
self.Post = Post.Post
self.User = User.User
def login(self, email, password):
... | alse
def register(self, email, password, nick, role, id = None):
from models import db
if id:
u = self.User.query.filter_by(Id=id).first()
u.Email = email
u.Role = role
u.set_password(password)
u.Nick = nick
subject = "You a... | is created"
db.session.commit()
body = "<p>Hello "+nick+", </p> <p>Your login details for "+URL+" :</p> <p>Username: "+email+" <br />Password: "+password+"</p>"
self.send_email(subject, email, body, nick)
return u.Id
def list(self):
users = self.User.query.all()
... |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... | erator.mul,
}
class MathCaptcha(object):
"""Simple match captcha object."""
| operators = ('+', '-', '*')
operators_display = {
'+': '<i class="fa fa-plus"></i>',
'-': '<i class="fa fa-minus"></i>',
'*': '<i class="fa fa-times"></i>',
}
interval = (1, 10)
def __init__(self, question=None, timestamp=None):
if question is None:
self.qu... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this fi | le
# to you 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 ... | r the specific language governing permissions and
# limitations under the License.
#
# Tests for Help
from nose.tools import assert_true, assert_equal
from desktop.lib.django_test_util import make_logged_in_client
def test_about():
c = make_logged_in_client(username="test", is_superuser=True)
# Test default out... |
import os
from flask import Flask, request, g
from flask_sqlalchemy import SQLAlchemy
from .decorators import json
db = SQLAlchemy()
def create_app(config_name):
""" Create the usual Flask application instance."""
app = Flask(__name__)
# Apply configuration
cfg = os.path.join(os.getcwd(), 'config', ... | u.import_data(request.json)
db.session.add(u)
| db.session.commit()
return {
'message': 'Your account has been successfuly created'
}, 201, {'Location': u.get_url()}
@app.route('/auth/login')
@auth.login_required
@json
def login_user():
return {'token': g.user.generate_auth_token()}
return app
|
from com.googlecode.fascinator.api.indexer import SearchRequest
f | rom com.googlecode.fascinator.common.solr import SolrResult
from com.googlecode.fascinator.spring import ApplicationContextProvider
from java.io import ByteArrayInputStream, ByteArrayOutputStream
class MaintenanceData:
def __init__(self):
| pass
def __activate__(self, context):
self.velocityContext = context
self.response = self.velocityContext["response"]
self.maintenanceModeService = ApplicationContextProvider.getApplicationContext().getBean("maintenanceModeService")
if self.maintenanceModeService.isMaintanceMode()... |
#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# 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 ... | TORS "AS I | S"
# 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 CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DA... |
# Generated by Django 2.0.1 on 2018-01-21 14:23
from django.db import migrations, mod | els
class Migration(migrations.Migration):
dependencies = [
('test_app', '0016_add_fil | epath'),
]
operations = [
migrations.AddField(
model_name='secondobject',
name='floating',
field=models.FloatField(default=0.0),
),
]
|
a default; values that are commented out
# serve to show the default.
import sys
import os
# 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 it absolute, like s... | the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, | sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep war... |
from django.conf.urls import patterns, url
from .views import PhotoListView
urlpatterns = patterns('' | ,
url(r'^(?P<slug>[\w-]+)/$', PhotoListView.as_view(), name='image' | ),
) |
response")
if deployment_settings.has_module("req"):
div_res.append(menu_box(T("Requests"), "req", "req"))
if deployment_settings.has_module("project"):
div_res.append(menu_box(T("Activities"), "project", "activity"))
#div_additional = DIV(A(DIV(T("Mobile Assess."),
# ... | T("to ac | cess the system")))))
if self_registration:
# Provide a Registration box on front page
request.args = ["register"]
auth.messages.submit_button = T("Register")
register_form = auth()
register_div = DIV(H3(T("Register")),
... |
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
from datetime import datetime
class StockScheduleWizard(models.TransientModel):
_name = "stock.schedule.wizard"
scheduled_date = fields.Datetime('Scheduled shipping date')
@api.multi
def action_button_schedule(self)... | id = cron_id[0]
if self.scheduled_date > cron_id.eta:
| cron_id.unlink()
picking.sale_id.scheduled_date = self.scheduled_date
picking.not_sync = True
picking._process_picking_scheduled_time()
|
#Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope tha... | else: # Scroll "in" if negative
scroll_event(z_move=-1, n=abs(depth))
class PyMouseEvent(PyMouseEventMeta):
def run(self):
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
... | uartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp),
self.handler,
... |
# Copyright (C)
#
# Author :
from GIC.Channels.GenericChannel import *
class ChannelTest (GenericChannel):
# mandatory fields to work on LibreGeoSocial search engine
MANDATORY_FIELDS = ["latitude", "longitude", "radius", "category"]
CATEGORIES = [{"id" : "0", "name" : "all", "desc" : "All supported ... | "
Fill self.options with the received dicti | onary
regarding mandatory and optional fields of your channel
"""
return True, ""
def process (self):
"""
Make the search and return the nodes
"""
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dataset', '0009_remove_selection_model'),
]
operations = [
migrations.AlterField(
model_name='dataset',
... | name= | 'name',
field=models.CharField(default=b'', max_length=150),
),
]
|
# 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) AutoRe | st Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
VERSION = "1.0.0b3"
|
import copy
import glob
import fnmatch
import os
import logging
import yaml
log = logging.getLogger("subiquitycore.netplan")
def _sanitize_inteface_config(iface_config):
for ap, ap_config in iface_config.get('access-points', {}).items():
if 'password' in ap_config:
ap_config['password'] = '<R... | else:
del config[match_key]
return config
return {}
def load_from_root(self, root):
for path in configs_in_root(root):
try:
fp = open(path)
except OSError:
log.exception("o... | with fp:
self.parse_netplan_config(fp.read())
class _PhysicalDevice:
def __init__(self, name, config):
match = config.get('match')
if match is None:
self.match_name = name
self.match_mac = None
self.match_driver = None
else:
... |
warning:: I doubt SPOINTs/EPOINTs work correctly
.. warning:: xref not fully implemented (assumes cid=0)
.. todo:: node_set stil does work on the all the nodes in the big
kdtree loop, which is very inefficient
.. todo:: remove_collapsed_elements is not supported
.. todo:: avoid_collapse... | . I'd rather break that
# check in order to support nodes_set.
#
# It's also possible that it's here, so you only consider nodes that
# are associated...
# there is some set of points that are used on the elements | that
# will be considered.
#
# Presumably this is enough to capture all the node ids and NOT
# spoints, but I doubt it...
spoint_epoint_nid_set = set([])
for eid, element in sorted(iteritems(model.elements)):
spoint_epoint_nid_set.update(element.node_ids)
... |
#
# THIS FILE WAS AUTOGENERATED BY makeSip6.py
# Do not edit this file manually. All changes will be lost.
#
"""
# TOP2049 Open Source programming suite
#
# Microchip PIC24f08kl201 SIP6
#
# Copyright (c) 2014 Pavel Stemberk <stemberk@gmail.com>
#
# This program is free software; you can redistribute it and/... | morySize = 0x800000
logicalFlashConfigurationMemorySize = 0x800000
hasEEPROM = False
def __init__(self):
Chip_Microchip16_common.__init__(self,
chipPackage = "DIP10",
chipPinVCC = 9,
chipPinsVPP = 10,
chipPinGND = 8,
signature=b"\x06\x4b",
# flashPageSize (in number of 24bit words)
flash | PageSize=0x15FE // 2 + 2,
# flashPageSize=0x40,
flashPages=1,
# eepromPageSize (in 16bit words)
eepromPageSize=0,
eepromPages=0,
# all 7 words uses lowest byte only
fuseBytes=2 * 9
)
self.configWordAddr = 0xF80000
# self.osccalBackupAddr = self.userIDLocationAddr + self.userIDLocationSize
fu... |
#!/usr/bin/env python
'''
Created on 18 gru 2014
@author: ghalajko
'''
from lvstop.screen import Screen
from lvstop import loop
if __name__ == '__main__':
with Screen() as scr:
| try:
scr.main_loop(loop)
except KeyboardInterrupt:
pass
except:
| raise |
#!/usr/bin/env python3
# Questo file visualizza la chiave "lists" redis
#
# Prima verifica che ci sia la chiave nel form
# Serve per la parte di gestione html in python
import cgi
import cgitb
# Abilita gli errori al server web/http
cgitb.enable()
# Le mie librerie mjl (Json, Files), mhl (Html), flt (T w/ Redis)
im... | er>","</h1>")
#print ("<hr/>","<b | r/>")
# Eventuale help/annotazione
#print ("Non ho rinominato i campi e non sono stato a riordinare le voci.<br/>")
form=cgi.FieldStorage()
if FormName not in form:
print ("<h2>ERRORE: Non e` stata passata la chiave Redis</h2>")
else:
RedisKey = cgi.escape(form[FormName].value)
RedisKeyStart = cgi.escape(form["VS... |
re.sub('sn2.fits', 'fits', string.split(img, '/')[-1]))
elif _typemag == 'ph':
agnkey.agnsqldef.updatevalue(_datatable, 'magtype', 3,
re.sub('sn2.fits', 'fits', string... | ):
if 'ZP' + filters1[_filter].upper | () == ww[0:3] and float(
string.split(dicti[_filter][img][ww])[1]) < 99:
Z1 = float(string.split(dicti[_filter][img][ww])[1])
C1 = float(string.split(dicti[_filter][img][ww])[2])
break
... |
"""
Model to hold edx-video-pipeline configurations.
"""
from __future__ import absolute_import
from config_models.models import ConfigurationModel
from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opaque_keys.edx.django.models impor... | xt=_('Oauth client name of video pipeline service.')
)
api_url = models.URLField(
verbose_name=_('Internal API URL'),
help_text=_('edx-video-pipeline API URL.')
)
service_user | name = models.CharField(
max_length=100,
default='veda_service_user',
null=False,
blank=False,
help_text=_('Username created for Video Pipeline Integration, e.g. veda_service_user.')
)
def get_service_user(self):
# NOTE: We load the user model here to avoid issue... |
"""
Django settings for SimpleMooc project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... | TEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'd | jango.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'SimpleMooc.urls'
WSGI_A... |
"""
This module is used to generate graphs that show the interaction between authors either through multiple edges or
through edge weights. There is an edge from one author to another if the former sent a message to the latter. These
graphs depict thread-wise interaction of the authors for the entire mailing list and t... | e=node[2].strip(), color="#ffffff", style='bold', sender=from_addr)
node_file.close()
print("Nodes added.")
# Add edges into NetworkX graph only if they are not a part of a thread that has only a single author
with open("graph_edges.csv", "r") as edge_file:
for pair in e... | edge = pair.split(';')
edge[0] = int(edge[0])
edge[1] = int(edge[1])
if edge[0] not in lone_author_threads and edge[1] not in lone_author_threads:
if edge[0] in msgs_before_time and edge[1] in msgs_before_time:
discuss... |
#! | /usr/bin/python
# encoding: utf-8
import sys
from gist import create_workflow, | set_github_token
from workflow import Workflow, web
from workflow.background import run_in_background, is_running
def main(wf):
arg = wf.args[0]
if len(arg) > 0:
token = wf.args[0]
set_github_token(wf, token)
if __name__ == '__main__':
wf = create_workflow()
sys.exit(wf.run(main))
|
"""scons.Node.Alias
Alias nodes.
This creates a hash of global Aliases (dummy targets).
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the So... | """The contents of an alias is the concatenation
of the content signatures of all its sources."""
childsigs = [n.get_csig() for n in self.children()]
return ''.join(childsigs)
def sconsign(self):
"""An Alias is not recorded in .sconsign files"""
pass
#
#
... | ur_csig = self.get_csig()
try:
return cur_csig != prev_ni.csig
except AttributeError:
return 1
def build(self):
"""A "builder" for aliases."""
pass
def convert(self):
try: del self.builder
except AttributeError: pass
self.reset_ex... |
def f(x):
| """
Returns
-------
object
| """
return 42 |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
clean_html,
int_or_none,
js_to_json,
parse_iso8601,
)
class NetzkinoIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?netzkino\.de/\#!/(?P<category>[^/]+)/(?P<id>[^/]+)'
_TEST = {
'u... | rmat_id': key,
'ext': 'mp4',
'url': tpl.replace('{}', film_fn) + suffix[key],
} for key, tpl in templates.items()]
self._sort_formats(formats)
comments = [{
' | timestamp': parse_iso8601(c.get('date'), delimiter=' '),
'id': c['id'],
'author': c['name'],
'html': c['content'],
'parent': 'root' if c.get('parent', 0) == 0 else c['parent'],
} for c in info.get('comments', [])]
return {
'id': video_id,
'formats': formats,
'comments': comments,
'title': i... |
"""Auto-generated file, do not edit by hand. BL metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BL = PhoneMetadata(id='BL', country_code=590, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:590|(?:69|80)\\d|976)\\d{6}', possibl... | 590(?:2[7-9]|5[12]|87)\\d{4}', example_number='590271234', possible_length=(9,)),
mobile=PhoneNumberDesc(national_number_pattern='69(?:0\\d\\d|1(?:2[2-9]|3[0-5]))\\d{4}', example_number='690001234', possible_length=(9,)),
toll_free=PhoneNumberDe | sc(national_number_pattern='80[0-5]\\d{6}', example_number='800012345', possible_length=(9,)),
voip=PhoneNumberDesc(national_number_pattern='976[01]\\d{5}', example_number='976012345', possible_length=(9,)),
national_prefix='0',
national_prefix_for_parsing='0',
mobile_number_portable_region=True)
|
mock_create_router,
mock_delete_router):
scenario = network.NeutronNetworks()
subnets_per_network = 1
subnet_cidr_start = "default_cidr"
net = {
"network": {
"id": "network-id"
}
}
... | as_calls(
[mock.call({"network": {"id": "fake-id"}},
{"allocation_pools": []})] * ports_per_network)
mock_update_port.assert_has_calls(
| [mock.call(mock_create_port.return_value, port_update_args)
] * ports_per_network)
@mock.patch(NEUTRON_NETWORKS + "._generate_random_name")
@mock.patch(NEUTRON_NETWORKS + "._delete_port")
@mock.patch(NEUTRON_NETWORKS + "._create_port")
@mock.patch(NEUTRON_NETWORKS + "._create_network")
... |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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... |
:type: Chassis100Reset
"""
self._chassis_reset = chassis_reset
| def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.... |
############################### | ################################################
# This file is part of openWNS (open Wireless Network Simulator)
# _____________________________________________________________________________
#
# Copyright (C) 2004-2007
# Chair of Communication Networks (ComNets)
# Kopernikusstr. 16, D-52074 Aachen, Germany
# phone: ... | _______________________________________________________________
#
# openWNS is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License version 2 as published by the
# Free Software Foundation;
#
# openWNS is distributed in the hope that it will be useful, but W... |
tRaises(AttributeError):
Sequence('ACGT').observed_chars = {'a', 'b', 'c'}
def test_eq_and_ne(self):
seq_a = Sequence("A")
seq_b = Sequence("B")
self.assertTrue(seq_a == seq_a)
self.assertTrue(Sequence("a") == Sequence("a"))
self.assertTrue(Sequence("a", metadat... | ld be None and not initialized to a "missing"
# representation
self.assertIsNone(seq1._metadata)
self.assertIsNone(seq1._positional_metadata)
self.assertIsNone(seq2._metadata)
self.assertIsNone(seq2._positional_metadata)
def test_getitem_gives_new_sequence(self):
seq... | s_positional_metadata(self):
s = "Sequence string !1@2#3?.,"
length = len(s)
seq = Sequence(s, metadata={'id': 'id', 'description': 'dsc'},
positional_metadata={'quality': np.arange(length)})
eseq = Sequence("S", {'id': 'id', 'description': 'dsc'},
... |
olor=True, bitmapdpi=100,
antialias=True, quality=85, backcolor='#ffffff00',
pdfdpi=150, svgtextastext=False):
"""Initialise export class. Parameters are:
doc: document to write
filename: output | filename
pagenumber: pagenumber to export or list of pages for some formats
color: use color | or try to use monochrome
bitmapdpi: assume this dpi value when writing images
antialias: antialias text and lines when writing bitmaps
quality: compression factor for bitmaps
backcolor: background color default for bitmaps (default transparent).
pdfdpi: dpi for pdf and eps files... |
_code=None, layerType=None, limit=100,
offset=0, url_user=None, scenario_id=None, squid=None, **params):
"""GET request. Individual layer, count, or list.
"""
# Layer type:
# 0 - Anything
# 1 - Environmental layer
# 2 - ? (Not implemented yet)
... | te_code=date_code, after_time=after_time,
before_time=before_time, epsg=epsg_code, env_type_id=env_type_id)
return lyr_atoms
# ................................
def _list_layers(self, user_id, after_time=None, before_time=None,
epsg_code=None, limit=100, offset=0, squid... | layers matching the specified criteria
Args:
user_id: The user to list layers for. Note that this may not be
the same user that is logged into the system
after_time: List layers modified after this time (Modified Julian
Day)
b... |
from unittest import skipIf
from django.conf import settings
def skipIfDefaultUser(test_func):
"""
Skip a test if a default user model is in use.
"""
return skipIf(settings.AUTH_USER_MODEL == "auth.User", "Default user model in use")(
test_func
)
def skipIfCustomUser(test_func):
"""... | _MODEL != "auth.User", "Custom user model in use")(
te | st_func
)
|
""" Tests for OAuth Dispatch python API module. """
import unittest
from django.conf import settings
from django.http import HttpRequest
from django.test import TestCase
from oauth2_provider.models import AccessToken
from common.djangoapps.student.tests.factories import UserFactory
OAUTH_PROVIDER_ENABLED = setting... | serFactory()
self.client = self.adapter.create_public_client(
name='public app',
user=self.user,
redirect_uri=DUMMY_REDIRECT_URL,
client_id='public-client-id',
)
def _assert_stored_token(self, stored_tok | en_value, expected_token_user, expected_client):
stored_access_token = AccessToken.objects.get(token=stored_token_value)
assert stored_access_token.user.id == expected_token_user.id
assert stored_access_token.application.client_id == expected_client.client_id
assert stored_access_token.a... |
# encoding: utf8
from __future__ import unicode_literals
from ..symbols import *
TAG_MAP = {
# Explanation of Unidic tags:
# https://www.gavo.t.u-tokyo.ac.jp/~mine/japanese/nlp+slp/UNIDIC_manual.pdf
# Universal Dependencies Mapping:
# http://universaldependencies.org/ja/overview/morphology.html
#... | ,*":{POS: NOUN},
"接尾辞,名詞的,副詞可能,*":{POS: NOUN}, # -後, -過ぎ
"代名詞,*,*,*":{POS: PRON},
"動詞,一般,*,*":{POS: VERB},
"動詞,非自立可能,*,*":{POS: VERB}, # XXX VERB if alone, AUX otherwise
"動詞,非自立可能,*,*,AUX":{POS: AUX},
"動詞,非自立可能,*,*,VERB":{POS: VERB},
"副詞,*,*,*":{POS: ADV},
"補助記号,AA,一般,*":{POS: SYM}, #... | "補助記号,一般,*,*":{POS: SYM},
"補助記号,括弧開,*,*":{POS: PUNCT}, # open bracket
"補助記号,括弧閉,*,*":{POS: PUNCT}, # close bracket
"補助記号,句点,*,*":{POS: PUNCT}, # period or other EOS marker
"補助記号,読点,*,*":{POS: PUNCT}, # comma
"名詞,固有名詞,一般,*":{POS: PROPN}, # general proper noun
"名詞,固有名詞,人名,一般":{POS: PROPN}, # per... |
from | unittest import TestCase
from pyrake.c | ontrib.spidermiddleware.urllength import UrlLengthMiddleware
from pyrake.http import Response, Request
from pyrake.spider import Spider
class TestUrlLengthMiddleware(TestCase):
def test_process_spider_output(self):
res = Response('http://pyraketest.org')
short_url_req = Request('http://pyraketes... |
#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | , either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the Priority Group Model."""
__authors__ = [
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from google.appengi | ne.ext import db
from django.utils.translation import ugettext
from soc.models import linkable
class PriorityGroup(linkable.Linkable):
"""The PriorityGroup model.
"""
#: the priority of this group, 0 being lower than 1
priority = db.IntegerProperty(required=False, default=0)
#: the human readable name o... |
# -*- coding: utf-8 -*-
#
# metasci documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 7 22:29:49 2010.
#
# 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... | tion
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# | non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclud... |
import json
import shakedown
import dcos
from dcos import marathon
from enum import Enum
from tests.command import (
cassandra_api_url,
spin,
WAIT_TIME_IN_SECONDS
)
class PlanState(Enum):
ERROR = "ERROR"
WAITING = "WAITING"
PENDING = "PENDING"
IN_PROGRESS = "IN_PROGRESS"
COMPLETE = "C... | nt"""
return marathon.Client(get_marathon_uri())
def strip_meta(app):
app.pop('fetch' | )
app.pop('version')
app.pop('versionInfo')
return app
|
# Author: Martin Oehler <oehler@knopper.net> 2013
# License: GPL V2
from django.forms import ModelForm
from django.forms import Form
from django.forms import ModelChoiceField
from django.forms.widgets import RadioSelect
from django.forms.widgets import CheckboxSelectMultiple
from django.forms.widgets import TextInput... | ss Meta:
model = vm
class clientForm(ModelForm):
pxelinuxconfiguration = ModelChoiceField(queryset=pxelinuxcfg.objects.all())
class Meta:
model = client
class clientGroupForm(ModelForm):
class Meta:
model = clientG | roup
class pxelinuxcfgForm(ModelForm):
class Meta:
model = pxelinuxcfg
widgets = {
'configuration': Textarea(attrs={'cols': 80, 'rows': 40}),
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.