prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/env python
import argparse
import sys
import re
import os
import locale
import subprocess
from multiprocessing import Process
def dbquery(query):
import psycopg2
db = psycopg2.connect(dbname = "firmware", user = "firmadyne", password = "firmadyne", host = "127.0.0.1")
ret = None
try:
... | g the firmware binaries | with AFL")
parser.add_argument("-n", dest="netafl", action="store_true",
default=False, help="Fuzzing the network services with AFL")
parser.add_argument("-m", dest="metasploit", action="store_true",
default=False, help="Penetration test with metasploit exploits")... |
// image_modulus - 1] = img
RT_blender[ii // image_modulus - 1, :] = RT.reshape(12)
R_i2bcam[ii // image_modulus - 1, :] = R.reshape(9)
# do some image processing and visual odometry
ii += 1
image_data.create_dataset('K', data=K)
image_data.cre... |
ii = 1
while system.successful() and system.t < tf:
# integrate the system and save state to an array
time[ii] = (system.t + dt)
| i_state[ii, :] = (system.integrate(system.t + dt))
# generate the view of the asteroid at this state
if int(time[ii]) % image_modulus == 0 and gen_images:
# img, RT, R = blender.gen_image(i_state[ii,0:3], i_state[ii,6:15].reshape((3, 3)),
# ast.... |
"""Functions for the backend of LetterBoy"""
def lb_standardcase():
"""Capitalise the first letter of each sentence, and set all others to lowercase."""
pass
def lb_uppercase():
"""Capitalise each letter."""
pass
def lb_lowercase():
"""Set all letters to lowercase."""
pass
def ... | """Alternate eac | h character between upper- and lower-case."""
pass
def lb_jumbles_nontrobo():
"""Jumble up text between the first and last letters in each word."""
pass
def lb_zcorrupt():
"""Add glitch text to the plaintext."""
pass
def lb_zstrip():
"""Remove glitch text."""
pass
|
import uuid
import datetime | as dt
import json
import urllib.request
import urllib.parse
from Main.handlers.settings import RECAPTCHA_SECRET_KEY
def get_title(title=""):
if title == "":
return "GetCompany info"
else:
return title + " - GetCompany info"
def get_new_token():
ret | urn str(str(uuid.uuid4()) + str(uuid.uuid4())).replace("-", "")[:32]
def get_timestamp(datetime):
return int(dt.datetime.strptime(datetime, "%Y-%m-%d %H:%M:%S.%f").timestamp())
def remove_microseconds(datetime):
return dt.datetime.strptime(datetime, "%Y-%m-%d %H:%M:%S.%f")
def get_remote_IP(request):
ip ... |
# 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 ... | Prefix', 'type': 'str'},
'destination_address_prefix': {'key': 'destinationAddressPrefix', 'type': 'str'},
'source_address_prefixes': {'key': 'sourceAddressPrefixes', 'type': '[str]'},
'destination_address_prefixes': {'key': 'destinationAddressPrefixes', 'type': '[str]'},
'expanded_sourc... | ess_prefix': {'key': 'expandedDestinationAddressPrefix', 'type': '[str]'},
'access': {'key': 'access', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'direction': {'key': 'direction', 'type': 'str'},
}
def __init__(self, **kwargs):
super(EffectiveNetworkSecurity... |
der the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import jsonpickle
from azure.cosmosdb.table import TableServi... | TYPE]}}
)
def __init__(self, data, manager=None):
super(StorageDiagnosticSettingsFilter, self).__init__(data, manager)
self.storage_type = data.get('storage-type')
s | elf.log = logging.getLogger('custodian.azure.storage')
def process(self, resources, event=None):
session = local_session(self.manager.session_factory)
token = StorageUtilities.get_storage_token(session)
result, errors = ThreadHelper.execute_in_parallel(
resources=resources,
... |
from django import template
from bookmarks.models import BookmarkInstance
from tagging.models import Tag
register = template.Library()
@register.inclusion_tag('bookmarks/tags.html')
def show_bookmarks_tags():
""" Show a box with tags for all articles that belong to current site.
""" |
return {'bookmark_tags': Tag.objects.usage_for_queryset(queryset=BookmarkInstance.on_site.all(), counts=T | rue, min_count=1)} |
"""
Helper file to manage translations for the Meerkat Authentication module.
We have two types of translations, general and implementation specific
The general translations are extracted from the python, jijna2 and js files.
"""
from csv import DictReader
import argparse
import os
import shutil
import datetime
f... | ="Two letter | langauge code")
if __name__ == "__main__":
args = parser.parse_args()
lang_dir = "meerkat_auth"
if args.action == "update-po":
os.system("pybabel extract -F babel.cfg -o {}/messages.pot .".format(lang_dir) )
os.system("pybabel update -i {}/messages.pot -d {}/translations".format(lang_dir... |
#/usr/bin/python
#!*-* coding:utf-8 *-*
# Este script es sofware libre. Puede redistribuirlo y/o modificarlo bajo
# los terminos de la licencia pública general de GNU, según es publicada
# por la free software fundation bien la versión 3 de la misma licencia
# o de cualquier versión posterior. (según su elección ).... | -geom 50x8+185+1 | 00 +cm -bg blue -e python bin/c_p_Ate.py &")
# os.system("python bin/c_p_Ate.py")
# --------------------------------CONFIGURACION DE VENTANA ------------------------------------------------------------------------------
X=8
Y=10
lblTitulo = Label(bicho, text="ATENUACION", fg = ("blue"), bg = ("white"), f... |
import os
from conans.tools import unzip
import shutil
from conans.util.files import rmdir, mkdir
from conans.client.remote_registry import RemoteRegistry
from conans import tools
from conans.errors import ConanException
def _handle_remotes(registry_path, remote_file, output):
registry = RemoteRegistry(registry_p... | der):
relative_path = os.path.relpath(root, source_folder)
if relative_path == ".":
relative_path = ""
for f in | files:
profile = os.path.join(relative_path, f)
output.info(" Installing profile %s" % profile)
shutil.copy(os.path.join(root, f), os.path.join(target_folder, profile))
def _process_git_repo(repo_url, client_cache, output, runner, tmp_folder):
output.info("Trying to clone r... |
"""
RUN FROM THIS FILE
Alexandre Yang
ITP 115
Final Project
05/08/2014
Description:
Refer to readme.txt
"""
import pygame
from Oto import Oto
from Button import Button
from Label import Label
# Input: pygame.Surface, tuple, int, int, int, int
# Output: none
# Side-effect: Draws the grid on the screen
def drawBoard... | seClick.image.get_rect()
mouseClick.rect.x = mouseX
mouseClick.rect.y = mouseY
return mouseClick
def main():
# Set general variables
screenW = 850
screenH = 775
boardW = 675
boardH = 675
tileWidth = 75
tileHeight = 75
running = True
screen = pygame.display.set_mode((sc... | r = 255, 255, 255
# Create sprite groups (necessary to call draw() method)
otoList = pygame.sprite.Group()
buttonList = pygame.sprite.Group()
labelList = pygame.sprite.Group()
# Create Menu Buttons and add them to buttonList sprite group
playButton = Button(screen, 100, boardH+40, 50, 50, "Pla... |
# -*- codin | g: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('SocialNetworkModels', '0006_remove_comments_post_author'),
]
operations = [
migrations.AddField(
model_name='comments',
... | ve_default=False,
),
]
|
#!/usr/bin/env python
import sys
import socket
import colorsys
import time
try:
| s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except:
print('Failed to create socket')
sys.exit(1)
host | = sys.argv[1];
port = 1337;
r = int(sys.argv[3])
g = int(sys.argv[4])
b = int(sys.argv[5])
msg = bytes([ 0x20 + int(sys.argv[2]), r, g, b, 0x1F, 0x20 + int(sys.argv[2]) ])
s.sendto(msg, (host, port))
|
from __future__ import print_function
import pandas
from sklearn.naive_bayes import MultinomialNB
from sklearn.cross_validation import train_test_split
from sklearn.pr | eprocessing import LabelEncoder
def main():
train_all = pandas.DataFrame.from_csv('train.csv')
train = train_all[['Survived', 'Sex', 'Fare']][:200]
gender_label = LabelEncoder()
train.Sex = gender_label.fit_transfor | m(train.Sex)
X = train[['Sex', 'Fare']]
y = train['Survived']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.33, random_state=42)
clf = MultinomialNB()
clf.fit(X_train, y_train)
print('Accuracy: ', end='')
print(sum(clf.predict(X_test) == y_test) / float(le... |
import datetime
import decimal
import hashlib
import logging
from time import time
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils.timezone import utc
logger = logging.getLogger('django.db.backends')
class CursorWrapper:
def __init__(self, cursor, db):
se... | ass
# The following methods cannot be implemented in __getattr__, because the
# code must run when the method is invoked, not just when it is accessed.
def callproc(self, procname, params=None):
self.db.validate_no_broken_transaction()
with self.db.wrap_database_errors:
if para... | name)
else:
return self.cursor.callproc(procname, params)
def execute(self, sql, params=None):
self.db.validate_no_broken_transaction()
with self.db.wrap_database_errors:
if params is None:
return self.cursor.execute(sql)
else:
... |
def pig_it(text):
ret | urn ' '.join([x[1:]+x[0]+'ay' if x.isalpha() else x for x in text.split()])
# 其实就是2个字符串过滤拼接,比移动方便多了,思路巧妙
# a if xx else b, 单行判断处理异常字符,xx为判断,标准套路
for x in text.split()
if x.isalpha()
x[1:]+x[0]+'ay'
... | ]) |
expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('add_2-0-0', nodes)
self._assert_map_nhwc_to_nchw('split-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
de... | nodes = []
num_tr | ansposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_n... |
from configparser import ConfigParser
import v20
# Create an object config
config = ConfigParser()
# Read the config
config.read("../API_Connection_Oanda/pyalgo.cfg")
ctx = v20.Context(
'api-fxpractice.oanda.com',
443,
True,
application = 'sample_code',
token = config['oanda_v20']['access_token'],... | accounts:
# account('Account: %s' %account)
print account
def get_instruments():
response = ctx.account.instruments(
| config['oanda_v20']['account_id'])
instruments = response.get('instruments')
# instruments[0].dict()
for instrument in instruments:
ins = instrument.dict()
print('%20s | %10s' % (ins['displayName'],
ins['name']))
|
# By starting at the top of the triangle below and moving to adjacent numbers on the
# row below, the maximum total from top to bottom is 23.
# 3
# 7 4
# 2 4 6
# 8 5 9 3
# That is, 3 + 7 + 4 + 9 = 23.
# Find the maximum total from top to bottom of the triangle below:
# 75
# 95 64
# 17 47 82
# 18 35 87 10
# 20 04 8... | 65 04 28 06 16 70 92\n\
41 41 26 56 83 40 80 70 33\n\
41 48 72 33 47 32 37 16 94 29\n\
53 71 44 65 25 43 91 52 97 51 14\n\
70 11 33 28 77 73 17 78 39 68 17 57\n\
91 71 52 38 17 14 91 43 58 50 27 29 48\n\
63 66 04 68 89 53 67 30 73 16 69 87 40 31\n\
04 62 98 27 23 09 | 70 98 73 93 38 53 60 04 23'
digits = [[int (y) for y in x.split(' ')] for x in text.split('\n')]
for i in range(1, len(digits)):
digits[i][0] += digits[i - 1][0]
digits[i][len(digits[i]) - 1] += digits[i - 1][len(digits[i - 1]) - 1]
for j in range(1, len(digits[i]) - 1):
digits[i][j] += max(digits[i - 1][j - 1],... |
def get_perm_argparser(self, args):
args = args.split(" ")
if args[0] == "nick":
self.conman.gen_send("Permission level for %s: %s" % | (args[1], self.permsman.get_nick_perms(args[1])))
elif args[0] == "cmd":
if args[1].startswith("."):
args[1] = args | [1][1:]
self.conman.gen_send("Permission level for %s: %s" % (args[1], self.permsman.get_cmd_perms(args[1])))
elif args[0] == "msg":
self.conman.gen_send("Message permissions for %s: %s" % (args[1], self.permsman.get_msg_perms(args[1])))
def set_perm_argparser(self, args):
args = args.split(" "... |
#!/usr/bin/env python
import os
import sys
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(PROJECT_DIR)
sys.path.append(os.path.abspath(PROJECT_DIR + '/../' | ))
sys.path.append(os.path.abspath(PROJECT_DIR + '/../realestate/'))
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTING | S_MODULE", "testproject.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
# -*- coding: utf-8 -*-
# gedit CodeCompletion plugin
# Copyright (C) 2011 Fabio Zendhi Nagao
#
# 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 o... | ed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not... | a.backward_char()
ch = a.get_char()
#if not (ch.isalnum() or ch in ['_', ':', '.', '-', '>']):
if not (ch.isalnum() or ch in "_:.->"):
a.forward_char()
break
word = a.get_visible_text(b)
return a, word
def get_document(piter):
a = piter.... |
"""Admin Configuration for Improved User"""
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
from .forms import UserChangeForm, UserCreationForm
class UserAdmin(BaseUserAdmin):
"""Admin panel for Improved User, mimics Django's default"""
... | "),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "... | "password1", "password2"),
},
),
)
form = UserChangeForm
add_form = UserCreationForm
list_display = ("email", "full_name", "short_name", "is_staff")
search_fields = ("email", "full_name", "short_name")
ordering = ("email",)
|
aidUtil = '/opt/MegaRAID/storcli/storcli64'
class RaidControllerLSI(TextAttributeParser, RaidController):
_attributes = [
(r'(?i)^Model\s=\s(.*)$', 'Model', None, False, None),
(r'(?i)^Serial\sNumber\s=\s(.*)$', 'Serial', None, False, None),
(r'(?i)^Controller\sStatus\s=\s(.*)$', 'Status'... | t(self.BIOS))
print('FW version : {}'.format(self.Firmware))
def __fill_data(self):
for line in helpers.getOutput('{} /c{} show all nolog'.format(raidUtil, self.Name)):
if re.match(r'(?i)^TOPOLOGY\s:', line):
| break
if self._process_attributes_line(line):
continue
class RaidLDvendorLSI(RaidLD):
def __init__(self, name, controller):
(self.DG, self.VD) = name.split('/')
super(self.__class__, self).__init__(name, controller)
self.Device = self.Name
... |
# -*- enc | oding: utf-8 -*-
import os
from abjad im | port abjad_configuration
from abjad.demos import desordre
def test_demos_desordre_01():
lilypond_file = desordre.make_desordre_lilypond_file() |
#### NOTICE: THIS FILE IS AUTOGENERA | TED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object | /tangible/furniture/all/shared_frn_all_lamp_free_s01_lit.iff"
result.attribute_template_id = 6
result.stfName("frn_n","frn_lamp_free")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Nument | a, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public Licen | se version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should ha... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Trial.max_participants'
db.delete_column(u'trials_trial', 'max_participants')
def ba... | 'participants': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'recruiting': ( | 'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'recruitment': ('django.db.models.fields.CharField', [], {'default': "'an'", 'max_length': '2'}),
'reporting_freq': ('django.db.models.fields.CharField', [], {'default': "'da'", 'max_length': '200'}),
'start_date': ('d... |
# Ansible module to manage CheckPoint Firewall (c) 2019
#
# Ansible 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.
#
# Ansible is dist... | = {
"name": "New Host 1",
"ip_address": "192.0.2.1"
}
UPDATE_PAYLOAD = {
"name": "New Host 1",
"color": "blue",
"ipv4_address": "192.0.2.2"
}
OBJECT_AFTER_UPDATE = UPDATE_PAYLOAD
DELETE_PAYLOAD = { |
"name": "New Host 1",
"state": "absent"
}
function_path = 'ansible.modules.network.check_point.cp_mgmt_host.api_call'
api_call_object = 'host'
class TestCheckpointHost(object):
module = cp_mgmt_host
@pytest.fixture(autouse=True)
def module_mock(self, mocker):
return mocker.patch.multipl... |
field_dict['help_text'] = self.field.help_text
field_dict['error_messages'] = self.field.error_messages
# Instantiate the Remote Forms equivalent of the widget if possible
# in order to retrieve the widget contents as a dictionary.
remote_widget_class_name = 'Remote%s' % self.field.wi... | idget_class_name, str(e))
widget_dict = {}
else:
widget_dict = remote_widget.as_dict()
field_dict['widget'] = widget_dict
return field_dict
class RemoteCharField(RemoteField):
def as_dict(self):
field_dict = super(RemoteCharField, self).as_dict()
... | eld.max_length,
'min_length': self.field.min_length
})
return field_dict
class RemoteIntegerField(RemoteField):
def as_dict(self):
field_dict = super(RemoteIntegerField, self).as_dict()
field_dict.update({
'max_value': self.field.max_value,
'min... |
#!/usr/bin/python
import math
# return statement
def printLog(x):
if x <= 0:
print "Positive number only, please."
return
result = math | .log(x)
print "The log of x is", result
x, y = -2, 3
printLog(y)
| |
ument):
def get_feed(self):
return '{0}: {1}'.format(_(self.status), self.project_name)
def onload(self):
"""Load project tasks for quick view"""
if not self.get('__unsaved') and not self.get("tasks"):
self.load_tasks()
self.set_onload('activity_summary', frappe.db.sql('''select activity_type,
sum(hou... | rappe.throw(_("Expected End Date can not be less than Expected Start Date"))
|
def validate_weights(self):
sum = 0
for task in self.tasks:
if task.task_weight > 0:
sum = sum + task.task_weight
if sum > 0 and sum != 1:
frappe.throw(_("Total of all task weights should be 1. Please adjust weights of all Project tasks accordingly"))
def sync_tasks(self):
"""sync tasks and remove... |
from base import MediaFile
from fields import MediaFileField
| from widgets import AdminMediaFi | leWidget
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
###########################################################... | 'name': 'Password Encryption',
'version': '1.1',
'author': ['OpenERP SA', 'FS3'],
'maintainer': 'OpenERP SA',
'website': 'http://www.openerp.com',
'category': 'Tools',
'description': """
Ecrypted passwords
==================
Interaction with LDAP authentication:
----------------------------... |
# encoding: utf-8
# module pyexpat
# from /usr/lib/python2.7/lib-dynload/pyexpat.x86_64-linux-gnu.so
# by generator 1.135
""" Python wrapper for Expat parser. """
# imports
impo | rt pyexpat.errors as errors # <module 'pyexpat.errors' (built-in)>
import pyexpat.model as model # <module 'pyexpat.model' (built-in)>
# Variables with simple values
EXPAT_VERSION = 'expat_2.1.0'
native_encoding = 'UTF-8'
XML_PARAM_ENTITY_PARSING_ALWAYS = 2
XML_PARAM_ENTITY_PARSING_NEVER = 0
XML_PARAM_ENTITY_PARSI... | """
ErrorString(errno) -> string
Returns string error for given number.
"""
return ""
def ParserCreate(encoding=None, namespace_separator=None): # real signature unknown; restored from __doc__
"""
ParserCreate([encoding[, namespace_separator]]) -> parser
Return a new XML parser object.
... |
"""Support for the AccuWeather service."""
from __future__ import annotations
from statistics import mean
from typing import Any, cast
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION,
ATTR_FORECAST_PRECIPITATION_PROBABILITY,
ATTR_FORECAST_TEMP,
A... | CAST_WIND_BEARING,
ATTR_FORECAST_WIND_SPEED,
Forecast,
WeatherEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
SPEED_MILES_PER_HOUR,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import HomeAss | istant
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util.dt import utc_from_timestamp
... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic string exercises
# Fill in the code for the functions below. main() is already se... | dditional functions to try in string2.py.
# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Num... | e:
return 'Number of donuts: many'
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) >= 2:
return s[0]... |
def main():
#init an array named a
a = list()
a = []
b = [1,'1',[1,2]]
#Get the size of a list
a_size = len(a)
#how to check if a list is empty
if (a):
print ("not empty")
else:
print ("empty")
index = 0
a = ['a','b','c']
print (a[index])
a.append('d')
a.extend(['e'])
print ('After append a, ex... | rt(2,'bb')
print ('After insert bb at 2')
print (a)
a.ins | ert(0, 'a0')
print ('After insert a0 at 0')
print (a)
#Find the index of a item in an array
answer_1 = a.index('a')
answer_0 = a.index('a0')
print ('use a.index(item) to find the index only for the first item')
#list.pop() r
eturn last item in the list and remove the last item
print 'Before a.pop(), a = ', ... |
# # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from doj... | tra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@us... | Form(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-s... |
r more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pygraph.algorithms.accessibility import accessibility, mutual_accessibility
from pygraph.classes.digraph import digraph
from pygraph.algorithms.minmax impor... | s(), key=lambda pattern: pattern.count(PREFERRED_SAME), reverse=True):
if pattern.count(PREFERRED_SAME) == 0:
break
self.proportional_completion_round(pattern, profile)
try:
assert round(weight_sum, 5) == round(sum(profile.values()), 5)
except:
... | tional_completion_round(self, completion_pattern, profile):
# Remove pattern that contains indifference
weight_sum = sum(profile.values())
completion_pattern_weight = profile[completion_pattern]
del profile[completion_pattern]
patterns_to_consider = {}
for pattern in pr... |
# ===============================================================================
# Copyright 2015 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | tory',
tooltip='Repository assigned to this analysis in the Experiment Queue',
editor=myEnumEditor(name='available_ids')),
ObjectColumn(name='repository_ids',
label='Existing Repositories',
... | e)]
v = okcancel_view(UItem('conflicts', editor=TableEditor(columns=cols)),
title='Resolve Repository Conflicts')
return v
if __name__ == '__main__':
def main():
from pychron.paths import paths
paths.build('_dev')
from pychron.core.helpers.logger... |
oding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from ..compat import USER_MODEL
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Review'
db.create_table(u'review_review', (
(u'id', se... | ))
db.send_create_signal(u'review', ['Review'])
# Adding model 'ReviewExtraInfo'
| db.create_table(u'review_reviewextrainfo', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('type', self.gf('django.db.models.fields.CharField')(max_length=256)),
('review', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['review.Review'])),... |
from .plot_widget import PlotWidget
from .filter_popup import FilterPopup
from .filterable_kw_list_model import Filtera | bleKwListModel
from .data_type_keys_list_model import DataTypeKeysListModel
from .data_type_proxy_model import DataTypeProxyModel
from .data_type_keys_widget import DataTypeKeysWidget
from .plot_case_model import PlotCaseModel
from .plot_case_selection_widget import CaseSelectionWidget
from .color_chooser import Colo... | _tool import PlotTool
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from random import randint
from time import sleep
import brain
import game
drv = webdriver.Firefox()
drv.get('http://gabrielecirulli.github.io/2048/')
container = drv.find_element_by_class_name('tile-container')
retry = drv.find_element_by_... | ard = [[None, None, None, None],
[None, None, None, None],
[None, None, None, None],
[None, None, None, None]]
def move_up():
container.send_keys(Keys.UP)
def move_down():
container.send_keys(Keys.DOWN)
def move_left():
container.send_keys(Keys.LEFT)
def move_right():
cont... | None, None, None],
[None, None, None, None],
[None, None, None, None]]
def update_board():
global board
sleep(0.1)
tiles = container.find_elements_by_class_name('tile')
tiledata = list(map(lambda x: x.get_attribute('class').split(), tiles))
zero_board()
for tile in til... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2011 Pexego Sistemas Informáticos. All Rights Reserved
# $Omar Castiñeira Saavedra$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of | the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTAB... | icense 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/>.
#
##############################################################################
|
#-*- coding: utf-8 -*-
# collections.py
# Define various kind of collections
#
# Copyright (C) 2016 Jakub Kadlcik
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) ... | cessesCollection(unique)
def filtered(self, function):
processes = ProcessesCollection()
for process in self:
try:
if function(process):
processes.append(process)
except NoSuchProcess: pass
return processes
class AffectedProcessesCollection(ProcessesCollection):
def update(self, iterable):
... | package_manager = None
def __init__(self, *args):
list.__init__(self, *args)
def intersection(self, packages):
if packages is not None:
return PackagesCollection(set(packages).intersection(self))
return self
@property
def files(self):
files = []
for package in self:
files.extend(self._package_man... |
"""
Analytical template tags and filters.
"""
from __future__ import absolute_import
import logging
from django import template
from django.template import Node, TemplateSyntaxError
from django.utils.importlib import import_module
from templatetags.utils import AnalyticalException
TAG_LOCATIONS = ['head_top', 'hea... | 'analytical.reinvigorate',
'analytical.woopra',
'''
logger = logging.getLogger(__name__)
r | egister = template.Library()
def _location_tag(location):
def analytical_tag(parser, token):
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' tag takes no arguments" % bits[0])
return AnalyticalNode(location)
return analytical_tag
for loc in ... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | ributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Set User.last_login automatically in the DB
Revision ID: a65114e48d6f
Revises: 10 | 4b4c56862b
Create Date: 2016-06-11 00:28:39.176496
"""
from alembic import op
import sqlalchemy as sa
revision = 'a65114e48d6f'
down_revision = '104b4c56862b'
def upgrade():
op.alter_column(
"accounts_user",
"last_login",
server_default=sa.func.now(),
)
def downgrade():
op.alt... |
from man import comm
from . import NogginConstants as Constants
from . import GameStates
from .util import FSA
from . import Leds
TEAM_BLUE = 0
TEAM_RED = 1
class GameController(FSA.FSA):
def __init__(self, brain):
FSA.FSA.__init__(self,brain)
self.brain = brain
self.gc = brain.comm.gc... | ef timeSincePlay(self):
return Constants.LENGTH_OF_HALF - self.timeRemaining
def getScoreDifferential(self):
'''
negative when we're losing
'''
return self.brain.gameController.gc.teams(self.brain.my.teamColor)[ | 1] -\
self.brain.gameController.gc.teams((self.brain.my.teamColor+1)%2)[1]
def setGCLEDS(self):
'''
Method to set the chest and feet according to the current
GC states and infos
'''
####### KICKOFF ######
if (self.gc.kickOff == self.gc.team and
... |
pe)
assert(args is None or type(args) in [list, tuple])
assert(kwargs is None or type(kwargs) == dict)
assert(timeout is None or type(timeout) in six.integer_types)
assert(receive_progress is None or type(receive_progress) == bool)
assert(discloseMe is None or type(discloseMe) == bool)
... | _id(wmsg[1], "'request' in CANCEL")
options = check_or_raise_extra(wmsg[2], "'options' in CANCEL")
## options
##
mode = None
if u'mode' in options:
| option_mode = options[u'mode']
if type(option_mode) != six.text_type:
raise ProtocolError("invalid type {} for 'mode' option in CANCEL".format(type(option_mode)))
if option_mode not in [Cancel.SKIP, Cancel.ABORT, Cancel.KILL]:
raise ProtocolError("invalid value '{}' for 'mo... |
ublished by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a ... | lf.label_indices = {} # Digit -> Indices in dataset
self.label_cursors = {} # Digit -> Cursor across images for each digit
sequences = list(sequences) # Avoid c | hanging underlying sequence list
if self.noise_buffer:
for seq in sequences:
if seq[-1] != -1:
seq.append(-1)
self.sequences = sequences
self.n_sequences = len(self.sequences)
self.seq_lengths = torch.tensor([len(subseq) for subseq in self.... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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.
T... | les(False)
self._totalTime = 0
while self._totalTime == 0:
try:
self._totalTime = self.getTotalTime()
except RuntimeError:
self._totalTime = 0
break
xbmc.sleep(1000)
if resume_point:
resume_time = f... | Total Time: %s" % (resume_point, resume_time, self._totalTime), log_utils.LOGDEBUG)
self.seekTime(resume_time)
def onPlayBackStopped(self):
log_utils.log('Service: Playback Stopped')
if self.tracked:
playedTime = float(self._lastPos)
try: percent_played = int((p... |
'''
|
New Integration Test for hybrid.
@author: Quarkonics
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.hybrid_operations as hyb_o | ps
import zstackwoodpecker.operations.resource_operations as res_ops
import time
import os
postfix = time.strftime('%m%d-%H%M%S', time.localtime())
test_obj_dict = test_state.TestStateDict()
remote_bucket_name = 'test-bucket-%s' % postfix
test_stub = test_lib.lib_get_test_stub()
hybrid = test_stub.HybridObjec... |
import os
import uuid
from django.db import models
from django.core.files.uploadedfile import UploadedFile
from django.forms.forms import | pretty_name
from . import get_image_cropper
from . import tasks
from . import settings
from . import utils
from . import signals
from .managers import AssetManager
from .fields import AssetRealFileField
try:
from ..versioning import manager
except ValueError:
from versioning import manager
try:
from ..c... | ernal_tags.models import AutoTagModel
class AssetBase(AutoTagModel):
UNKNOWN = 'unknown'
IMAGE = 'image'
DOCUMENT = 'document'
AUDIO = 'audio'
VIDEO = 'video'
TYPES = settings.ASSET_TYPES and settings.ASSET_TYPES or \
((UNKNOWN, 'Unknown'),
(IMAGE, 'Image'),
(DOCUMENT,... |
#!/usr/bin/env python
#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
###############################... | vals = af.sort_by_key(a, b, is_ascending=False)
display_func(keys)
display_func(vals)
c = af.randu(5, 1)
d = af.randu(5, 1)
cc = af.set_unique(c, is_sorted=False)
dd = af.set_unique(af.sort(d), is_sorted=True)
display_func(cc)
display_func(dd)
display_func(af.set_union(cc, dd, is_... | =False))
display_func(af.set_intersect(cc, cc, is_unique=True))
display_func(af.set_intersect(cc, cc, is_unique=False))
_util.tests["algorithm"] = simple_algorithm
|
#!/usr/bin/env python
import datetime
import logging
import math
import socket
import tables
import xml.etree.ElementTree as ET
logging.basicConfig(filename = 'mbta_daemon.log', level=logging.INFO)
logger = logging.getLogger('xml2hdf5')
class VehicleLocation(tables.IsDescription):
vehicleID = tables.StringCol(4)
... | f record is already reported
if (data['vehicleID'], data['time']) not in presentData:
vehiclePosition = database.row
for key, value in data.items():
vehiclePosition[key] = value
vehiclePosition.append()
presentData[data['veh... | database.flush()
logger.info('Parsed data from XML file: %s', thefile)
return presentData
def ParseAll(theHDF5FileName = 'mbta_trajectories.h5', Cleanup = True):
import glob, os
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
## Create an abstract socket, by prefixing i... |
json_errors
@cache.cached(timeout=60, key_prefix=cache_key)
#@log_request("aggregate", "aggregates")
def cubes_model(star_name):
cubes_arg = request.args.get("cubes", None)
try:
cubes = cubes_arg.split("|")
except:
raise RequestError("Parameter cubes with value '%s'should be a valid cube ... | se format '%s'" % output_format)
# csv
| if header_type == "names":
header = result.labels
elif header_type == "labels":
header = []
for l in result.labels:
# TODO: add a little bit of polish to this
if l == SPLIT_DIMENSION_NAME:
header.append('Matches Filters')
else:
... |
# Transformer/Utilities/__in | it__.py
| |
import bcrypt
from hashlib import sha512
from helptux import db, login_manager
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
role = db.Column(db.String(255), index=True, unique=True)
def __repr__(self):
return '<Role {0}>'.format(self.role)
de... | .role_id == Role.id),
backref=db.backref('users', lazy='dynamic'),
lazy='dynamic')
def __init__(self, email, password):
self.email = email
self.username = self.email
self.set_password(password)
def __repr__(self):
return '... | ername': self.username,
'posts': [p.id for p in self.posts],
'roles': [r.id for r in self.roles]
}
def set_password(self, input_password):
bit_input = input_password.encode('utf-8')
self.password_hash = bcrypt.hashpw(bit_input, bcrypt.gensalt())
def verify_passw... |
import csv
from openpyxl import load_workbook
import io
from dwarfsquad.lib.build.from_export import build_compound_methods, build_lots_and_levels
from dwarfsquad.lib.build.from_export.build_assay_configuration import build_assay_configuration
from dwarfsquad.lib.build.from_export.build_rulesettings import add_rules_to... | _full_ac(path_to_xlsx):
wb = load_workbook(path_to_xlsx)
validate_workbook(wb)
ac = build_assay_configuration(read_csv_from_sheet(wb.get_sheet_by_name('Assay')))
ac.compound_methods = build_compound_methods(read_csv_from_sheet(wb.get_sheet_by_name('Compound')))
ac.lots = build_lots_and_levels(read_c... | as = generate_rule_schemas(ac)
if not ac.macros:
ac.macros = generate_macros(ac)
return ac
def get_column_value(c):
if c.value:
try:
return str(round(c.value, 8))
except TypeError:
return str(c.value)
else:
return ''
def read_csv_from_sheet(wor... |
ute_import, unicode_literals
import flask
import os
import logging
from flask_heroku import Heroku
from flask_redis import Redis
from flask_sslify import SSLify
from flask_sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
from werkzeug.contrib.fixers import ProxyFix
from freight.api.controller impo... | .user_context({
'id': session['uid'],
'email': session['email'],
})
register_signal(sentry.client)
| register_logger_signal(sentry.client)
def configure_sqlalchemy(app):
db.init_app(app)
def configure_web_routes(app):
from freight.web.auth import AuthorizedView, LoginView, LogoutView
from freight.web.index import IndexView
from freight.web.static import StaticView
static_root = os.path.join(PR... |
#!/usr/bin/env python
# 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... | se RuntimeError('Template %s is not a file.')
pass
def backup_template(template):
extension = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
backup_filename = os.path.realpath(template) + '.' + extension
if os.path.exists(backup_filename):
raise RuntimeError('Backupe file: %s already exists.... | ackup_filename)
def needs_conversion():
with open(OPTS.template, 'r') as f:
template = yaml.load(f.read(), Loader=TemplateLoader)
net_config_res = template['resources'].get('OsNetConfigImpl')
if (net_config_res and net_config_res[
'type'] == 'OS::Heat::SoftwareConfig'):
backup_... |
from Monument import Monument, Dataset
import importer_utils as utils
import importer as importer
class DkBygningDa(Monument):
def set_adm_location(self):
if self.has_non_empty_attribute("kommune"):
if utils.count_wikilinks(self.kommune) == 1:
adm_location = utils.q_from_first... | irst positive
# we can leave
return
def set_sagsnr(self):
"""Danish listed buildings case ID (P2783)."""
self.add_statement("listed_building_dk", str(self.sagsnr))
def update_labels(self):
self.add_label("da", utils.remove_markup(self.sagsnavn))
... | self.addresse is always streetname + number.
self.postnr is always zipcode
self.by is always placename.
"""
if self.has_non_empty_attribute("adresse"):
address = self.adresse + " " + self.postnr + " " + self.by
self.add_statement("located_street", address)
... |
"""helpers.py -- supporting routines for PyBlaster project
@Author Ulrich Jansen <ulrich.jansen@rwth-aachen. | de>
"""
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def humansize(nbytes):
if nbytes == 0:
return '0 B'
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' | % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i])
def seconds_to_minutes(nsecs):
if nsecs == 0:
return ""
return "%d:%02d" % (int(nsecs / 60), nsecs % 60)
|
import unittest
from cumulusci.core import template_utils
class TemplateUtils(unittest.TestCase):
def test_string_generator(self):
x = 100
y = template_utils.StringGenerator(lambda: str(x))
assert str(y) == "100"
x = 200
assert str(y) == "200"
def test_faker_library(se... | ame
assert "example.com" in fake.email(domain="example.com")
def test_faker_languages(self):
fake = template_utils.FakerTemplateLibrary("no_NO")
assert fake.first_name
assert "example.com" in fake.email(domain="example.com")
def test_format_str(self):
| assert template_utils.format_str("abc") == "abc"
assert template_utils.format_str("{{abc}}", {"abc": 5}) == "5"
assert len(template_utils.format_str("{{fake.first_name}}"))
assert "15" in template_utils.format_str(
"{{fake.first_name}} {{count}}", {"count": 15}
)
asse... |
"""General tests for Buoyant library."""
import datetime
import unittest
from io import BytesIO
import buoyant
from buoyant import buoy
sampledata = [
{
"latitude (degree)": "39.235",
"sea_surface_wave_peak_period (s)": "13.79",
"polar_coordinate_r1 (1)": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;... | servation(1.0, 'm')"
assert obs + 2 == 3
def test_buoy_instant(self):
assert self.b
assert isinstance(self.b, buoyant.Buoy)
def tes | t_data_exists(self):
x = self.b.sea_water_electrical_conductivity
assert x.unit == "mS/cm"
currents = self.b.currents
self.assertIsInstance(currents, list)
assert isinstance(x.datetime, datetime.datetime)
assert isinstance(self.b.image, BytesIO)
assert isinstance(... |
"Port": config['Incoming/MMTP'].get('Port', 0),
"Nickname": nickname,
"Identity":
formatBase64(mixminion.Crypto.pk_encode_public_key(identityKey)),
"Published": formatTime(now),
"ValidAfter": formatDate(validAt),
"ValidUntil": formatDate(validUntil),
"Pa | cketKey":
formatBase64(mixminion.Crypto.pk_encode_public_key(packetKey)),
"KeyID": identityKeyID,
"MMTPProtocolsIn" : mmtpProtocolsIn,
"MMTPProtocolsOut" : mmtpProtocolsOut,
"PacketVersion" : mixminion.Packet.PACKET_VERSION,
"mm_version" : mixminion.__version__,
... | f fields['IP'] == '0.0.0.0': #XXXX008 remove; not needed since 005.
try:
fields['IP'] = _guessLocalIP()
LOG.warn("No IP configured; guessing %s",fields['IP'])
except IPGuessError, e:
LOG.error("Can't guess IP: %s", str(e))
raise UIError("Can't guess IP: %s... |
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = | models.DateTimeField('date published')
def __unicode__(self): # __unicode__ on Python 2
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_fi... | was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self): #... |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Safari switches).
- quiet - If True, the driver's stdout and stderr is suppressed.
- keep_alive - Whether to configure SafariRemoteConnection to use
HTTP keep-alive. Defaults to Fa... |
"""
self._reuse_service = reuse_service
self.service = Service(executable_path, port=port, quiet=quiet)
if not reuse_service:
self.service.start()
executor = SafariRemoteConnection(remote_server_addr=self.service.service_url,
... |
asks that have no FAILED descendants
self.update(worker_id, {'host': host}, get_work=True)
if assistant:
self.add_worker(worker_id, [('assistant', assistant)])
best_task = None
if current_tasks is not None:
ct_set = set(current_tasks)
for task in sort... | status = max(upstream_status, key=UPSTREAM_SEVERITY_KEY)
upstream_status_table[dep_id] = status
return upstream_status_table[dep_id]
def _serialize_task(self, task_id, include_deps=True, deps=None):
task = self._state.get_task(task_id)
ret = {
'disp... | name': task.pretty_id,
'status': task.status,
'workers': list(task.workers),
'worker_running': task.worker_running,
'time_running': getattr(task, "time_running", None),
'start_time': task.time,
'last_updated': getattr(task, "updated", task.time),
... |
import nose
from nose.plugins.attrib import attr
import logging
import colorguard
import os
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries'))
@attr(speed='slow')
def test_cromu_00070_caching():
# Test exploitation of CROMU_00070 given an input which causes a leak. Th... | ons[f]()
if __name__ == "__main__":
logging.getLogger("colorguard").setLevel("DEBUG")
logging.getLogger("p | ovsim").setLevel("DEBUG")
import sys
if len(sys.argv) > 1:
globals()['test_' + sys.argv[1]]()
else:
run_all()
|
# coding=utf-8
#https://developers.google.com/drive/v3/web/quickstart/python
from __future__ import print_function
import httplib2
import os
import io
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from apiclient.http import MediaIoBaseDownload
from ap... | {}".format(name))
if name == fileToDownload and not list:
credentials = self.get_credentials()
http = credentials.authorize(httpli | b2.Http())
drive_service = discovery.build('drive', 'v3', http=http)
self.download_file(item['id'],"text/plain",item['name'],drive_service)
#drive = GoogleManager()
#drive.init_for_download("weights.h5")
#drive.init_for_download("model.json")
#drive.init_for_upload("more_... |
# -*- coding: utf-8 -*-
#Import libraries
from sys import exit
from math import sqrt
#Print title (http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Equation%20Solver%20V2.1)
print " ____ __ _ ____ __ _ _____ ___"
print " / __/__ ___ _____ _/ /_(_)__ ___ ... | "
#Welcome phrase
print "\nWelcome in the 'Equation Solver' 2.1 by Rafa | el Riber .\nPlease give the values for 'a', 'b' and 'c' as follows: f(x) = Ax^2+Bx+C.\n"
#Define check function
def check(x):
if x != 0:
pass
else:
exit("Invalid value. Please enter only numbers other than zero.")
#Input and check
a = float(input("Value of 'A': "))
check(a)
b = float(input("Value of '... |
"""
sentry_javascript_lite.plugin
~~~~~~~~~~~~~~~~~~~~~
"""
import re
from django.conf import settings
from sentry.lang.javascript.plugin import JavascriptPlugin
from sentry.lang.javascript.processor import SourceProcessor
from sentry.interfaces.stacktrace import (Frame, Stacktrace)
from sentry_javascript_lite import... | mes']) > 0:
| return [Stacktrace(**kwargs)]
return []
def format_chrome_ie_frame(self, frame):
tokens = JavascriptLiteSourceProcessor.chrome_ie_stacktrace_expr.findall(frame)[0]
frame = {
'filename': tokens[1],
'function': tokens[0] or '?',
'in_app': True,
... |
###############################################################################
# This file is part of openWNS (open Wireless Network Simulator)
# _____________________________________________________________________________
#
# Copyright (C) 2004-2007
# Chair of Communication Networks (ComNets)
# Kopernikusstr. 16, D-... | cenarios.interfaces.INodePlacer):
"""
Place a number of nodes on the given positions.
"""
def __init__(self, numberOfNodes = 1, positionsList = [openwns.geometry.position.Position(1,1)], rotate = 0.0):
"""
@type numberOfNodes: int
@param numberOfNodes: | The number of nodes on the circle
@Type: position: float
@param position: distance from BS in Meters for every single node
@type rotate: float
@param rotate: Rotate the final result by rotate in radiant [0..2pi]
"""
self.center = openwns.geometry.position.Position(x =... |
# AsteriskLint -- an Asterisk PBX config syntax checker
# Copyright (C) 2015-2016 Walter Doekes, OSSO B.V.
#
# 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
... | ialplan import DialplanAggregator
from .file import FileReader
from .func_odbc import FuncOdbcAggregator
class FileConfigParser(ConfigAggregator, FileReader):
pass
class FileDialplanParser(DialplanAggregator, FileReader):
pass
class FileFuncOdbcParser(FuncOdbcA | ggregator, FileReader):
pass
|
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | val(3))
self.assertFalse(real.IsGreaterThan(3.0).eval(3.0))
self.assertFalse(real.IsGreaterThan(4.0).eval(3.0))
self.assertFalse(real.IsGreaterThan(4).eval(3))
def test_is_less_than_or_equal_to_rule(self):
rule = real.IsLessThanOrEqualTo(3)
self.assertTrue(rule.eval(2))
... | est_is_greater_than_or_equal_to_rule(self):
rule = real.IsGreaterThanOrEqualTo(3)
self.assertTrue(rule.eval(4))
self.assertTrue(rule.eval(3))
self.assertFalse(rule.eval(2))
def test_is_inclusively_between_rule(self):
with self.assertRaises(AssertionError):
real.... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | ###############################
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('layers', '0002_initi | al_step2'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Upload',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('im... |
# Sample 5
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
print('Failed to create socket!')
print('Error code: ' + str(msg[0]) + ', error message: ' + msg[1])
sys.exit()
print('Socked created successfully.')
# Part 1
host = ''
port = 8888
try:
s.... | e first client that comes
# can type in bash the following to talk to the socket: telnet localhost 8888
# Part 2
data = conn.recv(1024)
if not data:
break
reply = '<<<Hello ' + str(data) + '>>>'
conn.sendall(reply.encode('UTF8'))
# once you start the socket with python sample5.py |
# try telnet localhost 8888 in another terminal
# type test, and it should echo back <<<Hello test>>>
conn.close()
s.close() |
import typing as t
import warnings
from .request import Request
class _FakeSubclassCheck(type):
def __subclasscheck__(cls, subclass: t.Type) -> bool:
warnings.warn(
"'BaseRequest' i | s deprecated and will be removed in"
" Werkzeug 2.1. Use 'issubclass(cls, Request)' instead.",
DeprecationWarning,
stacklevel=2,
)
return issubclass(su | bclass, Request)
def __instancecheck__(cls, instance: t.Any) -> bool:
warnings.warn(
"'BaseRequest' is deprecated and will be removed in"
" Werkzeug 2.1. Use 'isinstance(obj, Request)' instead.",
DeprecationWarning,
stacklevel=2,
)
return isin... |
t_to_32bytearray, big_endian_to_int, ecsign, ecrecover_to_pub, normalize_key
# Reimplemented from ethereum.utils
def sha3(seed):
return sha3_256(to_string(seed))
big_endian_to_int = lambda x: big_endian_int.deserialize(str_to_bytes(x).lstrip(b'\x00'))
is_numeric = lambda x: isinstance(x, int)
def bytearray_to_byte... | 0:
raise InvalidTransaction("Invalid signature values!")
pub = ecrecover_to_pub(sighash, vee, self | .r, self.s)
if pub == b"\x00" * 64:
raise InvalidTransaction("Invalid signature (zero privkey cannot sign)")
self._sender = sha3(pub)[-20:]
return self._sender
@property
def network_id(self):
if self.r == 0 and self.s == 0:
return ... |
# This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | eturn client.call(
messages.OntologyGetPublicKey(address_n=address_n, show_display=show_display)
)
@expect(messages.OntologySignedTransfer)
def sign_transfer(client, address_n, t, | tr):
return client.call(
messages.OntologySignTransfer(address_n=address_n, transaction=t, transfer=tr)
)
@expect(messages.OntologySignedWithdrawOng)
def sign_withdrawal(client, address_n, t, w):
return client.call(
messages.OntologySignWithdrawOng(
address_n=address_n, transac... |
assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any v... | ossibilities for their peers
if twins_list:
for twins in twins_list:
# intersect list of twins' peers for common units
twins_peers = set(peers[twins[0]]).intersection(set(peers[twins[1]]))
for peer in twins_peers:
for v in values[twins[0]]:
... | assign_value(values, peer, values[peer].replace(v,''))
return values
def cross(A, B):
"Cross product of elements in A and elements in B."
return [s+t for s in A for t in B]
def diag(A, B):
"Diagonals of A elements with elements in B."
return [A[r]+B[c] for r in range(len(A)) for c in range(len(B)... |
import click
import pickle
from build import Build
@click.group()
def cli():
pass
@cli.comman | d()
@click.option('--cache-file', default='test-cache')
@click.option('--query')
def query(cache_file, query):
with open(cache_file, 'rb') as f:
key, criteria = query.split('=')
buildobjs = pickle.load(f)
for name, build in buildobjs.items():
item = getattr(build, key, '')
... | cli()
|
from dnfpyUtils.stats.statistic import Statistic
import numpy as np
class Trajectory(Statistic):
"""
Abstract class for trajectory
"""
def __init__(self,name,dt=0.1,dim=0,**kwargs):
super().__init__(name=name,size=0,dim=dim,dt=dt,**kwargs)
self.trace = [] #save the trace
... | reset()
self.trace = []
self._data = np.nan
def getMean(self):
return np.nanmean(self.trace)
def getRMSE(self):
return np.sqrt(np.nanmean(self.trace))
def getCount(self):
return np.sum(~np.isnan(self.trace))
def getMax(self | ):
return np.max(self.trace)
def getPercentile(self,percent):
return np.nanpercentile(self.trace,percent)
def getMin(self):
return np.min(self.trace)
def getStd(self):
return np.std(self.trace)
def getTrace(self):
"""
Return the time trace of t... |
ctName("addAxialAction")
self.addCoronalAction = QtGui.QAction(self)
self.addCoronalAction.setText(QtGui.QApplication.translate("MWindow",
"Coronal",
None,
... | ]
mscreen.createScene(VtkImagePlane.PLANE_ORIENTATION_CORONAL)
elif result == self.addSagittalAction:
mscreen = self._mScreens[self.currentIndex()]
mscreen.createScene(VtkImagePlane.PLANE_O | RIENTATION_SAGITTAL)
elif result == self.addVolumeAction:
mscreen = self._mScreens[self.currentIndex()]
mscreen.createScene(VtkImagePlane.PLANE_ORIENTATION_VOLUME)
def updateWidgets(self):
logging.debug("In MWindow::updateWidgets()")
self.setT... |
make_consistencygroup(root)
alias = Consistencygroups.alias
namespace = Consistencygroups.namespace
return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace})
class ConsistencyGroupsTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('co... | nsistencygroup-from-sr | c')
make_consistencygroup_from_src(root)
alias = Consistencygroups.alias
namespace = Consistencygroups.namespace
return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace})
class CreateDeserializer(wsgi.MetadataXMLDeserializer):
def default(self, string):
dom = utils.s... |
import unittest
from restkiss.preparers import Preparer, FieldsPreparer
class InstaObj(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class LookupDataTestCase(unittest.TestCase):
def setUp(self):
super(LookupDataTestCase, self).setUp()
... | arent.id', self.dict_data), None)
def test_obj_nullable_fk(self):
self.assertEqual(self.preparer.lookup_data('parent.id', | self.obj_data), None)
def test_empty_lookup(self):
# We could possibly get here in the recursion.
self.assertEqual(self.preparer.lookup_data('', 'Last value'), 'Last value')
def test_complex_miss(self):
with self.assertRaises(AttributeError):
self.preparer.lookup_data('more... |
from huzzer.function_generator import generate_expression, generate_unary_expr
from huzzer.expressions import VariableExpression, FunctionExpression, BRANCH_EXPRESSIONS
from huzzer.namers import DefaultNamer
from huzzer import INT, BOOL
empty_variables = {
INT: [],
BOOL: []
}
def test_generate_unary_expr():
... | ons,
BRANCH_EXPRESSIONS,
2,
branching_probability=1.0,
function_call_probability=1.0,
variable_probability=1.0
)
assert type(func_expr_with_only_vars) == type(bool_function) and \
all([ar | g is bool_variable for arg in func_expr_with_only_vars.args])
|
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MOD | ULE', 'persephone.settings')
app = Celery('persephone')
app.config_fr | om_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
|
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 you... | version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public Lice... | 01 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
import re
from ...const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#---------------------------------------... |
import numpy as np
from . import _marching_cubes_cy
def marching_cubes(volume, level, spacing=(1., 1., 1.)):
"""
Marching cubes algorithm to find iso-valued surfaces in 3d volumetric data
Parameters
----------
volume : (M, N, P) array of doubles
Input data volume to find isosurfaces. Will... | # Fancy indexing to define two vector arrays from triangle vertices
actual_verts = verts[tris]
a = actual_verts[:, 0, :] - actual_verts[:, 1, :]
b = actual_verts[:, 0, :] - actual_verts[:, 2, :]
del actual_verts
# Area of triangle in 3D = 1/2 * Euclidean norm of cross product
return ((np.cross... | sum(axis=1) ** 0.5).sum() / 2.
|
#!/bin/false
# -*- coding: utf-8 -*-
from objects.orobject import OrObject
from objects.function import Function
from objects.number import Number
from objects.file import File
from objects.inheritdict import InheritDict
from objects.ordict import OrDict
from objects.orddict import ODict
import objects.console as cons... | output": expose(console.output | ),
"error": expose(console.error),
"endl": expose("\n"),
"repr": expose(repr),
"join": expose(libbuiltin.join),
"range": expose(range),
"type": expose(libbuiltin.typeof, "type"),
"dir": expose(libbuiltin.dirof, "dir"),
"attrs": expose(libbuiltin.attrsof, "attrs"),
"reverse": expose... |
from django.contrib.auth import update_session_auth_hash
from rest_framework import serializers
from authentication.models import Account
class AccountSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=False)
confirm_password = serializers.CharField(write_onl... | instance.username)
instance.tagline = validated_data.get('tagline', instance.tagline)
instance.save()
password = validated_data.get('password', None)
confirm_password = validated_data.get('confirm_password', None)
if password and confirm_password and password == confirm_passwo... | sword(password)
instance.save()
update_session_auth_hash(self.context.get('request'), instance)
return instance
class SimpleAccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'email', 'username',)
|
#!/usr/bin/python
# coding=utf-8
# Simple Steam profile checker Telegram bot
# Copyright (c) 2017 EasyCoding Team
#
# 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 Licen... | am. If not, see <http:// | www.gnu.org/licenses/>.
from html import unescape
from re import sub
from urllib.request import Request as request, urlopen
from xml.dom import minidom
class SteamChecker:
@staticmethod
def striptags(gtstr, gtrep=''):
"""
Strip HTML tags from string.
:param gtstr: String to strip tags... |
# -*- coding: utf-8 -*-
""" Tablib - JSON Support
"""
import tablib
import sys
from tablib.packages import omnijson as json
title = 'json'
extentions = ('json', 'jsn')
def export_set(dataset):
"""Returns JSON representation of Dataset."""
return json.dumps(dataset.dict)
def export_book(databook):
"... | turn json.dumps(databook._package())
def import_set(dset, in_stream):
"""Returns dataset from JSON stream."""
dset.wipe()
dset.dict = json.loads(in | _stream)
def import_book(dbook, in_stream):
"""Returns databook from JSON stream."""
dbook.wipe()
for sheet in json.loads(in_stream):
data = tablib.Dataset()
data.title = sheet['title']
data.dict = sheet['data']
dbook.add_sheet(data)
def detect(stream):
"""Returns Tr... |
ef nest_update_event_broker(hass, nest):
"""
Dispatch SIGNAL_NEST_UPDATE to devices when nest stream API received data.
Runs in its own thread.
"""
_LOGGER.debug("Listening for nest.update_event")
while hass.is_running:
nest.update_event.wait()
if not hass.is_running:
... | break
nest.update_event.clear()
_LOGGER.debug("Dispatching nest data update")
dispatcher_send(hass, SIGNAL_NEST_UPDATE)
_LOGGER.debug("Stop listening for nest.update_event")
async def async_setup(hass, config):
"""Set up Nest components."""
if DOMAIN not in config: |
return True
conf = config[DOMAIN]
local_auth.initialize(hass, conf[CONF_CLIENT_ID], conf[CONF_CLIENT_SECRET])
filename = config.get(CONF_FILENAME, NEST_CONFIG_FILE)
access_token_cache_file = hass.config.path(filename)
hass.async_create_task(
hass.config_entries.flow.async_init(
... |
# -*- coding: ut | f-8 -*-
import os
import django
from .fixtures import * # noqa
# import pytest
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
def pytest_configure(config):
django.setup() | |
#!/usr/bin/env python
#
# Copyright 2014 (c) Lei Xu <eddyxu@gmail.com>
#
# 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 ... | uage governing permissions and
# limitations under the License.
from | fabric.api import task
import yaml
import logging
import vsfs_ec2 as ec2
vsfs = ec2.VsfsEC2()
logging.basicConfig(format='[%(asctime)s](%(levelname)s) %(message)s',
level=logging.INFO)
@task
def help(name=''):
"""Print full information of the function. (name='task')
"""
if not name:... |
"""
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_... | label')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_s | et='train', label_type='azimuth')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert 0.0 <= train_y.y.max() <= 1.0
assert 0.0 <= train_y.y.min() <= 1.0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='rotation')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.