prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from htmldoc import * from chunk import * from module import * from js import * #? This global variable is used to specify where the javascript files are on the server. JavascriptDir = "./" #<_ view="internal">A Marker showing where the RPCs are installed</_> rpcim = Marker("js") rpcs=[""" <script language='JavaScri...
here """, rpcim,"// End RPC call installation.\n</script>\n"] #? The json module is defined jsonModule = Module("json",jsm,[("head",["<script language='JavaScript' src='%sjson2.js'>1;</script>\n<script language='JavaScript' src='%sjsonreq.js'>1;</script>\n" % (JavascriptDir,JavascriptDir
)] + rpcs) ]) class DefineRpc: def __init__(self,rpcname): self.name = rpcname def call(self,*jsargs): args = ",".join([str(x) for x in jsargs]) return "server.%s(%s)" % (self.name,args) def gen(self,doc): doc.AddModule(jsModule,LocationBoth) doc.AddModule(jsonModule,LocationBoth) ...
"""Test template specific functionality. Make sure tables expose their functionality to templates right. This generally about testing "out"-functionality of the tables, whether via templates or otherwise. Whether a test belongs here or, say, in ``test_basic``, is not always a clear-cut decision. """ from django.temp...
les.TextColumn() population = tables.NumberColumn(verbose_name="Population Size") c
urrency = tables.NumberColumn(visible=False, inaccessible=True) tld = tables.TextColumn(visible=False, verbose_name="Domain") calling_code = tables.NumberColumn(name="cc", verbose_name="Phone Ext.") countries = CountryTable( [{'name': 'Germany', 'capital': 'Berlin', 'population': 83, 'curre...
format(len(sets))) sys.stdout.write("\n") sets = list(sets) keys = list(range(len(sets))) # Generate paddings for asym. max_size = max(len(s) for s in sets) paddings = dict() if pad_for_asym: padding_sizes = sorted(list(set([max_size-len(s) for s in sets]))) for num_perm ...
(ground_truth_times, ground_truth_results, query_data[1], query_data[2]): rows.append((query_key, len(query_set), threshold, t, ",".join(str(k) for k in r))) df_groundtruth = pd.DataFrame.from_records(rows, columns=["query_key", "query_size", "...
redis: storage_config = { "type": "redis", "redis": { "host": args.redis_host, "port": args.redis_port, }, } rows = [] for threshold in level["thresholds"]: for num_part in level["num_parts"]: for num_perm i...
""" The Fibonacci numbers, which we are all familiar with, start like this: 0,1,1,2,3,5,8,13,21,34,... Where each new number in the sequence is the sum of the previous two. It turns out that by summing different Fibonacci numbers with each other, you can create every single positive integer. In fact, a much stronger...
lways be of the representation, so we remember that number and proceed recursively, and figure out the representation of 100 - 89 = 11. The largest Fibonacci number less than or equal to 11 is 8. We remember that number and proceed recursively
with 11 - 8 = 3. 3 is a Fibonacci number itself, so now we're done. The answer is 89 + 8 + 3. Write a program that finds the Zeckendorf representation of different numbers. What is the Zeckendorf representation of 315 ? Thanks to SwimmingPastaDevil for suggesting this problem in /r/dailyprogrammer_ideas! Do yo...
#-*- coding: utf-8 -*- import inspect from django import forms from django.conf import settings as globalsettings from django.contrib.admin.widgets import ForeignKeyRawIdWidget from django.contrib.admin.sites import site from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import revers...
introspector field_class = "dj
ango.db.models.fields.related.ForeignKey" args, kwargs = introspector(self) # That's our definition! return (field_class, args, kwargs)
# Copyright (C) 2012 Thomas "stacks" Birn (@stacksth) # # 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...
with this program. If not, see <http://www.gnu.org/licenses/>. from lib.cuckoo.common.abstracts import Signature class InstallsWinpcap(Signature): name = "sniffer_winpcap" description = "Installs WinPCAP" severity = 3 categories = ["sniffer"] authors = ["Thomas Birn", "nex"] minimum = "0.5" ...
tors = [ ".*\\\\packet\.dll$", ".*\\\\npf\.sys$", ".*\\\\wpcap\.dll$" ] for indicator in indicators: if self.check_file(pattern=indicator, regex=True): return True return False
parse import ( urlparse, urljoin, urlsplit, urlunsplit, parse_qs) from .packages.tldextract import tldextract log = logging.getLogger(__name__) MAX_FILE_MEMO = 20000 GOOD_PATHS = ['story', 'article', 'feature', 'featured', 'slides', 'slideshow', 'gallery', 'news', 'video', 'media', ...
Perform a regex check on an absolute url. First, perform a few basic checks like making sure the format of the url is right, (scheme, domain, tld). Second, make sure that the url isn't some static resource, check the file type. Then, search of a YYYY/MM/DD pattern in the url. News sites lo...
ators can be [\.-/_]. Years can be 2 or 4 digits, must have proper digits 1900-2099. Months and days can be ambiguous 2 digit numbers, one is even optional, some sites are liberal with their formatting also matches snippets of GET queries with keywords inside them. ex: asdf.php?topic_id=blahlbah We ...
import networkx as nx import numpy as np import pandas as pd def normalise(x): x = x[:]#deepcopy error x -= min(x) x /= max(x) return x def jgraph(posjac): ''' networkx graph object from posjac at timestep ''' posjac = 1 - normalise(np.log10(p
osjac).replace([np.inf,-np.inf],np.nan).dropna()) split = [i.split('->') for i in posjac.index] #graph G = nx.DiGraph() for e in range(len(split)): G.add_edge(split[e][0],split[e][1],weight=posjac[e]) G.remove_edges_from(G.selfloop_edges()) return G def getnx(self, ts ,save=...
ate_posjac() G = nx.DiGraph() posjac = self.posjac.loc[ts,:] split = [i.split('->') for i in posjac.index] for e in range(len(split)): G.add_edge(split[e][0],split[e][1],weight=posjac[e]) G.remove_edges_from(G.selfloop_edges()) if save: nx.write_weighted_edgelist(G...
except IOError, err: raise EasyBuildError("Failed to patch %s: %s", fn, err) self.log.debug("Contents of patched %s: %s" % (fn, open(fn, "r").read())) # patch default make.sys for wannier if LooseVersion(self.version) >= LooseVersion("5"): fn = os.path.join(self.cf...
bands_FS.x", "kvecs_FS.x"]) if LooseVersion(self.version) > LooseVersion("5"): bin
s.extend(["generate_vdW_kernel_table.x"]) else: bins.extend(["path_int.x"]) if 'pwcond' in self.cfg['buildopts'] or 'pwall' in self.cfg['buildopts'] or \ 'all' in self.cfg['buildopts']: bins.extend(["pwcond.x"]) if 'tddfpt' in self.cfg['buildopts'] or...
iew_data) def delete_save_search(request): """ Called via ajax to delete a table. Only called from the saved_search.html """ id = request.GET.get("id", None) if not id: return respondWithError("Saved search cannot be found."\ " Please refresh and try again", T...
fault'].lower() == "true": isDefault = True sortBy = None if 'sortDirection' in table and 'sortField' in table: sortBy = {'field':table['sortField'],'direction':table['sortDirection']}
response = save_data(userId, table['columns'], table['tableName'], tableId=table['id'], isDefaultOnDashboard=isDefault, sortBy=sortBy, dashboard=dashboard, clone=clone, row=table['row'], grid_col=table['col'], ...
# # 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 # ...
ons and limitations # under the License. from heat.api.aws import exception from heat.common import identifier from heat.c
ommon import wsgi from heat.rpc import client as rpc_client class SignalController(object): def __init__(self, options): self.options = options self.rpc_client = rpc_client.EngineClient() def update_waitcondition(self, req, body, arn): con = req.context identity = identifier.R...
import numpy, matplotlib, random, pylab, math def matrix_square_root(sigma) : eigen, vect = numpy.linalg.eig(sigma) dim = len(sigma) res = numpy.identity(dim) for i in range(0,dim) : res[i,i] = eigen[i]**0.5 return vect * res * vect.transpose() def chi2_level (alpha = 0.95) : N = 1...
) y.append ( -a ) x.append ( (random.random ()-0.5) * a*2 ) xs,ys = [],[] for a,b in zip (x,y) : ar = numpy.matrix( [ [a], [b] ] ).transpose() we = ar * root xs.append ( we [0,0] ) ys.append ( we [0,1] ) pylab.plot(xs,ys, 'bo') pylab.sh...
andom.random() * math.pi * 2 i = a * mat[0][0]**0.5 * math.cos(z) j = a * mat[0][0]**0.5 * math.sin(z) x.append ( i ) y.append ( j ) pylab.plot(x,y, 'ro') x = [ ] y = [ ] for i in range (0,200) : z = random.random() * math.pi * 2 i = a * math.cos(z) ...
""" De
mo of the errorbar function. """ import numpy as np import matplotlib.pyplot as plt # example data x = np.arange(0.1, 4, 0.5) y = np.exp(-x) plt.errorbar(x,
y, xerr=0.2, yerr=0.4) plt.show()
s="the q
uick brown fox jumped over the lazy dog" t = s.split(" ") for v in t: print(v) r = s.split("e") for v in r: print(v) x = s.split() for v in x: print(v) # 2-arg version of split not supported # y = s.split("
",7) # for v in y: # print v
from common_fixtures import * # NOQA def _clean_clusterhostmap_for_host(host): for cluster in host.clusters(): cluster.removehost(hostId=str(host.id)) def _resource_is_inactive(resource): return resource.state == 'inactive' def _resource_is_active(resource): return resource.state == 'active' ...
n( super_client, cluster, lambda x: len(x.hosts()) == 2, lambda x: 'Number of hosts in cluster is: ' + len(x.hosts())) # Remove 2nd host from cluster cluster = cluster.removehost(hostId=str(host2.id)) cluster = wait_for_condition( super_client, cluster, lambda x: le...
def test_host_purge(super_client, new_context): host1 = super_client.reload(new_context.host) _clean_clusterhostmap_for_host(host1) cluster = super_client.create_cluster( accountId=new_context.project.id, name='testcluster2', port=9000) cluster = wait_for_condition( super_client...
ntent'])) def backwards(self, orm): # Renaming column for 'Comment.parent_content' to match new field type. db.rename_column('canvas_comment', 'parent_content_id', 'parent_content') # Changing field 'Comment.parent_content' db.alter_column('canvas_comment', 'parent_content', self....
ve': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTime...
('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max...
# -*- coding: utf-8 -*- # Copyright 2015 Objectif Libre # # 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 ...
name='policy1', data='return 0', checksum='cf83e1357eefb8bdf1542850d66d8007d620e4050b5715d' 'c83f4a921d36ce9ce47d0d13c
5d85f2b0ff8318d2877eec' '2f63b931bd47417a81a538327af927da3e') return sample class ScriptCollection(wtypes.Base): """Type describing a list of scripts. """ scripts = [Script] """List of scripts.""" @classmethod def sample(cls): sample = Script.sa...
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import random import sys from couchdb import client from couchdb import ServerError class TempDatab...
mmit=False) def tearDown(self): if self.temp_dbs: for name in self.temp_dbs: try: self.server.delete(name) except ServerError as err: if err.args[0] == (500, ('error',
'eacces')): continue raise def temp_db(self): if self.temp_dbs is None: self.temp_dbs = {} # Find an unused database name while True: name = 'couchdb-python/%d' % random.randint(0, sys.maxsize) if name not in s...
#!/usr/bin/env python # Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Library for manipulating naclports packages in python. This library can be used to build tools for working with naclports p...
ut_path, new_foldern
ame)): return tmp_output_path = tempfile.mkdtemp(dir=OUT_DIR) try: archive = self.DownloadLocation() ext = os.path.splitext(archive)[1] if ext in ('.gz', '.tgz', '.bz2'): cmd = ['tar', 'xf', archive, '-C', tmp_output_path] elif ext in ('.zip',): cmd = ['unzip', '-q...
from ubuntutweak.janitor import JanitorCachePlugin class ChromeCachePlugin(JanitorCachePlugin): __title__ = _('Chrome Cache') __category__ = 'application'
root_path = '~/.cache/google-chrome/Default' class ChromiumCachePlugin(JanitorCachePlugin): __title__ = _('Chromium Cache') __category__ = 'application' root_path = '~/.cac
he/chromium/Default'
#!/usr/bin/env python # encoding: utf-8 import logging import math import time from django.utils import timezone import django from modularodm import Q from oauthlib.oauth2 import OAuth2Error from dateutil.relativedelta import relativedelta django.setup() from framework.celery_tasks import app as celery_app from sc...
- (time.time() - last_call)) except (ValueError, IOError): pass # Value/IOError indicates negative sleep time in Py 3.5/2
.7, respectively allowance = rate_limit[0] allowance -= 1 last_call = time.time() success = False try: success = Provider(record).refresh_oauth_key(force=True) except OAuth2Error as e: logger.error(e) ...
nalyze the performance # of a network. class Metrics(object): ## Calculate average throughput as: total_bytes_rcvd / duration. # # @param pkts_list An iterator object in the format [(timestamp, size),] # @param duration Time duration (in s) over which thruput is to be computed. Typicall...
## Return the end to end delay for each packet moving between a source and # destination node, and identified by a flow ID. The delay is computed as # the difference between sending t
ime of the packet at source node and # receiving time of the packet at the destination node. # @param send_pkts_list An iterator object in the format [(seq_num, timestamp)] # @param rcvd_pkts_list An iterator object in the format [(seq_num, timestamp)] # @return A list in the form [(seq_num, delay),...
# -*- coding: utf-8 -*- """ Pygments unit tests ~~~~~~~~~~~~~~~~~~ Usage:: python run.py [testfile ...] :copyright: Copyright 2006-2012 by the Pygments team, see AUTHOR
S. :license: BSD, see LICENSE for details. """ import sys, os if sys.version_info >= (3,): # copy test suite over to "build/lib" and convert it print ('Copying and converting sources to build/lib/test...') from distutils.util import copydir_run_2to3 testroot = os.path.dirname(__file__) newroot...
) # make nose believe that we run from the converted dir os.chdir(newroot) else: # only find tests in this directory os.chdir(os.path.dirname(__file__)) try: import nose except ImportError: print ('nose is required to run the Pygments test suite') sys.exit(1) try: # make sure the curr...
""" Caching instances via ``related_name`` -------------------------------------- ``cache_relation`` adds utility methods to
a model to obtain ``related_name`` instances via the cache. Usage ~~~~~ :: from django.db import models from django.contrib.auth.models import User class Foo(models.Model): user = models.OneToOneField(
User, primary_key=True, related_name='foo', ) name = models.CharField(max_length=20) cache_relation(User.foo) :: >>> user = User.objects.get(pk=1) >>> user.foo_cache # Cache miss - hits the database <Foo: > >>> user = User.objects.get(pk=1) >...
# -*- 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 field 'Product.date_added' db.add_column(u'clone_product', 'date...
related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'},...
efault': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField'...
# found at http://stackoverflow.com/questions/855759/python-try-else # The statements in the else block are executed if execution falls off # the bottom of the try, i.e. if there was no exception. try: operation_that_can_throw_ioerror() except IOError: handle_the_exception_somehow() else: # we don't wan...
he IOError if it's raised another_operation_that_can_throw_ioerror() final
ly: something_we_always_need_to_do() # The else lets you make sure: # # * another_operation_that_can_throw_ioerror() is only run if there's no exception, # * it's run before the finally block, and # * any IOErrors it raises aren't caught here
nd, * `Gamma` is the [gamma function]( https://en.wikipedia.org/wiki/Gamma_function), and, * `||y||**2` denotes the [squared Euclidean norm]( https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm) of `y`. The VectorStudentT distribution is a member of the [location-scale family]( https://en.wik...
loc: Floating-point `Tensor`. If this is set to `None`, no `loc` is applied. scale_identity_multiplier: floating point rank 0 `Tensor` representing a scaling done to the identity matrix. When `scale_identity_multiplier = scale_diag=scale_tril = None` then `scale += IdentityMatrix`. Other...
ded to `scale`. scale_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ..., k], which represents a k x k diagonal matrix. When `None` no diagonal term is added to `scale`. scale_tril: Floating-point `Tensor` representing the diagonal matrix. ...
od(ast.Mod): def prepare(self): pass def print_c(self): return '%' class C_LShift(ast.LShift): def prepare(self): pass def print_c(self): return '<<' class C_RShift(ast.RShift): def prepare(self): pass def print_c(self): return '>>' class C_BitOr(ast.BitOr)...
c.print_c() in classNames: asC += ';\n' asC += self.value.func.print_c() + '___init__(' asC += se
lf.target.print_c() asC += self.value.print_args() + ')' else: if self.value: asC += ' = ' + self.value.print_c() return asC class C_AugAssign(ast.AugAssign): def prepare(self): pass def print_c(self): asC = self.target.print_c() + ' ' asC += self.op.print_...
flags = h5py.h5p.CRT_ORDER_TRACKED | h5py.h5p.CRT_ORDER_INDEXED gcpl.set_link_creation_order(flags) name = self.name.encode("utf-8") gid = h5py.h5g.create(self._parent.id, name, gcpl=gcpl) self.group = h5py.Group(gid) def create_link(self, target, name): ...
f.group[name] return H5DataSet.create_from_h5obj(dset) else:
raise notfound def write_data(self, name, data, dtype=None): """ Writes the data to a Dataset contained in the group with the given name. Creates the Dataset if necessary. :param name: name of the Dataset object :param data: the data to write :param dtype: o...
M, OperandType.IMM_FULL : O_IMM, OperandType.IMM32 : O_IMM, OperandType.SEIMM8 : O_IMM, OperandType.IMM16_1 : O_IMM_1, OperandType.IMM8_1 : O_IMM_1, OperandType.IMM8_2 : O_IMM_2, OperandType.REG8 : O_REG, OperandType.REG16 : O_REG, OperandType.REG_FULL : O_REG, OperandType.REG32 : O_REG, OperandTy...
the internal structures diStorm uses for holding the instructions' information. Using this structure diStorm knows how to format an opcode when it reads it from the stream. An instruction information structure is found by its byte codes with a prefix of "II_". So for example ADD EAX, Imm32 instruction is II_00...
here might be optional fields, if there's a 3rd operand or a second/third mnemonic. optFields = "" # Default type of structure is InstInfo. type = "_InstInfo" # Make sure the instruction can be fully represented using the diStorm3 _DecodeInst structure. CheckOTCollisions(ii) # Add flags for flow control...
#!/usr/bin/env python3 import time import random import socket from flask import Flask, render_template, redirect, url_for, request, jsonify import config log = None # classes class Agent(): def __init__(self, ip, cw=True, node=None, state='initial'): self.ip = ip self.cw = cw self.state...
('/get/<agent_ip>') def get_status(agent_ip): """Get the list of agents in the current node.""" agent = app.agents[agent_ip] # aggiungere blocked return jsonify(agents=[app.agents[ip].state for ip in app.ring.get_node(agent.node).agents if ip != agent_ip], blocked=app.ring.bloc
ked(agent)) @app.route('/set/<agent_ip>', methods=['GET']) def set_status(agent_ip): global log turned = request.args.get('turned') == '1' state = request.args.get('state') stopped = request.args.get('stopped') == '1' # logging sss = '\n\n[Request] {} - ip: {}, turned: {}, state: {},...
# -*- coding: utf-8 -*- from django.contrib im
port admin from ionyweb.plugin_app.plugin_video.models import Plugin_Video admin.site.regist
er(Plugin_Video)
rom functools import wraps def requires_auth(endpoint_class): """ Enables Authorization logic for decorated functions. :param endpoint_class: the 'class' to which the decorated endpoint belongs to. Can be 'resource' (resource endpoint), 'item' (item endp...
ash: hash included with the request. :param headers: request headers. Suitable for hash computing. :param data: request data. Suitable for hash computing. :param allowed_roles: allowed user roles. :param resource: resource being requested. :param method: HTTP method being execute...
ant to change the response. """ abort(401, description='Please provide proper credentials') def authorized(self, allowed_roles, resource, method): """ Validates the the current request is allowed to pass through. :param allowed_roles: allowed roles for the current request, ...
# -*- coding: utf-8 -*- # from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import nose from nose.tools import * import numpy as np from sknano.structures import Graphene, PrimitiveCellGraphene, \ ConventionalCellGraphene, GraphenePrimitiveCell, GrapheneConv...
s = Graphene.from_primitive_cell(edge_length=5) assert_true(isinstance(s, PrimitiveCellGraphene)) assert_true(isinstance(s.unit_cell, GraphenePrimitiveCell)) if __name__ == '__main__': nose.runmodu
le()
# ============================================================ # modelparser.py # # (C) Tiago Almeida 2016 # # Still in early development stages. # # This module uses PLY (http://www.dabeaz.com/ply/ply.html) # and a set of grammar rules to parse a custom model # definition language. # =======================...
p[1]) def p_field_decl(p): """ field : ID COLON multiplicity datatype notnull SEMICOLON """ # return an object with the field data # p[0] = { 'name': p[1], 'type': p[4], 'mult': p[3], 'null': p[5] } def p_datatype(p): """ datatype...
E | ID """ p[0] = p[1] def p_field_multiplicity(p): """ multiplicity : STAR | empty """ if p[1] == '*': p[0] = MULT_ANY else: p[0] = MULT_SINGLE def p_field_notnull(p): """ notnull : EXCLAMATION | empty """ if p[1] == '!': ...
from django.db import models from django.contrib.auth.models import User from helper_functions import my_strftime # Create your models here. #This only contains metadata about this thread (i.e. just the subject for now) #It is used in a Many-to-Many relationship with User, with a through object that contains the has_...
e author of this message time_sent = models.DateTimeField(auto_now_add=True) text = models.TextField() def getDetail(self): """Returns dictionary object containing the info of this object""" return { 'author' : self.user.getInfo(), 'timestamp' : my_strftime(self.time_sent), ...
thread = models.ForeignKey(Thread) #Meta data for user's relation to thread has_been_read = models.BooleanField(default=False)
se... def testPermissionPutWithQuotedEmail(self): ret = self._put('/users/bob%40bobsworld.com/permissions/admin', data=dict(options=json.dumps(dict(products=["a"])))) self.assertStatusCode(ret, 201) self.assertEqual(ret.data, json.dumps(dict(new_data_version=1)), "Data: %s" % ret.data) ...
ecute().fetchall() self.assertEqual(len(r), 1) self.assertEqual(r[0], ('release_read_only', 'bob', {"products": ["a", "b"]}, 2)) def testPermissionsPostMissing(self): ret = self._post("/users/bill/permissions/rule", data=dict(options="", data_version=1)) self.assertStatusCode(ret, 4...
ret = self._post("/users/bill/permissions/admin") self.assertStatusCode(ret, 400) def testPermissionsPostWithoutPermission(self): ret = self._post("/users/bob/permissions/rule", username="shane", data=dict(data_version=1, options=json.dumps(dict(actions=["create"])))) self.assertStatusCode...
""" The file preprocesses the files/train.txt and files/test.txt files. I requires the dependency based embeddings by Levy et al.. Download them from his website and change the embeddingsPath variable in the script to point to the unzipped deps.words file. """ from __future__ import print_function import numpy as np ...
ainSentences, window_size, word2Idx, label2Idx, case2Idx
) dev_set = createMatrices(devSentences, window_size, word2Idx, label2Idx, case2Idx) test_set = createMatrices(testSentences, window_size, word2Idx, label2Idx, case2Idx) f = gzip.open(outputFilePath, 'wb') pkl.dump(train_set, f) pkl.dump(dev_set, f) pkl.dump(test_set, f) f.close() print("Data stored in pkl folder")...
import pytest from ..context import dnsimple, fixture_path from ..request_helper import RequestHelper, request from dnsimple.client import Client class TestClient(RequestHelper, object): def test_constructor_raises_errors_when_improperly_configured(self): with pytest.raises(dnsimple.credentials....
_sandbox_to_false(self): subject = Client(email = 'user@host.com', password = 'password') assert subject.request.sandbox is False
def test_constructor_enables_sandbox(self): subject = Client(sandbox = True, email = 'user@host.com', password = 'password') assert subject.request.sandbox is True def test_transfer_creates_domain_transfer(self, mocker, request): method = self.stub_request(mocker, request, method_name...
from storitell.tastypie.resources import ModelResource from storitell.stories.models import Story from storitell.stories.extra_methods import moderate_comment from storitell.ta
stypie.validation import Validation # Stories can be read through a REST-ful interface. It'd be nice # to be able to POST as well, but that requires validation I haven't # had time to code yet. Want to add it? Be my guest. class StoryResource(ModelResource): class Meta: queryset = Story.objects.all() resource_na...
ory' fields = ['maintext','pub_date','upvotes'] allowed_methods = ['get']
# 10.0 is the maximum version ('|10.0', '5.1', True), ('|10.0', '10.0', True), ('|10.0', '10.1', False), # 6.1 is the minimum version ('6.1|', '5.1', False), ('6.1|', '6.0', False),
('6.1|', '6.1', True), ('6.1|', '6.2', True), ('6.1|', '10.0', True), ('6.2|', '5.1', False), ('6.2|', '6.0', False), ('6.2|', '6.1', False), ('6.2|', '6.2', True), # must be 6.2 or 6.3 ...
, ('6.2|6.3', '6.2', True), ('6.2|6.3', '6.3', True), ('6.2|6.3', '10.0', False), # 10.0 is the minimum ('10.0|', '5.1', False), ('10.0|', '10.0', True)) for (req, mock, expected_return) in tests: m...
param object self: tthe object being initialised @param object manager: the manager object that @param str name: unique name for this object @param dict configuration: parameters from the configuration file @param dict callbacks: dictionary specifying functions to be run ...
ule state. @param OrderedDict dict: variable names and contents. """ if not isinstance(variableDict, (dict, OrderedDict)): self.log.error('Did not pass a dict o
r OrderedDict to ' 'setStatusVariables in {0}.'.format( self.__class__.__name__)) return self._statusVariables = variableDict def getState(self): """Return the state of the state machine implemented in this class. @ret...
if self.emittance_aim >= self.bucket_area: self.tb1.append("Chosen emittance too large for this bucket. Aborting!") raise RuntimeError("Chosen emittance too large for this bucket. Aborting!") self.tb1.append("Calculating 4-sigma bunch length for an emittance of " ...
.setObjectName("leVoltage")
# Label "Optional" self.lbOptional = QtWidgets.QLabel(mainWindow) self.lbOptional.setGeometry(QtCore.QRect(20, 230, 70, 17)) self.lbOptional.setObjectName("lbOptional") # Label "Emittance" with units self.leEmittance = QtWidgets.QLineEdit(mainWindow) self.leEmit...
= None self.sent_bytes = None self.request = None self.user_agent = None self.ssl_cipher = None self.ssl_protocol = None self.destination_group_arn = None self.trace_identifier = None self.domain_name = None self.chosen_cert_arn = None self.matched_rule_priority = None self.a...
ns a dfdatetime object from a timestamp. Args: parser_medi
ator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. time_structure (str): a timestamp string of the event. Returns: TimeElements: Time elements contain separate values for year, month, day of month, hours, minutes and seconds. ...
def extractStealtranslationHomeBlog(item): ''' Parser for 'stealtranslation.home.blog' '''
return Non
e
import utils import os
import shutil import sys def go( boost_root ): OUTPUT = "src/third_party/boost" if os.path.exists( OUTPUT ): shutil.rmtree( OUTPUT ) cmd = [ "bcp" , "--scan" , "--boost=%s" % boost_root ] src = utils.getAllSourceFiles() cmd += src cmd.append( OUTPUT ) if not os.path...
: os.makedirs( OUTPUT ) res = utils.execsys( cmd ) out = open( OUTPUT + "/bcp-out.txt" , 'w' ) out.write( res[0] ) out.close() out = open( OUTPUT + "/notes.txt" , 'w' ) out.write( "command: " + " ".join( cmd ) ) out.close() print( res[1] ) if __name__ == "__main__": ...
def save_model_as(X, columns, model, save_model, flatten): '''Model Saver WHAT: Saves a trained model so it can be loaded later for predictions by predictor(). ''' model_json = model.to_json() with open(save_model+".json", "w") as json_file: json_file.write(model_json) model.save...
+ save_model + " " + "have been saved.") temp = "" f = open(save_model+".x", "w+") # for a range of columns (two ints) if type(X) == list:
if len(X) == 2: if type(X[0]) == int: for i in range(X[0], X[1]): try: temp += columns[i] + " " except: pass # for multiple column index if type(X) == list: if len(X) > 2: ...
######## def install_and_import(package): import importlib try: importlib.import_module(package) except ImportError: try: import pip except ImportError: print "no pip" os.system('python get_pip.py') finally: import pip pip.main(['install', package]) finally: ...
arget_lang = None self.output_text= None self.cwd = os.getcwd() def is_moses_dir_valid(self, directory): is_valid = True
if directory == "": is_valid = False # Empty string elif not os.path.exists(directory): is_valid = False # Directory does not exist else: # Check if dir exists but does not contain moses installation is_valid = self._check_moses_installation(directory)...
''' Proxy for drivers. Copyright (c) 2009, 2013 Peter Parente Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR ...
@type value: object ''' self._push(self._driver.setProperty, (name, value)) def runAnd
Wait(self): ''' Called by the engine to start an event loop, process all commands in the queue at the start of the loop, and then exit the loop. ''' self._push(self._engine.endLoop, tuple()) self._driver.startLoop() def startLoop(self, useDriverLoop): ''' ...
exception.InstanceInvalidState: # Note(yufang521247): instance which has never been active # is not allowed to be soft_deleted. Thus we have to call # delete() to clean up the instance. self.compute_api.delete(context, instance) else: s...
raise exc.HTTPBadRequest(explanation=msg) try: instance = self.compute_api.get(ctxt, id, want_objects=True) req.cac
he_db_instance(instance) policy.enforce(ctxt, 'compute:update', instance) instance.update(update_dict) instance.save() except exception.NotFound: msg = _("Instance could not be found") raise exc.HTTPNotFound(explanation=msg) return self._view_...
""" This config file extends the test environment configuration so that we can run the lettuce acceptance tests. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=wildcard-import, unused-wildcard-import from .test import * f...
le import logging logging.basicConfig(filename=TEST_ROOT / "log" / "lms_acceptance.log", level=logging.ERROR) # set root logger level logging.getLogger().setLevel(logging.ERROR) import os from random import choice def seed(
): return os.getppid() # Silence noisy logs LOG_OVERRIDES = [ ('track.middleware', logging.CRITICAL), ('codejail.safe_exec', logging.ERROR), ('edx.courseware', logging.ERROR), ('audit', logging.ERROR), ('instructor_task.api_helper', logging.ERROR), ] for log_name, log_level in LOG_OVERRIDES: ...
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # All rights reserved. # #Redistribution and use in source and binary forms, with or without # #modification, are permitted provided that the following conditions are #met: # ...
OF SUCH DAMAGE. """ Implements controller for GridFTP option pages. """ from datafinder.gui.admin.datastore_configuration_wizard.gridftp impo
rt performance_option_controller from datafinder.gui.admin.datastore_configuration_wizard.gridftp import security_option_controller __version__ = "$Revision-Id:$"
# Helpers for pytest tests import subprocess import json import os def find_cppcheck_binary(): possible_locations = [ "./cppcheck", "./build/bin/cppcheck", r".\bin\cppcheck.exe", ] for location in possible_locations: if os.path.exists(location): break else: ...
p = subprocess.Popen(cmd) p.communicate() if p.returncode != 0: raise OSError("cppcheck returns error code: %d" % p.returncode) subprocess.Popen(["sync"]) def dump_remove(fpath): subprocess.Popen(["rm", "-f", fpath
+ ".dump"]) def convert_json_output(raw_json_strings): """Convert raw stdout/stderr cppcheck JSON output to python dict.""" json_output = {} for line in raw_json_strings: try: json_line = json.loads(line) # json_output[json_line['errorId']] = json_line json_ou...
from django.contrib import admin from .models import User from application.models import (Contact, Personal, Wife, Occupation, Children, Hod, Committee, UserCommittee, Legal) # Register your models here. class ContactInline(admin.StackedInline):
model = Contact class PersonalInline(admin.StackedInline): model = Personal class WifeInline(admin.StackedInline): model = Wife class OccupationInline(admin.StackedInline): model = Occupation class HodInline(admin.StackedInline): model = Hod class ChildrenInline(admin.StackedInline): mode...
sonalInline, WifeInline, OccupationInline, HodInline, ChildrenInline, UserCommitteeInline ] class LegalAdmin(admin.ModelAdmin): model = Legal admin.site.register(User, UserAdmin) admin.site.register(Legal, LegalAdmin) admin.site.site_header = 'Hebrew Order of David Admi...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2009 Gary Burton # Copyright (C) 2011 Tim G L Lyons # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published ...
ned keyword -- see po/update_po.py and po/genpot.sh #------------------------------------------------------------------------- # # Integer to String mappings for constants # #---------------------------
---------------------------------------------- gender = { Person.MALE : _("male"), Person.FEMALE : _("female"), Person.UNKNOWN : _("gender|unknown"), } def format_gender( type): return gender.get(type[0], _("Invalid")) conf_strings = { Citation.CONF_VERY_HIGH : _T_("Very High"), Ci...
self.turnText.hide() self.clockNode.stop() self.clockNode.hide() if winDirection == 0: blinkList = self.findHorizontal(x, y, playerNum) elif winDirection == 1: blinkList = self.findVertical(x, y, playerNum) elif winDirect
ion == 2: blinkList = self.findDiagonal(x, y, playerNum) if blinkList != []: print blinkList val0 = x * 7 + y x = blinkList[0][0] y = blinkList[0][1] val1 = x * 7 + y x = blinkList[1][0] y = blinkList[1][1] ...
nce = Sequence() downBlinkerParallel = Parallel(LerpColorInterval(self.locatorList[val0], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[val1], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[val2], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Ve...
# For some reason, probably because we were trying to serialize the default # object, we put the "filter" field into the metadata. But the filter doesn't # make sense for data other than location, so it doesn't seem like it should be # in the metadata. Putting it into the metadata also means that it is not # accessible...
et_curr_key(entry), curr_filter)) else: pass # logging.warning("No filter found for entr
y %s, skipping" % entry) if "filter" not in entry["data"] and is_location_entry(entry): # This must be an entry from before the time that we started sending # entries to the server. At that time, we only sent time entries, # so set it to time in this case entry["...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
= datas[0] if not data: return {} value = { 'name': 'Document Page', 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'document.page', 'view_id': False, 'type': 'ir.actions.act_window', 'target': '...
['res_id'] = page.id action_id = obj_action.create(cr, SUPERUSER_ID, value) # only the super user is allowed to create menu due to security rules on ir.values menu_id = obj_menu.create(cr, SUPERUSER_ID, { 'name': data.menu_name, 'parent_id':data.m...
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible DIRECTOR = 0 ACTOR = 1 PRODUCER = 2 SCREENPLAY = 3 PHOTOGRAPHY = 4 WRITER = 5 PEOPLE_ROLE = ( (DIRECTOR, 'Director'), (ACTOR, 'Actor'), (PRODUCER, 'Producer'), (SCREENPLAY, 'Sc...
(null=True, default=0) search = models.TextField(null=True,
default=0) genres = models.ManyToManyField(Genre) def __str__(self): return self.title def custom_meth(self): return "Voila" @python_2_unicode_compatible class Role(models.Model): role = models.IntegerField(default=0, choices=PEOPLE_ROLE) people = models.ForeignKey(People, on_del...
from django.app
s import AppConfig class GeoPositionConfig(AppConfig): name =
'geoposition' verbose_name = "GeoPosition"
import numpy as np from . import errors from .container import DiskImageContainer from .segments import SegmentData class DCMContainer(DiskImageContainer): valid_densities = { 0: (720, 128), 1: (720, 256), 2: (1040, 128), } def get_next(self): try: data = self...
raise errors.InvalidContainer("DCM multi-file archive combined in the wrong order") else: raise errors.InvalidContainer("Expected pass one of DCM archive first") density_flag = (archive_flags >> 5) & 3 if density_flag not in self.valid_densities: ...
M file") # DCM decoding goes here. Currently, instead of decoding it raises the # UnsupportedContainer exception, which signals to the caller that the # container has been successfully identified but can't be parsed. # # When decoding is supported, return the decoded byte array ...
import pytest from cli_config.tag import tag from utility.nix_error import NixError def test_tag_show_no_tag(capsys): with pytest.raises(SystemExit) as _excinfo: tag.tag("nixconfig", ["show"]) _out, _err = capsys.readouterr() assert "2" in str(_excinfo.value), "Exception doesn't contain expecte...
, ["show", "badtag"]) _out, _err = capsys.readouterr() a
ssert "Unknown tag: badtag" in str(_excinfo.value) assert len(_out) == 0, "StdOut should be empty, contains: {}".format(_out) assert len(_err) is 0, "StdErr should be empty, contains: {}".format(_err) def test_tag_show_good_tag(capsys): tag.tag("nixconfig", ["show", "tag1"]) _out, _err = capsys.readou...
"""Support for an interface resource in Skytap.""" import json from skytap.framework.ApiClient import ApiClient # noqa from skytap.models.PublishedServices import PublishedServices # noqa from skytap.models.SkytapResource import SkytapResource # noqa class Interface(SkytapResource): """One Skytap (network) In...
ou're doing anything other than asking for services, then this passes the call upstream to do the default stuff. """ if key == 'services':
api = ApiClient() services_json = json.loads(api.rest(self.url)) self.services = PublishedServices(services_json["services"], self.url) return self.services return super(Interface, self).__getattr__(key)
# coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pant...
: self._index(vt, indexer_cp, jvm_options) for vt in invalidation_check.all_vts: entries = self._entries_file(vt) self.context.products.get_data('kythe_entries_files', dict)[vt.target] = entries def _index(self, vt, indexer_cp, jvm_options): self.context.log.info('Kythe indexing {}'.fo...
raise TaskError('No .kindex file found for {}'.format(vt.target.address.spec)) args = [kindex_file, '--emit_jvm', 'semantic', '--out', self._entries_file(vt)] result = self.runjava(classpath=indexer_cp, main=self._KYTHE_JAVA_INDEXER_MAIN, jvm_options=jvm_options, ...
#some useful operations in module arithmetic def power2(base, mod): return (base ** 2) % mod def prod(num1, num2, mod): return (num1 * num2) % mod def power(base, exp, mod): k = 0 while exp >> k != 0: k += 1 k -= 1 result = base for i in range(k - 1, -1, -1): ...
_now = P_fut Q_last = Q_now Q_now = Q_fut return (Q_l
ast, P_last, a * Q_last + b * P_last)
# -*- coding: iso-8859-1 -*- """ MoinMoin - cli show script @copyright: 2006 MoinMoin:ThomasWaldmann @license: GNU GPL, see COPYING for de
tails. """ from MoinMoin.script import MoinScript from MoinMoin.wsgiapp import run class PluginScript(MoinScript): """\ Purpose: ======== Just run a CLI request and show the output. Detailed Instructions: ====================== General syntax: moin [options] cli show [options] usua
lly should be: --config-dir=/path/to/my/cfg/ --wiki-url=http://wiki.example.org/ """ def __init__(self, argv, def_values): MoinScript.__init__(self, argv, def_values) def mainloop(self): self.init_request() run(self.request)
import unittest2 from models.event import Event from models.match import Match from models.team import Team class TestKeyNameValidators(unittest2.TestCase): def setUp(self): self.valid_team_key = "frc177" self.valid_team_key2 = "frc1" self.invalid_team_key = "bcr077" self.invalid_...
self.invalid_match_key = "0010c1_0m2" self.invalid_match_key2 = "2010c1_1f1m1" self.invalid_match_key3 = "2010c1_ef10m1" def test_valid_team_key(self): self.assertEqual(Team.validate_key_name(self.valid_team_key), True) self.assertEqual(Team.validate_key_name(self.valid_team_k...
al(Team.validate_key_name(self.invalid_team_key2), False) self.assertEqual(Team.validate_key_name(self.invalid_team_key3), False) def test_valid_event_key(self): self.assertEqual(Event.validate_key_name(self.valid_event_key), True) self.assertEqual(Event.validate_key_name(self.valid_event_k...
import Logger import os # The following five lines of code MUST ABSOLUTELY appear in this order. DO NOT MOVE OR CHANGE THE FOLLOWING FOUR LINES OF CODE. # Logger.initPins() Should never be called by the user. It should only be called when this script is automatically run. Logger.init() # Initialzie the Logger Pytho...
on dataTuple = Logger.loadData() # Read the data from the EEPROM chip Logger.setRomFree() # Tell the AVR datalogger that the EEPROM chip is no longer in use. # Process the contents of dataTuple here. The format is as follows: # Index
| dataTuple # --------------------------------------------------------- # 0 Number of Records # 1 Year logging started # 2 Month logging started # 3 Day logging started # 4 Hour logging started # 5 Minute logging started # 6 ...
from neo.io.basefromrawio import BaseFromRaw from neo.rawio.plexonrawi
o import PlexonRawIO class PlexonIO(PlexonRawIO, BaseFromRaw): """ Class for reading the old data format from Plexon acquisition system (.plx) Note that Plexon now use a new format PL2 which is NOT supported by this IO. Compatible with versions 100 to 106. Other versions have not been te...
Raw.__init__(self, filename)
# -*- coding: utf-8 -*- """ Created on Tue Apr 9 2
1:30:31 2019 @author: Rignak """ import os from os.path import join, split lines = [] for root, folders, filenames in os.walk('..'): for filename in filenames: if filename ==
'readme.md': lines += [''] with open(join(root, filename), 'r', encoding='utf-8') as file: spoiler = False lines.append(f"\n# {split(root)[-1]}") for line in file.readlines(): if line.startswith('#') and not spoiler: ...
c
lass Student(object): """For student records""" def __init__(self, name=None): # This special method is called a "constructor" self.name = name def print_name(self):
print self.name jenny = Student('Jenny') jenny.print_name() # prints 'Jenny' ### Exercise Time ### bill = Student() bill.print_name()
# -*- coding: UTF-8 -*- # Copyright 2009-2018 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) """Defines the :class:`DisableDeleteHandler` class. See :doc:`/dev/delete`. """ # import logging ; logger = logging.getLogger(__name__) from django.conf import settings from dj...
1208 generic related objects for %s:" % obj for gfk, fk_field, qs in kernel.get_generic_related(obj): if gfk.name in qs.model.allow_cascaded_delete: continue if fk_field.null:
# a nullable GFK is no reason to veto continue n = qs.count() # print "20141208 - %s %s %s" % ( # gfk.model, gfk.name, qs.query) if n: return obj.delete_veto_message(qs.model, n) return None
import importlib import json from .base import MongoEnginericsAdapter class ApistarWSGIAdapter(MongoEnginericsAdapter): def __init__(self, *args, **kwargs): self.engine = importlib.import_module('apistar') self._wsgi = importlib.import_module('apistar.frameworks.wsgi') super(ApistarWSGIAda...
, self).__init__(*args, **kwargs) def attach(self, ctrl): def find(query: self.engine.http.QueryParams): return ctrl.find(query) def update(item_id, updates: s
elf.engine.http.Body): return ctrl.update(item_id, json.loads(updates)) def create(body: self.engine.http.Body): return ctrl.create(json.loads(body)) def find_one(item_id): return ctrl.find_one(item_id) def delete(item_id): return ctrl.delete(it...
import re import requests import bs4 from ralybot import hook from ralybot.util import web # different forks of cloudflare-scrape have different package layouts try: from cfscrape import cfscrape except ImportError: import cfscrape except ImportError: cfscrape = None class SteamError(Exception): pa...
4.BeautifulSoup(request.content) # get all the data we need try: data["name"] = soup.find("h1", {"class": "header-title"}).find("a").text data["url"] = request.url data["status"] = soup.find('td', text='Status').find_next('td').text data["value"] = soup.find("h1", {"class": "c...
e-lowest"}).text data["count"] = int(soup.find("div", {"class": "pull-right price-container"}).find("p").find("span", {"class": "number"}).text) played = soup.fin...
from selenium import webdriver fr
om fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import ContactHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox() elif browser == "chrome":
self.wd = webdriver.Chrome() elif browser == "ie": self.wd = webdriver.Ie() else: raise ValueError("Unrecognezed browser %s" % browser) self.session = SessionHelper(self) self.group = GroupHelper(self) self.contact = ContactHelper(self) s...
#!/usr/bin/env python # encoding: utf-8 """ nim-game.py Created by Shuailong on 2015-12-21. https://leetcode.com/problems/nim-game/. """ class Solution1(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ '''Too time consuming''' win1 = True ...
win3 = win i += 1 return win class Solution(object): def canWinNim(self, n): """ :type n: int
:rtype: bool """ '''Find the law and rewrite''' return n & 3 != 0 # return n % 4 != 0 def main(): solution = Solution() n = 4 print solution.canWinNim(n) if __name__ == '__main__': main()
# 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...
Cloud TPU performance', long_description='Tools for capture TPU profile', url='https://www.tensorflow.org/tfrc/', author='Google Inc.', author_email='opensource@google.com', packages=['cloud_tpu_profiler'], package_data={ 'cloud_tpu_profiler': ['data/*'], }, entry_points={ ...
_SCRIPTS, }, classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Int...
"""Softmax
.""" scores = [3.0, 1.0, 0.2] import numpy as np def softmax(x): """Compute softmax values for each sets of scores in x.""" return np.exp(x) / sum(np.exp(x)) print(softmax(scores)) # Plot softmax curves import matplotlib.
pyplot as plt x = np.arange(-2.0, 6.0, 0.1) scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) plt.plot(x, softmax(scores).T, linewidth=2) plt.show()
#!/usr/bin/env python import os import sys if __nam
e__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bitcamp.settings") from django.core.management import execute_from_co
mmand_line execute_from_command_line(sys.argv)
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
1) if types: return types[0].id return False @api.model def _default_location_id(self): move_obj = self.env['stock.move'] picking_type_id = self._default_picking_type_id() return (move_obj .with_context(default_picking_type_id=picking_type_id)...
on' return self.get_location_from_ref(ref) _defaults = { 'picking_type_id': _default_picking_type_id, 'location_id': _default_location_id, 'location_dest_id': _default_location_dest_id, 'product_uom_qty': 1.0, } @api.multi def reserve(self): """ Confirm ...
warnings from collections import deque from .utils.generic_utils import Progbar class CallbackList(object): def __init__(self, callbacks=[], queue_length=10): self.callbacks = [c for c in callbacks] self.queue_length = queue_length def append(self, callback): self.callbacks.append(ca...
k])) # skip progbar update for the last batch; will be handled by on_epoch_end if self.verbose and self.seen < self.params['nb_sample']: self.progbar.update(self.seen, self.log_values) def on_epoch_end(self, epoch, logs={}): for k in self.params['metrics']: if k in ...
self.log_values.append((k, logs[k])) if self.verbose: self.progbar.update(self.seen, self.log_values) class History(Callback): def on_train_begin(self, logs={}): self.epoch = [] self.history = {} def on_epoch_begin(self, epoch, logs={}): self.seen = 0 sel...
s not round properly' if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass else: raise TestFailed, 'long() does not round properly' if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass else: raise TestFailed, 'float() does not work properly' print '6.4.1 32-bit integers' if 12 + 24 !=...
if a[ 3: pow(2,145L) ] != [3,4]: raise TestFailed, "list slicing with too-large long integer" print '6.6 Mappings == Dictionaries' d = {} if d.keys() != []: raise TestFailed, '{}.keys()' if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')' if ('a' in d) != 0: raise Test
Failed, "'a' in {}" if ('a' not in d) != 1: raise TestFailed, "'a' not in {}" if len(d) != 0: raise TestFailed, 'len({})' d = {'a': 1, 'b': 2} if len(d) != 2: raise TestFailed, 'len(dict)' k = d.keys() k.sort() if k != ['a', 'b']: raise TestFailed, 'dict keys()' if d.has_key('a') and d.has_key('b') and not d.has_key('c...
# -*- coding: utf-8 -*- # Copyright 2016-2017 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """Runs some tests about the notification framework. You can run only these tests by issuing:: $ go team $ python manage.py test tests.test_notify Or:: $ go noi $ python setup.py test -s tests.Project...
es for %d users.', MailModes.often, 1) # logger.info.assert_called_with( # 'Notify %s users about %s', 1, 'Change by robin') Message.objects.all().delete() self.assertEqual(Message.objects.count(), 0)
ar = rt.login('robin') cw = ChangeWatcher(obj) obj.priority = 200 obj.save_watched_instance(ar, cw) with capture_stdout() as out: send_pending_emails_often() out = out.getvalue().strip() # print(out) expected = "" ...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apac
he License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed ...
OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from .client import AccessApprovalClient from .async_client import AccessApprovalAsyncClient __all__ = ( "AccessApprovalClient", "AccessApprovalAsyncCl...
# Copyright 2019 Canonical, Ltd. # # This program is free software: you can redi
stribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even t...
ITNESS 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 this program. If not, see <http://www.gnu.org/licenses/>. import asyncio import concurrent.futures import logging log = logging.ge...
arning = slim_formatwarning def _normalize_ld(launch_description_fn): # A launch description fn can return just a launch description, or a tuple of # (launch_description, test_context). This wrapper function normalizes things # so we always get a tuple, sometimes with an empty dictionary for the test_con...
h_description_fn) if 'ready_fn' in f
n_args.args + fn_args.kwonlyargs: # This is an old-style launch_description function which expects ready_fn to be passed # in to the function # This type of launch description will be deprecated in the future. Warn about it # here warnings.warn( ...
` or ``categories``, which can be used to select which portion of the corpus should be returned. """ def __init__(self, root, fileids, encoding='utf8', tagset=None): """ :type root: PathPointer or str :param root: A path pointer identifying the root directory for this co...
def encoding(self, file): """ Return the unicode encoding for the given corpus file, if known. If the encoding is unknown, or if the given file should be processed using byte strings (str), then return None. """
if isinstance(self._encoding, dict): return self._encoding.get(file) else: return self._encoding def _get_root(self): return self._root root = property(_get_root, doc=""" The directory where this corpus is stored. :type: PathPointer""") ######################...
from
pele.systems import BaseSystem import pele.utils.elements.elements as elem # This is a dictionary of element parameters for atoms class MolecularSystem(BaseSystem): """ Representation for a molecular system, this system stores info about atoms, bonds, angles and torsions. It is possible to repres...
r, this class is used to quickly and efficiently: - add/remove atoms, bonds, angles and torsions; - read/write PDB and other common formats; - interface between different formats of input files for CHARMM, AMBER etc.; - visualise molecular structures; - measure distances betw...
# -*- coding: utf-8 -*- import sys PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if PY3: import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo else: import urlparse # Usamos...
for scrapedurl, scrapedtitle, scrapedthumbnail in matches: scrapedplot = "" if not "manyvids" in scrapedtitle: itemlist.append(item.clone(action="findvideos", title=scrapedtitle, contentTitle=scrapedtitle, fanart=scrapedthumbnail, url=scrapedurl, thumbnail=scrap...
end(item.clone(action="lista", title="[COLOR blue]Página Siguiente >>[/COLOR]", url=next_page)) return itemlist def findvideos(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|amp;|\s{2}|&nbsp;", "", data) patron = '<a href="([^"]+)" rel=...
verifyOrder = { 'orderId': 1234, 'orderDate': '2013-08-01 15:23:45',
'prices': [{ 'id': 1, 'laborFee': '2', 'oneTimeFee': '2', 'oneTimeFeeTax': '.1', 'q
uantity': 1, 'recurringFee': '2', 'recurringFeeTax': '.1', 'hourlyRecurringFee': '2', 'setupFee': '1', 'item': {'id': 1, 'description': 'this is a thing'}, }]} placeOrder = verifyOrder
# yellowbrick.model_selection # Visualizers that wrap the model selection libraries of Scikit-Learn # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Fri Mar 30 10:36:12 2018 -0400 # # ID: __init__.py [c5355ee] benjamin@bengfort.com $ """ Visualizers that wrap the model selection libraries of Scikit-Le...
## from .learning_curve import LearningCurve, lea
rning_curve from .validation_curve import ValidationCurve, validation_curve from .cross_validation import CVScores, cv_scores # RFECV and Feature Importances moved here as of YB v1.0 from .importances import FeatureImportances, feature_importances from .rfecv import RFECV, rfecv
import unittest import numpy as np from numpy.testing import assert_allclose import theano from keras.layers import convolutional class TestConvolutions(unittest.TestCase): def test_convolution_1d(self): nb_samples = 9 nb_steps = 7 input_dim = 10 filter_length = 6 nb_filte...
np.ones((nb_samples, stack_size, input_nb_row, in
put_nb_col)) for weight in [None, weights_in]: for border_mode in ['valid', 'full', 'same']: for subsample in [(1, 1), (2, 3)]: if border_mode == 'same' and subsample != (1, 1): continue for W_regularizer in [None, 'l2']...
# Authors: # Pedro Jose Pereira Vieito <pvieito@gmail.com> (Twitter: @pvieito) # # URL: https://github.com/mr-orange/Sick-Beard # # This file is part of SickRage. # # SickRage 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 Softwa...
, 'method':'create', 'session':'DownloadStation', '_sid':self.auth, 'uri':result.url } if sickbeard.TORRENT_PATH: data['destination'] = sickbeard.TORRENT_PATH self._
request(method='post', data=data) return self.response.json()['success'] def _add_torrent_file(self, result): data = {'api':'SYNO.DownloadStation.Task', 'version':'1', 'method':'create', 'session':'DownloadStation', '_sid':self.auth ...
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Test mempool limiting together/eviction with the wallet from test_framework.test_framework import Bitc...
90) #create a mempool tx that will be evicted us0 = utxos.pop() inputs = [{ "txid" : us0["txid"], "vout" : us0["vout"]}] outputs = {self.nodes[0].getnewaddress() : 0.0001} tx = self.nodes[0].createrawtransaction(inputs,
outputs) self.nodes[0].settxfee(self.relayfee) # specifically fund this tx with low fee txF = self.nodes[0].fundrawtransaction(tx) self.nodes[0].settxfee(0) # return to automatic fee selection txFS = self.nodes[0].signrawtransaction(txF['hex']) txid = self.nodes[0].sendrawtransac...
#!/usr/bin/pythonTest # -*- coding: utf-8 -*- # # Web functions want links # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later vers...
# print3( 'Usage: WantLinks [inputFile [, outputFile] ]' ) print3( 'default inputFile {temp dir}lotsolinks.txt' ) print3( 'default outputFile
{temp dir}UniqueLinks.txt' ) # # # if False: # lProblems.append( 'getDotQuad4IspTester()' ) # # # sayTestResult( lProblems )
############################################################################### # # file: urlfetcher.py # # Purpose: refer to module documentation for details # # Note: This file is part of Termsaver application, and should not be used # or executed separately. # #####################################...
: * `UrlFetcherScreen` """ # # Internal modules # from termsaverlib.screen.base.urlfetcher import UrlFetcherBase from termsaverlib import constants from termsaverlib.i18n import _ class UrlFetcherScreen(UrlFetcherBase): """ Simple screensaver that displays data from a URL. """ de
f __init__(self): """ Creates a new instance of this class. """ UrlFetcherBase.__init__(self, "urlfetcher", _("displays url contents with typing animation")) def _message_no_url(self): """ """ return _(""" You just need to provide the ...
import numpy as np import sys import os import time from ase import Atom, Atoms from ase.visualize import view from ase.units import Bohr from ase.structure import bulk from gpaw import GPAW from gpaw.atom.basis import BasisMaker from gpaw.response.df import DF from gpaw.mpi import serial_comm, rank, size from gpaw.uti...
ts=(24,24,24), kpts=(2,2,2), xc='LDA') atoms.set_calculator(calc) atoms.get_potential_energy() calc.write('Al2.gpw','all')
# Excited state calculation q = np.array([1./2.,0.,0.]) w = np.linspace(0, 24, 241) df = DF(calc='Al2.gpw', q=q, w=w, eta=0.2, ecut=50) #df.write('Al.pckl') df.get_EELS_spectrum(filename='EELS_Al_2') d1 = np.loadtxt('EELS_Al_1') d2 = np.loadtxt('EELS_Al_2') error1 = (d1[1:,1] - d2[1:,1]) / d1[1:,1] * 100 error2 = (d...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Tue 31 May 2016 @author: Fabrizio Coccetti (fabrizio.coccetti@centrofermi.it) [www.fc8.net] Query Run Db and extract several infos """ import os import MySQLdb from datetime import datetime, timedelta import ConfigParser import logging import logging.config...
pen(os.path.join(pathWorkDir, pklStatFile), 'wb') #pickle.dump(trackStat, output) #output.close() #logger = logging.getLogger('full') #logger.info('Written '
+ os.path.join(pathWorkDir, pklStatFile)) cur.close() db.close() w.close() logger.info('Finished')
# # Licensed to the Apache Software Fou
ndation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Lice
nse"); 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 WARRAN...
# intended to be altered after initial creation. obj = copy.copy(self) if self.rel: obj.rel = copy.copy(self.rel) if hasattr(self.rel, 'field') and self.rel.field is self: obj.rel.field = obj memodict[id(self)] = obj return obj def __copy__(se...
override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self._choices and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(opt...
group_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages['invalid_choice'], code='invalid_choice...