prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# Copyright 2015 Adam Greenstein <adamgreenstein@comcast.net>
#
# Switcharoo Cartographer 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 versio... | ents.on_not_adding_to_queue(url)
def _get(self):
return self.queue.popleft()
def _is_unique(self, entry):
# TODO Logic here to determine if new url found
if entry not in self.queue:
return Access(self.eve | nts).is_unique_entry(entry)
else:
return False |
class A:
def <weak_w | arning descr="Function name should be lowercase">fooBar</weak_warning>(self): pass
class B(A | ):
def fooBar(self): pass |
# Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class AP... | raise TweepError('No parameter value found for path variable: %s' % name)
del self.parameters[name]
self.pa | th = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if len(self.parameters):
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
# Query the cache if one is available
... |
return dict_strip_unicode_keys(qs_filters)
def apply_sorting(self, obj_list, options=None):
"""
Given a dictionary of options, apply some ORM-level sorting to the
provided ``QuerySet``.
Looks for the ``sort_by`` key and handles either ascending (just the
... | (mismatched type).")
def obj_create(self, bundle, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_create``.
"""
bundle.obj = self._meta.object_class()
for key, value in kwargs.items():
setattr(bundle.obj, key, value)
... | ate(bundle)
bundle.obj.save()
# Now pick up the M2M bits.
m2m_bundle = self.hydrate_m2m(bundle)
self.save_m2m(m2m_bundle)
return bundle
def obj_update(self, bundle, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_update``.
... |
from django.urls import r | e_path
from systextil.views import apoio_index
from systextil.views.table import (
deposito,
colecao,
estagio,
periodo_confeccao,
unidade,
)
urlpatterns = [
re_path(r'^colecao/$', colecao.view, name='colecao'),
re_path(r'^deposito/$', deposito.deposito, name='deposito'),
re_p | ath(r'^estagio/$', estagio.view, name='estagio'),
re_path(r'^periodo_confeccao/$', periodo_confeccao.view, name='periodo_confeccao'),
re_path(r'^unidade/$', unidade.view, name='unidade'),
]
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produce | d at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free ... | License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesse... |
import numpy as np
import pandas as pd
from bokeh import mpl
ts = pd.Series(np.random.randn | (1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot | (legend=False)
mpl.to_bokeh(name="dataframe")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-04 22:45
from __future__ import unicode_literals
from django.d | b import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('domain_api', '0009_remove_topleveldomain_slug'),
]
operations = [
migrations.AddField(
model_name='topleveldomain',
name='slug',
field=models.CharField(max_length=100, null=True),
),
]
|
'''
Created on | Nov 21, 2016
@author: julimatt
'' | '
from django import forms
|
from distuti | ls.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("_nbt", ["_nbt.pyx"])]
import numpy
setup(
name = 'NBT library (Cython implementation)',
cmdclass | = {'build_ext': build_ext},
ext_modules = ext_modules,
include_dirs = numpy.get_include()
)
|
s ``True`` if ``lhs`` is a file name or file object in the project store."""
return (lhs in self._sourcefiles or
lhs in self._targetfiles or
lhs in self._transfiles or
lhs in self._files or
lhs in self._files.values())
# METHODS #
def appe... | t in self._files:
rai | se FileNotInProjectError(fname)
if not ftype:
# Guess file type (source/trans/target)
for ft, prefix in self.TYPE_INFO['f_prefix'].items():
if fname.startswith(prefix):
ftype = ft
break
self.TYPE_INFO['lists'][ftype].remove... |
from myhdl import *
from str_builder import StrBuilder
import os
import sys
class GenWrapperFile(object):
'''|
| This class is used to generate a python wrapper of a verilog design
|________'''
def __init__(self):
self.module_name = ''
self.interface = [] # keeps the order of the d... | nterface to the verilog ip core #\n'
s += '#---------------------------------------------#\n'
str_name = self.module_name i | f py_name == None else py_name
s += str_name + '_wrp.verilog_code = \\' + '\n'
if self.parameters != []:
s += '"""' + self.module_name + '#(\\n""" + \\' + '\n'
for p in self.parameters:
s += '""" .' + p["name"] + '($' + p["name"] + '),\\n""" + \\'... |
# encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('letter_ | to_editor', '0004_company_newspaper_webcache_wikipediapage'),
]
operations = [
migrations.AddField(
model_name='newspaper',
name='sister_newspapers',
field=models.ForeignKey(to='letter_to_editor.Newspaper', to_field='newspaper_name') | ,
preserve_default=True,
),
]
|
import itertools
import pickle
import numpy as np
from numpy.testing import assert_array_almost_equal
import pytest
from scipy.spatial.distance import cdist
from sklearn.neighbors import DistanceMetric
from sklearn.neighbors import BallTree
from sklearn.utils import check_random_state
from sklearn.utils._testing imp... | = check_random_state(0)
X = rng.rand(10, 3)
pyfunc = DistanceMetric.get_metric("pyfunc", func=custom_metric)
eucl = DistanceMetric.get_metric("euclidean")
asser | t_array_almost_equal(pyfunc.pairwise(X), eucl.pairwise(X) ** 2)
|
#!/usr/bin/python3
import exhibition
import inputdevice
import data
from levels import level1
import os
import pygame
import logging
log = logging.getLogger(__name__)
class Engine:
""" Main class responsible for running the game.
Controls game setup and runs the main loop.
Passes input to game... | exhibi | tion.optimize()
self.level = level1.Level1()
self.input = inputdevice.KeyboardInput()
def run(self):
""" Starts the game and runs the main game loop. """
self.main_loop()
pygame.quit()
def main_loop(self):
clock = pygame.time.Clock()
... |
# Copyright 2018 The Exoplanet ML 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 law or agreed t... | ())
# Weighted cross-entropy loss.
metrics["losses/weighted_cross_entropy"] = tf.metrics.mean(
batch_losses, weights=weights, name="cross_entropy_loss")
def _count_condition(name, labels_value, predicted_value):
"""Creates a counter for given values of predictions and labels."""
count ... | tf.equal(predicted_labels, predicted_value))
weighted_is_equal = weights * tf.cast(is_equal, tf.float32)
update_op = tf.assign_add(count, tf.reduce_sum(weighted_is_equal))
return count.read_value(), update_op
# Confusion matrix metrics.
num_labels = 2 if binary_classification else output_dim... |
weakened, flagged = set(), set()
infected = {(i,j) for i,a in enu | merate(open('22.in')) for j,b in enumerate(a.strip('\n')) if b=='#'}
s = len(open('22.in').readlines())/2
p = (s,s)
total = 0
d = (-1,0)
for _ in xrange(10**7):
if p in infected:
d = d[1], -1*d[0]
infected.remove(p)
flagged.ad | d(p)
elif p in weakened:
total += 1
weakened.remove(p)
infected.add(p)
elif p in flagged:
d = -1*d[0], -1*d[1]
flagged.remove(p)
else:
d = -1*d[1], d[0]
weakened.add(p)
p = p[0]+d[0], p[1]+d[1]
print total |
from oscarbluelight.ba | sket_utils import BluelightLineOfferConsumer a | s LineOfferConsumer
__all__ = [
"LineOfferConsumer",
]
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Feedback'
db.create_table('feedback_form_feedback', (
... | 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField'... | 'feedback_form.feedback': {
'Meta': {'object_name': 'Feedback'},
'body': ('django.db.models.fields.TextField', [], {}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... |
# -*- coding: utf-8 -*-
import re
from mobify.source import MobifySource
class OReillySource(MobifySource):
HEADER = u"""
<h1>{title}</h1>
<p><strong>{lead}</strong></p>
<p><small>{author} @ oreilly.com</small><br></p>
"""
@staticmethod
def is_my_url(url):
# https://www.ore | illy.com/ideas/the-evolution-of-devops
return 'oreilly.com/ideas/' in url
def get_inner_html(self):
article = self.xpath('//*[@itemprop="articleBody"]')
xpaths = [
'aside',
'div',
'figure[@class]',
]
# clean up the HTML
article = ... | return html
def get_html(self):
# add a title and a footer
return '\n'.join([
self.HEADER.format(title=self.get_title(), author=self.get_author(), lead=self.get_lead()).strip(),
self.get_inner_html()
]).strip()
def get_title(self):
# <meta property... |
generating PDIP models in X3D format
#
# from https://bitbucket.org/hyOzd/freecad-macros
# author hyOzd
# This is a
# Dimensions are from Microchips Packaging Specification document:
# DS00000049BY. Body drawing is the same as QFP generator#
## requirements
## cadquery FreeCAD plugin
## https://github.com/jmwright/... | ####################
import cq_belfuse # modules parameters
from cq_belfuse import *
import cq_keystone # modules parameters
from cq_keystone import *
import cq_bulgin # modules parameters
from cq_bulgin import *
import cq_schurter # modules parameters
from cq_schurter import *
import cq_tme # modul | es parameters
from cq_tme import *
import cq_littlefuse # modules parameters
from cq_littlefuse import *
different_models = [
cq_belfuse(),
cq_keystone(),
cq_bulgin(),
cq_schurter(),
cq_tme(),
cq_littlefuse(),
]
def make_3D_model(models_dir, model_class, modelID):
LIST_license = ["... |
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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
#... | lic_url,
CATALOGUE_BASE_URL=default_catalogue_backend()['URL'],
REGISTRATION_OPEN=settings.REGISTRATION_OPEN,
VERSION=get_version(),
SITE_NAME=site.name,
SITE_DOMAIN=site.domain,
GROUPS_APP = True if "geonode.contrib.groups" in settings.INSTALLED_APPS else False,
... | r_upload'),
GEOGIT_ENABLED = ogc_server_settings.GEOGIT_ENABLED,
TIME_ENABLED = getattr(settings, 'UPLOADER', dict()).get('OPTIONS', dict()).get('TIME_ENABLED', False),
DEBUG_STATIC = getattr(settings, "DEBUG_STATIC", False),
MF_PRINT_ENABLED = ogc_server_settings.MAPFISH_PRINT_ENABLED,
... |
#
# Copyright (C) 2008 The Android Open Source Project
#
# 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 la... | nto the
# command line because we are going to wrap the command into
# a pipe and git won't know coloring should activate.
#
for cn in cmd[1:]:
if not cn.startswith('-'):
break
if cn in _CAN_COLOR:
class ColorCmd(Coloring):
def __init__(self, c | onfig, cmd):
Coloring.__init__(self, config, cmd)
if ColorCmd(self.manifest.manifestProject.config, cn).is_on:
cmd.insert(cmd.index(cn) + 1, '--color')
mirror = self.manifest.IsMirror
out = ForallColoring(self.manifest.manifestProject.config)
out.redirect(sys.stdout)
rc =... |
ePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
self.widget.setSizePolicy(sizePolicy)
self.widget.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.widget.setObjectName("widget")
... | tVerticalStretch(0)
sizePolicy.setHeightForWidth(self.screenshotPixelYLineEdit.sizePolicy().hasHeightForWidth())
self.screenshotPixelYLineEdit.setSizePolicy(sizePolicy)
self.screenshotPixelYLineEdit.setObjectName("screenshotPixelYLineEdit")
self.formLayout.setWidget(1, QtGui.QFormLayout.... | e, self.screenshotPixelYLineEdit)
self.screenshotFilenameLabel = QtGui.QLabel(self.screenshotgroup)
self.screenshotFilenameLabel.setObjectName("screenshotFilenameLabel")
self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.screenshotFilenameLabel)
self.screenshotFilenameLineEdi... |
# -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from lxml import etree
def participa... | nt = etree.SubElement(element, "narrative")
if org.long_name:
narrative_element.text = org.long_name
elif org.name:
narrative_element.text = org.name
partnership_elements.append(element)
r | eturn partnership_elements
|
- retry_limit (int, optional):
Automatic retry count. Default: 0
- engine_version (str, optional):
Engine version to be used. If none is
specified, the account's default engine version would be set.
{"stable"... | Range is from -2 (very low) to 2 (very high). Default: 0
- retry_limit (i | nt, optional):
Automatic retry count. Default: 0
- engine_version (str, optional):
Engine version to be used. If none is
specified, the account's default engine version would be set.
{"stable", "experimental"}
... |
"""
API views for badges
"""
from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser
from opaque_keys import InvalidKeyError
from opaque_keys.edx.django.models import CourseKeyField
from opaque_keys.edx.keys import CourseKey
from rest_framework import generics
from r... | ing component for a particular badge class to filter by
(requires slug to have been specified, or this will be ignored.) If slug is provided and this is not,
assumes | the issuing_component should be empty.
* course_id (optional): Returns assertions that were awarded as part of a particular course. If slug is
provided, and this field is not specified, assumes that the target badge has an empty course_id field.
'*' may be used to get all badges with the spe... |
"""Imports for Python API.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from | tensorflow.python.platform.resource_loader import get_data_files_path
from t | ensorflow.python.platform.resource_loader import get_path_to_datafile
from tensorflow.python.platform.resource_loader import get_root_dir_with_all_resources
from tensorflow.python.platform.resource_loader import load_resource
from tensorflow.python.platform.resource_loader import readahead_file_path |
import sst
import sst.actions
# tests for simulate_keys
sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.go_to('/')
sst.actions.assert_title('The Page Title')
sst.actions.write_textfield('text_1', 'Foobar..')
sst.actions.simulate_keys('text_1', 'BACK_SPACE')
sst.actions.simulate_ke... | ommon/keys.py):
#
# 'NULL'
# 'CANCEL'
# 'HELP'
# 'BACK_SPACE'
# 'TAB'
# 'CLEAR'
# 'RETURN'
# 'ENTER'
# 'SHIFT'
# 'LEFT_SHIFT'
# 'CONTROL'
# 'LEFT_CONTROL'
# 'ALT'
# 'LEFT_ALT'
# 'PAUSE'
# 'ESCAPE'
# 'SPACE'
# 'PAGE_UP'
# 'PAGE_DOWN'
# 'END'
# 'HOME'
# 'LEFT'
# 'ARROW_LEFT'
# 'UP'
# 'ARROW_UP'
#... | NUMPAD3'
# 'NUMPAD4'
# 'NUMPAD5'
# 'NUMPAD6'
# 'NUMPAD7'
# 'NUMPAD8'
# 'NUMPAD9'
# 'MULTIPLY'
# 'ADD'
# 'SEPARATOR'
# 'SUBTRACT'
# 'DECIMAL'
# 'DIVIDE'
# 'F1'
# 'F2'
# 'F3'
# 'F4'
# 'F5'
# 'F6'
# 'F7'
# 'F8'
# 'F9'
# 'F10'
# 'F11'
# 'F12'
# 'META'
# 'COMMAND'
|
# D | O NOT EDIT THIS FILE!
#
# Python module CosTradingDynamic generated by omniidl
import omniORB
omniORB.updateModule("CosTradingDynam | ic")
# ** 1. Stub files contributing to this module
import CosTradingDynamic_idl
# ** 2. Sub-modules
# ** 3. End
|
# -*- coding: utf- | 8 -*-
__author__ = 'massimo'
import unittest
class UtilTestFunctions(unittest.TestCase):
def test_verify_url(self):
self.assertTrue(True)
if __name__ == "__main__":
UtilTestFunctions.main | ()
|
from __future__ import unicode_literals
from django.db import models
from wagtail.core.models import Site
class SystemString(models.Model):
DEFAULT_GROUP = 'general'
identifier = models.CharField(max_length=1024)
string = models.CharField(max_length=1024, blank=True, null=True)
group = models.CharFi... | els.DateTimeField(null=True, blank=True)
| modified = models.BooleanField(default=False)
class Meta:
unique_together = ['identifier', 'site', 'group']
def __unicode__(self):
return unicode(self.identifier)
|
"""
Siren protocol adapter. See `SIREN specification <https://github.com/kevinswiber/siren>`_.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from ripozo.adapters import AdapterBase
from ripozo.utilities import t... | _endpoint_funct(options.get('endpoint_func'))
actn = dict(name=endpoint, title=titlize_endpoint(endpoint),
method=meth, href=route, fields=fields)
actions.append(actn)
| return actions
def generate_fields_for_endpoint_funct(self, endpoint_func):
"""
Returns the action's fields attribute in a SIREN
appropriate format.
:param apimethod endpoint_func:
:return: A dictionary of action fields
:rtype: dict
"""
return_fiel... |
from PyQt4 import QtCore
from PyQt4 import QtGui
from Action import Speech
from UI.ActionPushButton import ActionPushButton
class BaseStudy(QtGui.QWidget):
def __init__(self):
super(BaseStudy, self).__init__()
self._actionQueue = None
self._nao = None
self._widgets = None
s... | layoutSpeech.addSpacing(3)
widget = QtGui.QWidget(self._grpSpeech)
layout = QtGui.QHBoxLayout(widget)
layout.setMargin(0)
for item in self._speechs:
if item is None:
layoutSpeech.addWidget(widget)
| widget = QtGui.QWidget(self._grpSpeech)
layout = QtGui.QHBoxLayout(widget)
layout.setMargin(0)
else:
item.setParent(widget)
item.clicked.connect(self.on_runSpeech_clicked)
layout.addWidget(ite... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Function/method decorators that provide timeout and retry logic.
"""
import functools
import itertools
import sys
from devil.android import device_erro... | , **kwargs)
if pass_values:
kwargs['timeout'] = timeout
kwargs['retries'] = retries
@functools.wraps(f)
def impl():
return f(*args, **kwargs)
try:
if timeout_retry.CurrentTime | outThreadGroup():
# Don't wrap if there's already an outer timeout thread.
return impl()
else:
desc = '%s(%s)' % (f.__name__, ', '.join(itertools.chain(
(str(a) for a in args),
('%s=%s' % (k, str(v)) for k, v in kwargs.iteritems()))))
return timeout_retry.Ru... |
# -*- coding: utf-8 -*-
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/set... | ontrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, '... | nds.mysql',
# 'NAME': 'blog', # app's database name
# 'USER': 'root',
# 'PASSWORD': 'root',
# 'HOST': '127.0.0.1', # localhost or cloudhost
# 'PORT': '3306',
# },
# 'another_db':{
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'app2_database', # app2'... |
#!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjac... | dir*i]
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
highest = 0
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]:
... | _dir*i]
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
highest = 0
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]:
... |
#!/usr/bin/env python
import json
my_list = range(10)
my_list.append('whatever')
my_list.append('some thing')
my_dict = {
'ke | y1': 'val1',
'key2': 'val2',
'key3': 'val3'
}
my_dict['key4'] = my_list
my_dict['key5'] = False
print my_dict
print json.dumps(my_dict)
with o | pen("my_file.json", "w") as f:
json.dump(my_dict, f)
|
"""This submodule contains objects for handling different representations of models and model functions | .
:synopsis: This submodule contains objects for handling different representations of models and model functions.
.. moduleauthor:: Johannes | Gaessler <johannes.gaessler@student.kit.edu>
"""
from ._base import *
from .yaml_drepr import *
|
from pygfa.graph_element.parser import line, field_validator as fv
SERIALIZATION_ERROR_MESSAGGE = "Couldn't serialize object identified by: "
def _format_exception(identifier, exception):
return SERIALIZATION_ERROR_MESSAGGE + identifier \
+ "\n\t" + repr(exception)
def _remove_common_edge_fields | (edge_dict):
edge_dict.pop('eid')
edge_dict.pop('from_node')
edge_dict.pop('from_orn')
edge_dict.pop('to_node')
edge_dict.pop('to_orn')
edge_dict.pop('from_positio | ns')
edge_dict.pop('to_positions')
edge_dict.pop('alignment')
edge_dict.pop('distance')
edge_dict.pop('variance')
def _serialize_opt_fields(opt_fields):
fields = []
for key, opt_field in opt_fields.items():
if line.is_optfield(opt_field):
fields.append(str(opt_field))
re... |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateV | iew
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url( | r'^$', TemplateView.as_view(template_name='base.html'))
)
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | sert_element_shape
from tensorflow.contrib.data.python.ops.batching import batch_and_drop_remainder
from tensorflow.contrib.data.python.ops.batching import dense_to_sparse_batch
from tensorflow.contrib.data.python.ops.batching import map_and_batch
from tensorflow.contrib.data.python.ops.batching import padded_batch_and... | .ops.batching import unbatch
from tensorflow.contrib.data.python.ops.counter import Counter
from tensorflow.contrib.data.python.ops.enumerate_ops import enumerate_dataset
from tensorflow.contrib.data.python.ops.error_ops import ignore_errors
from tensorflow.contrib.data.python.ops.get_single_element import get_single_e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from telesto import plot
OFFSET = 1000 # REMEMBER TO CALCULATE MANUALLY!
def main():
path = sys.argv[1]
mean = plot.mean(
| plot.rows(path, plot.parse_middleware_line),
("waiting", "parsing", "database", "response")
)
dev = plot.standard_deviation(
plot.rows(path, plot.parse_middleware_line), mean
)
print "#",
for key in mean:
print key,
print
for key in mean:
print mean[key],... | rint 100.0 * mean[key] / sum(mean.itervalues()),
print
for key in mean:
print dev[key],
print
if __name__ == "__main__":
main()
|
def len2mask(len):
"""Convert a bit length to a dotted netmask (aka. CIDR to netmask)"""
mask | = ''
if not isinstance(len, int) or len < 0 or len > 32:
print "Illegal subnet length: %s (which is a %s)" % \
(str(len), type(len).__name__)
return None
for t in range(4):
if len > 7:
mask += '255.'
else:
dec = 255 - (2**(8 - len) - 1)
... | o bit length (aka. netmask to CIDR)"""
octets = [int(x) for x in subnet.split(".")]
count = 0
for octet in octets:
highest_bit = 128
while highest_bit > 0:
if octet >= highest_bit:
count = count + 1
octet = octet - highest_bit
high... |
# coding=utf-8
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "..")))
from db.MysqlUtil import initMysql, execute, select, batchInsert, disconnect
from common.JsonHelper import loadJsonConfig
from api.tushareApi import getSimpleHistoryData
from datetime import datetime, timedelta
f... | ode='{0}' and date='{1}'").format(
code, date, volume, high, low, open, close, amount)
execute(updateSql)
print code, date, updateSql
else:
insertSql = unicode(
"insert into s_stock(code,date,time... | e,lowPrice,openPrice,closePrice,amount) VALUES ('{0}','{1}',{2},{3},{4},{5},{6},{7},'{8}')").format(
code, date, int(time.mktime(time.strptime(date, '%Y-%m-%d'))), volume, high, low, open, close,
amount)
execute(insertSql)
print cod... |
from . | import *
offline_providers = {
'builtin': builtin.ProviderBuil | tin,
}
|
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permissio
"""
import logging
import sleekxmpp
from sleekxmpp.stanza import Message
from sleekxmpp.xmlstream.handler import Callback
from sleek... | gister_stanza_plugin(Message, stanza.Inactive)
register_stanza_plugin(Message, stanza.Paused)
def plugin_end(self):
s | elf.xmpp.remove_handler('Chat State')
def session_bind(self, jid):
self.xmpp.plugin['xep_0030'].add_feature(ChatState.namespace)
def _handle_chat_state(self, msg):
state = msg['chat_state']
log.debug("Chat State: %s, %s", state, msg['from'].jid)
self.xmpp.event('chatstate_%s' %... |
er
def put(self, item, block=True, timeout=None):
"""Process event."""
self._handler(item)
def _get_entity_from_soco_uid(hass, uid):
"""Return SonosEntity from SoCo uid."""
for entity in hass.data[DATA_SONOS].entities:
if uid == entity.unique_id:
return entity
retu... | ps)
subscribe(player.contentDirectory, self.update_content)
def update(self):
"""Retrieve latest state."""
if self._available and not self._receives_events:
try:
self.update_groups()
self.update_volume()
if self.is_coordinator:
... | oException:
pass
def update_media(self, event=None):
"""Update information about currently playing media."""
transport_info = self.soco.get_current_transport_info()
new_status = transport_info.get('current_transport_state')
# Ignore transiti |
"""
The latest version of this package is available at:
<http://github.com/jantman/webhook2lambda2sqs>
################################################################################
Copyright 2016 Jason Antman <jason@jasonantman.com> <http://www.jasonantman.com>
This file is part of webhook2lambda2sqs, also kno... | 2lambda2sqs 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with webhook2lambda2sqs. If not, see <http://www.gnu.org/licenses/>.
The Copyright and Authors attributions contained herein may not be removed or
otherwise altered... |
import os
CA | CHE_PORT = 8080
HTTP_PORT = 8000
HTTPS_PORT = 4430
DEFAULT_MAX_AGE = 3600
DEFAULT_LOG_PATH = os.path.dirname(__file__)
DEFAULT_LOG_FILE = os.path.join(DEFAULT_LOG_PATH, 'default-hendrix.lo | g')
|
# SET THE FOLLOWING EITHER BEFORE RUNNING THIS FILE OR BELOW, BEFORE INITIALIZING
# PRAW!
# set variables for interacting with reddit.
# my_user_agent = ""
# my_username = ""
# my_password = ""
# reddit_post_id = -1
# import praw - install: pip install praw
# Praw doc: https://praw.readthedocs.org/en/latest/index... | r( created_from_map ) + " (map); " + str( created_from_obj ) + " (obj); " + str( created_dt | ) )
summary_string = "\nPRAW testing complete!\n"
# generate summary string
# set stop time.
my_summary_helper.set_stop_time()
# generate summary string.
summary_string += my_summary_helper.create_summary_string( item_prefix_IN = "==> " )
print( summary_string ) |
"""
Fiber-based fixed point location in the Lorenz system
f(v)[0] = s*(v[1]-v[0])
f(v)[1] = r*v[0] - v[1] - v[0]*v[2]
f(v)[2] = v[0]*v[1] - b*v[2]
Reference:
http://www.emba.uvm.edu/~jxyang/teaching/Math266notes13.pdf
https://en.wikipedia.org/wiki/Lorenz_system
"""
import numpy as np
import matplotlib.pyp... | t
fiber_kwargs["v"] = U[:,[fc]]
| # ax.text(U[0,fc],U[1,fc],U[2,fc], str(fc))
# Run in one direction
solution = sv.fiber_solver(**fiber_kwargs)
V1 = np.concatenate(solution["Fiber trace"].points, axis=1)[:N,:]
z = solution["Fiber trace"].z_initial
# Run in other direction (negate initial tangent)
... |
OTHER DEALINGS IN THE
# SOFTWARE.
# =============================================================================
# DOCS
# =============================================================================
"""Synthetic light curve generator.
"""
# =======================================================================... | id=id,
ds_name=ds_name,
desc | ription=description,
bands=bands,
metadata=metadata,
data=data,
)
def create_normal(
mu=0.0, sigma=1.0, mu_err=0.0, sigma_err=1.0, seed=None, **kwargs
):
"""Generate a data with magnitudes that follows a Gaussian
distribution. Also their errors are gaussian.
Parameters
... |
# | Say hello to Django | |
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
b... | )
# '0b11111010'
################################################ | ####################
# 4. Cryptography
####################################################################
import random
import string
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
# Generate a ra... |
#! /usr/bin/env python3
import math, sys
import shtns
impor | t numpy as np
class shtnsfiledata:
#
# Adopted from https://bitbucket.org/nschaeff/shtns/src/master/examples/shallow_water.py
#
def __init__(
self,
rsphere = 1.0
):
self.rsphere = rsphere
def setup(self, file_info, anti_aliasing=False):
import s | htns
import numpy as np
if file_info['modes_m_max'] != file_info['modes_m_max']:
raise Exception("Only num_lon == num_lat supported")
ntrunc = file_info['modes_n_max']
self._shtns = shtns.sht(ntrunc, ntrunc, 1, shtns.sht_orthonormal+shtns.SHT_NO_CS_PHASE)
nlons = (... |
# -*- coding: utf-8 -*-
import inspect
import random
import numpy as np
from django.contrib import messages
from django.views.generic import RedirectView
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from django.contrib.auth.mixins import UserPassesTestMixin
class RunAct... | 1]
mod = inspect.getmodule(frm[0])
modname = mod.__name__ if mod else frm[1]
messages.error(self.request,
"ERROR WHILE {}: [{}] {}".format(
| action['str'], modname, str(msg)))
def get_redirect_url(self, *args, **kwargs):
if kwargs['action'] not in self.ACTIONS:
raise Http404("Action not Found")
if self.ACTIONS[kwargs['action']]["type"] == 'object':
action_object = self.get_ct_object(kw... |
# This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2014, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You s... | ict()
cjson_dict['atoms']['coords']['3d'] = self.ccdata.atomcoords[-1].flatten().tolist()
| cjson_dict['bonds'] = dict()
cjson_dict['bonds']['connections'] = dict()
cjson_dict['bonds']['connections']['index'] = []
if has_openbabel:
for bond in self.bond_connectivities:
cjson_dict['bonds']['connections']['index'].append(bond[0] + 1)
cjson_dict... |
steriors.sum(axis=1), np.ones(nobs))
viterbi_ll, stateseq = h.decode(obs)
assert_array_equal(stateseq, gaussidx)
def test_sample(self, n=1000):
h = hmm.GaussianHMM(self.n_components, self.covariance_type)
# Make sure the means are far apart so posteriors.argmax()
# picks th... | g/wiki/Hidden_Markov_model
- http://en.wikipedia.org/wiki/Viterbi_algorithm
"""
def setUp(self):
self.prng = np.random.RandomState(9)
self.n_components = 2 # ('Rainy', 'Sunny')
self.n_symbols = 3 # ('walk', 'shop', 'clean')
self.emissionprob = [[0.1, 0.4, 0.5], [0.6, 0.3,... | startprob=self.startprob,
transmat=self.transmat)
self.h.emissionprob_ = self.emissionprob
def test_wikipedia_viterbi_example(self):
# From http://en.wikipedia.org/wiki/Viterbi_algorithm:
# "This reveals that the observations ['walk', 'sh... |
f copy(self, name=None):
if not name:
name = self.name + "copy"
navigate_to(self, 'Details')
tb.select('Configuration', 'Copy this Role to a new Role')
new_role = Role(name=name)
fill(self.form, {'name_txt': new_role.name},
action=form_buttons.add)
... | appliance=None):
Navigatable.__init__(self, appliance=appliance)
self.name = name
self.description = description
self.parent_tenant = parent_tenant
self._default = _default
@property
def parent_tenant(self):
if self._default:
return None
if s... | enant):
if tenant is not None and isinstance(tenant, Project):
# If we try to
raise ValueError("Project cannot be a parent object.")
if isinstance(tenant, basestring):
# If parent tenant is passed as string,
# we assume that tenant name was passed instead ... |
"""
Signals for user profiles
"""
from django.conf import settings
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from discussions import tasks
from profiles.models import Profile
from roles.models import Role
from roles.roles import P... | ussionUser every time a profile is created/updated
"""
if not settings.FEATURES.get('OPEN_DISCUSSIONS_USER_SYNC', False):
return
transaction.on_commit(lambda | : tasks.sync_discussion_user.delay(instance.user_id))
@receiver(post_save, sender=Role, dispatch_uid="add_staff_as_moderator")
def add_staff_as_moderator(sender, instance, created, **kwargs): # pylint: disable=unused-argument
"""
Signal handler add user as moderator when his staff role on program is added
... |
ever" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If G... |
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only ... | or: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Cre... |
# 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/.
from django.core.exceptions import PermissionDenied
from mock import Mock, patch
from nose.tools import eq_, raises
fro... | st = Mock() |
request.user = UserProfileFactory.create(privacy_policy_accepted=True).user
eq_(self.view.dispatch(request), 'fakemixin')
def test_has_profile_and_not_accepted_privacy_policy(self):
"""
If the user has created a profile, and has not accepted privacy policy
redirect them to... |
import frappe
from frappe.utils import get_fullname
def execute():
for user_id in frappe.db.sql_list("""select distinct user_id from `tabEmployee`
where ifnull(user_id, '')!=''
group by user_id having count(name) > 1"""):
fullname = get_fullname(user_id)
employee = frappe.db.get_value("Employee", {"employe... | llname, "user_id": user_id})
if employee:
frappe.db.sql("""update `tabEmployee` set user_id=null
where user_id=%s and name!=%s""", (user_id, emplo | yee)) |
from django.apps import AppConfig
class VotesConfig(AppConfig):
| name = 'meinberlin.apps.votes' |
label = 'meinberlin_votes'
|
return "test_PoissonSolver failed! calc/theory field ratio at 0: {}".format(g.electric_field[1] / field[0])
assert np.allclose(g.electric_field, field), plots()
# def test_PoissonSolver_complex(debug=DEBUG):
# L = 1
# N = 32 * 2**5
# epsilon_0 = 1
# x, dx = np.linspace(0, L, N, retstep=True, end... | isclose(energy_fouri | er, energy_direct)
# field_correct = np.isclose(g.electric_field, anal_field(g.x)).all()
# potential_correct = np.isclose(g.potential, anal_potential(g.x)).all()
# assert field_correct and potential_correct and energy_correct, plots()
def test_PoissonSolver_energy_sine(_NG, ):
_L = 1
resolution_inc... |
# -*- coding: utf-8 -*-
"""
Tests for the WMS Service Type.
"""
import unittest
from httmock import with_httmock
import mocks.warper
from aggregator.models import Service
class TestWarper(unittest.TestCase):
@with_httmock(mocks.warper.resource_get)
def test_create_wms_service(self):
# create the ... | y0, None)
self.assertEqual(layer_no_bbox.bbox_x1, None)
self.assertEqual(layer_no_bbox.bbox_y1, None)
# test that if creating the service and is already exiting it is not being duplicated
# create the service
def create_duplicated_service():
duplicated_service = Ser | vice(
type='WARPER',
url='http://warper.example.com/warper/maps',
)
duplicated_service.save()
self.assertRaises(Exception, create_duplicated_service)
if __name__ == '__main__':
unittest.main()
|
class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
ret = []
for elem in asteroids:
if elem > 0:
| ret.append(elem)
else:
while ret:
if 0 < ret[-1] <= -elem:
temp = ret.pop()
if temp == -elem:
break
else:
if ret[-1] < 0:
... | |
# Copyright 2021 The TF-Coder 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 law or agreed to in... | uage governing permissions and
# limitations under the License.
# Lint as: python3
"""Serialization of objects relevant to TF-Coder.
This module will be used to send information from the public Colab notebook to
Google Analytics, in string form. Using BigQuery we can extract the strings that
were sent, and then parse... |
represent. The information we want to log includes:
* Input/output objects. Usually these are multidimensional lists, Tensors, or
SparseTensors, but in principle these can be anything that value search
supports (e.g., primitives, dtypes, tuples of Tensors etc.).
* Constants. Usually these are Python primi... |
ta
from django.db import models
from django.contrib.sites.models import Site
from django.core.validators import MinValueValidator
from clubdata.models import Club
def range_date_inclusive(start_date, end_date):
for n in range((end_date - start_date).days+1):
yield start_date + timedelta(n)
def num_days_in... | for z in range(num_days_in_month(start_date)):
d = start_date + timedelta(z)
if d.weekday() == y[1]:
found_count += 1
if found_count == y[0]:
| calcdays.append(z+1)
break
print(calcdays)
# Check if this month is included (not a skipped month per the repeat_each rule)
if r == 1:
if (xday in specificdays) or (xday in calcdays):
# Assuming the daystocalculate have been calculated (above... |
from django.core.checks.compatibility.django_1_10 import (
check_duplicate_middleware_settings,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
class CheckDuplicateMiddlwareSettingsTest(SimpleTestCase):
@override_settings(MIDDLEWARE=[], MIDDLEWARE_CLASSES=['django.mid... | sult[0].id, '1_10.W001')
@override_settings(MIDDLEWARE=None)
def test_middleware_not_defined(self):
result = check_duplicate | _middleware_settings(None)
self.assertEqual(len(result), 0)
|
from django | .core.management.base import BaseCommand
from migrate_dns.import_utils import do_import
class Command( | BaseCommand):
args = ''
def handle(self, *args, **options):
do_import()
|
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.binaries.binary_tool import BinaryToolBase
from pants.binaries.binary_util import (
BinaryToolFetcher,
Bi | naryToolUrlGenerator,
BinaryUtil,
HostPlatform,
)
from pants.option.scope import GLOBAL_SCOPE
from pants.testutil.test_base import TestBase
from pants.util.contextutil import temporary_dir
from pants.util.dirutil import safe_file_dump
class DefaultVersion(BinaryToolBase):
options_scope = "default-version-... | "
name = "default_version_test_tool"
default_version = "XXX"
class AnotherTool(BinaryToolBase):
options_scope = "another-tool"
name = "another_tool"
default_version = "0.0.1"
class ReplacingLegacyOptionsTool(BinaryToolBase):
# TODO: check scope?
options_scope = "replacing-legacy-options-... |
#! /usr/bin/env python3
with open('x.c', | 'w') as f:
print('int main(void) { return 0; }', file=f)
with open('y', 'w'):
| pass
|
._finish_pending_requests()
# In theory, we shouldn't have to do this because curl will
# call _set_timeout whenever the timeout changes. However,
# sometimes after _handle_timeout we will need to reschedule
# immediately even though nothing has changed from curl's
# perspectiv... | da line: _curl_header_callback(headers, line))
if request.streaming_callback:
curl.setopt(pycurl.WRITEFUNCTION, request.streaming_callback)
else:
curl.setopt(pycurl.WRITEFUNCTION, buffer.write)
curl.setopt(pycurl.FOLLOWLOCATION, request.follow_redirects)
curl.setopt(pycurl.MAXREDIRS, req... | CTTIMEOUT_MS, int(1000 * request.connect_timeout))
curl.setopt(pycurl.TIMEOUT_MS, int(1000 * request.request_timeout))
if request.user_agent:
curl.setopt(pycurl.USERAGENT, utf8(request.user_agent))
else:
curl.setopt(pycurl.USERAGENT, "Mozilla/5.0 (compatible; pycurl)")
if request.network... |
from canvas i | mport MappingCanvas
from viewport import MappingViewport
try:
from geojson_overlay import GeoJSONOverlay
except ImportError:
# No geojson
pass
# Tile managers
from mbtile_manager import MBTileManager
from http_tile_manager import HTTPTile | Manager
|
"""Ensures that account.identifier is unique.
Revision ID: ea2739ecd874
Revises: 5bd631a1b748
Create Date: 2017-09 | -29 09:16:09.436339
"""
# revision identifiers, used by Alembic.
revision = 'ea2739ecd874'
down_revision = '5bd631a1b748'
from alembic import op
import sqla | lchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint(None, 'account', ['identifier'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'account',... |
from model.flyweight import Flyweight
from model.static.database import database
class Service(Flyweight):
def __init__(self,service_id):
#prevents reinitializing
if "_inited" in self.__dict__:
return
self._inited = None
#prevents reinitial | izing
self.service_id = service_id
cursor = database.get_cursor(
"select * from staServices where serviceID={};".format(
self.service_id))
row = cursor.fetchone()
self.service_name = row["serviceName"]
self.description = row["description"]
| cursor.close()
|
import numpy as np
def test_prepare_abi_connectivity_maps():
from samri.fetch.local import prepare_abi_connectivity_maps
pre | pare_abi_connectivity_maps('Ventral_tegmental_area',
invert_lr_experiments=[
"127651139",
"127796728",
"127798146",
"127867804",
"156314762",
"160539283",
"160540751",
"165975096",
"166054222",
"171021829",
"175736945",
"2781783 | 82",
"292958638",
"301062306",
"304337288",
],
)
def test_prepare_feature_map():
from samri.fetch.local import prepare_feature_map
prepare_feature_map('/usr/share/ABI-connectivity-data/Ventral_tegmental_area-127651139/',
invert_lr=True,
save_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz',... |
#!/usr/bin/env python
#
# Copyright (c) 2016 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
# list of conditions and t... | self.assertIn("64", apks[i])
apkLength = apkLength + 1
if apks[i].endswith(".apk") and "arm" in apks[i]:
if comm.BIT == "64":
self.assertIn("64", apks[i])
| apkLength = apkLength + 1
self.assertEquals(apkLength, 2)
else:
for i in range(len(apks)):
if apks[i].endswith(".apk") and "shared" in apks[i]:
apkLength = apkLength + 1
appVersion = apks[i].split('-')[1]
sel... |
from nodetraq.tests import *
class Tes | tPoolsController(TestController):
def test_index(self):
response = self.app.get(url(controller= | 'pools', action='index'))
# Test response...
|
# this example shows how to append new calculated results to an already
# existing cmr file, illustrated for calculation of PBE energy on LDA density
import os
import cmr
# set True in order to use cmr in parallel jobs!
cmr.set_ase_parallel(enable=True)
from ase.structure import molecule
from ase.io import read, wri... | der(directory='.', ext='.cmr')
# read all compounds in the project with lcao
all = reader.find(name_value_list=[('mode', 'lcao')],
keyword_list=[project_id])
results = all.get('formula', formula)
print results['formula'], results['xc'], results['ase_potential_energy']
# colum... | ngth=0 aligns data in the table (-1 : data unaligned is default)
all.print_table(column_length=0,
columns=['formula', 'xc', 'h', 'ase_potential_energy', 'PBE'])
if rank == 0:
equal(results['PBE'], e + ediff, 1e-6)
if rank == 0:
for file in [formula + '.gpw', formula + '.db', cmrfile]:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-22 16:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def forwards_func(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'l... | elp_text=(
'For module and module-set typed questions, this is the Module that'
| ' Tasks that answer this question must be for.'
),
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name='is_type_of_answer_to',
to='guidedmodules.Module',
),
),
migrations.RunPython(forwards_f... |
# 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 may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.authentication import (
BasicAu... |
sr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Hou Shaohui
#
# Author: Hou Shaohui <houshao55@gmail.com>
# Maintainer: Hou Shaohui <houshao55@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of... | fg_press_dpixbuf = self.icon_group
select_index = self.get_index()
bg_image = bg_normal_dpixbuf.get_pixbuf()
fg_image = fg_normal_dpixbuf.get_pixbuf()
if widget.state == gtk.STATE_NORMAL:
if select_index == self.index:
select_status = BUTTON... | if select_index == self.index:
select_status = BUTTON_PRESS
else:
select_status = BUTTON_HOVER
elif widget.state == gtk.STATE_ACTIVE:
select_status = BUTTON_PRESS
if select_status == BUTTON_NORMAL:... |
from builtins import range
import sys
import unittest
import re
import os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from Exscript import Account
from Exscript.account import AccountPool
from Exscript.util.file import get_accounts_from_file
class AccountPoolTest(unittest.TestCase):
... | assertNotIn(account2, pool.unlocked_accounts)
pool.release_accounts('two')
self.assertIn(account1, | pool.unlocked_accounts)
self.assertIn(account2, pool.unlocked_accounts)
def suite():
return unittest.TestLoader().loadTestsFromTestCase(AccountPoolTest)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# lice | nse information.
#
# Code generated by Microsoft (R) A | utoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .linked_service import LinkedService
class SapHanaLinkedService(LinkedService):
"""SAP HANA Linked Service.
:param a... |
j = j + 2
# reformatting "{{Discussion|...}}"
elif string[j:j+13] == '{{Discussion|':
string = string[:j] + '\\fI' + string[j+13:]
nr = 1
j = j + 2
... | elif string[j:j+7] == '</table':
tab = j
while len(string) > j and string[j] != '>':
j = j + 1
| if string[j] == '>':
string = string[:tab] + string[j+1:]
j = tab - 1
tab = 0
else:
j = tab
tab ... |
#!/usr/bin/env python3
# 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... | p
from kfp import dsl
def random_num_op(low, high):
"""Generate a random number between low and | high."""
return dsl.ContainerOp(
name='Generate random number',
image='python:alpine3.6',
command=['sh', '-c'],
arguments=['python -c "import random; print(random.randint($0, $1))" | tee $2', str(low), str(high), '/tmp/output'],
file_outputs={'output': '/tmp/output'}
)
... |
import pandas as pd
from sklearn import model_selection
from sklearn.ensemble import RandomForestClassifier
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabet | es/pima-indians-diabetes.data"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
df = pd.read_csv(url, names=names)
array = df.values
X = array[:,0:8]
y = array[:,8]
seed = 21
num_trees = 100
max_features = 3
kfold = model_selection.KFold(n_splits=10, random_state=seed)
model = RandomF... | str(results.mean())) |
from resource_media_types import *
from ClientFile import ClientFile
from ClientFolder import ClientFolder
from queryResource import ClientQuery
class ResourcesTypeResolverUtil(object):
classes = {}
#classes[ClientAdhocDataView.__name__] = ResourceMediaType.ADHOC_DATA_VIEW_MIME
#classes[ClientAw... | ceMediaType.MONDRIAN_CONNECTION_MIME);
#put(ClientMondrianXmlaDefinition.class, ResourceMediaType.MONDRIAN_XMLA_DEFINITION_MIME);
#put(ClientOlapUnit.class, ResourceMediaType.OLAP_UNIT_MIME);
classes[ClientQuery.__name__] = TYPE_QUERY
#put(ClientReportUnit.class, ResourceMediaType.REPORT_UNIT_MIME);
... | N_MIME);
#put(ClientSemanticLayerDataSource.class, ResourceMediaType.SEMANTIC_LAYER_DATA_SOURCE_MIME);
#put(ClientVirtualDataSource.class, ResourceMediaType.VIRTUAL_DATA_SOURCE_MIME);
#put(ClientXmlaConnection.class, ResourceMediaType.XMLA_CONNECTION_MIME);
#put(ClientResourceLookup.class, ResourceMedia... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis ... | ond = 1
results = []
if condition:
for _ in range(max_trip_count):
third = first + second |
first = second
second = third
results.append(third)
if third > 100:
break
return (first, second, np.array(results).astype(np.float32))
self.assertReferenceChecks(
gc,
whi... |
# -*- coding: utf-8 -*-
import sys
def get_skeleton(N, strings):
skeletons = []
for i in range(N):
skeleton = [strings[i][0]]
skeleton += [strings[i][j] for j in range(1, len(strings[i])) if strings[i][j] != strings[i][j-1]]
skeletons.append(skeleton)
for i in range(1, N):
... | (abs(k - l) * | length[l] for l in length) for k in length)
return ans
def main():
T = int(input())
for i in range(1, T + 1):
print('Case #{}: {}'.format(i, solve()))
if __name__ == '__main__':
sys.exit(main())
|
nd #12121.
defers = []
pk_val = None
if self._deferred:
from django.db.models.query_utils import deferred_class_factory
factory = deferred_class_factory
for field in self._meta.fields:
if isinstance(self.__class__.__dict__.get(field.attname),
... | _data = True
def save_base(self, raw=False, cls=None, origin=None, force_insert=False,
force_update=False, using=None):
"""
| Does the heavy-lifting involved in saving. Subclasses shouldn't need to
override this method. It's separate from save() in order to hide the
need for overrides of save() to pass around internal-only parameters
('raw', 'cls', and 'origin').
"""
using = using or router.db_for_... |
tailData">')[1].split('</td>')[0]
# Pull out values from summary stuff
AppraisedSplit = lambda data: data.split('Appraised:</td><td class="ssDetailData" width="125px" align="right">')[1].split(' ')[0]
LandHSSplit = lambda data: data.split('Land HS:</td><td class="ssDetailData" width="125px" align="right">')[1]... | align="left" nowrap="true" class="ssDataColumn"></td><td align="right" nowrap="true" class="ssDataColumn">'
def parse_main_page(main_store, property, cyear='2010'):
propId,ownerId_sql = get_propId(property,cyear)
page_data = get_main_page(propId,cyear, ownerId_sql)
#page_data = open(" | page.txt").read()
addr = AddrSplit(page_data)
ownerName = NameSplit(page_data)
print "Owner Name:", ownerName
g = threading.Thread(target=get_pdf_listing, args=(propId,ownerId_sql,ownerName))
g.start()
THREADS.append(g)
ownerid = OwnerIdSplit(page_data)
print "Owner Id:", ownerid
#property = PropID(pa... |
from setuptools import set | up
from setuptools import find_packages
setup(name='Keras-layers',
version='0.0.1',
description='Collection of useful non-standard layers for keras',
author='Atanas Mirchev',
author_email='taimir93@gmail.com',
url='https://github.com/taimir/keras-layers',
license='MIT',
| packages=find_packages())
|
nb_epoch = 100
batch_size = 64
optimizer = 'adam'
hidden_units = 3000
nb_val_samples = 462 |
embedding_size = 10
dropout_percentage = 0.3 |
embedding_GRU_size = 100
maximum_line_length = 500
samples_per_epoch = 4127 * maximum_line_length
loss = 'categorical_crossentropy'
|
#!/usr/bin/env python
# Original code was created by Nadeem Douba as part of the Canari Framework
from collections import OrderedDict
from xml.etree.cElementTree import XML
from zipfile import ZipFile
def mtgx2json(graph):
zipfile = ZipFile(graph)
graphs = filter(lambda x: x.endswith('.graphml'), zipfile.n... | /'
'{http://maltego.paterva.com/xml/mtgx}Property'):
value = prop.find('{http://maltego.paterva.com/xml/mtgx}Value').text or ''
entity_prop = {prop.get('displayName'): value.strip()}
props['Data'].update(entity_prop)
record... | record.update(data)
link = {'Links': {}}
i_link = {'Incoming': links.get(node_id, {}).get('in_', 0)}
link['Links'].update(i_link)
o_link = {'Outgoing': links.get(node_id, {}).get('out', 0)}
link['Links'].update(o_link)
record.update(link)
... |
from io import StringIO
from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent
def test_filtered_value():
"""Test for filtered values."""
# Doesn't touch normal key/value pairs
assert filtered_value('normal', 'value') == 'value'
assert filtered_value('also_normal', 123) =... | r is 1234 5678-90123456')
== 'My number is [Filtered]'
)
def test_pprint_with_indent():
"""Test pprint_with_indent does indentation."""
out = StringIO()
data = {
12: 34,
'confirm_password': '12345qwerty',
'credentials': ['abc', 'def'],
'key' | : 'value',
'nested_dict': {'password': 'not_filtered'},
'password': '12345qwerty',
}
pprint_with_indent(data, out)
assert (
out.getvalue()
== '''\
{12: 34,
'confirm_password': [Filtered],
'credentials': [Filtered],
'key': 'value',
'nested_dict': {'pass... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2. | 0 (the "Li | cense");
# 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 W... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.